id
stringlengths 40
40
| text
stringlengths 9
86.7k
| metadata
stringlengths 3k
16.2k
| source
stringclasses 1
value | added
stringdate 2024-11-21 00:00:00
2024-12-12 00:00:00
| created
stringdate 2024-11-21 00:00:00
2024-12-12 00:00:00
|
|---|---|---|---|---|---|
cd132695ec2f8e0ef81e8362d613f94f2c399f96
|
Coloured cause-effect structures
Alexander P. Ustimenko
We present an extension of the class of cause-effect structures by coloured tokens. As an example of coloured c-e structure we use the well-known problem of dining philosophers. Relationships between the classes of coloured c-e structures and coloured Petri Nets introduced by K. Jensen are investigated.
Introduction
In order to describe concurrent systems, L.Czaja in [1] has introduced cause-effect structures (CESs) inspired by condition/event Petri nets (PNs). CES can be defined as a triple \((X, C, E)\) where \(X\) is the set of nodes, \(C\) and \(E\) are the cause and effect functions from \(X\) to the set of formal polynomials over \(X\) such that \(x \in X\) occurs in \(C(y)\) iff \(y\) occurs in \(E(x)\). Each polynomial \(C(x)\) \((E(x))\) denotes a family of cause (effect) subsets of the node \(x\). The operator \(\ast\) combines nodes into subsets, and the operator \(+\) combines subsets into families.
Section 1 contains the basic definitions of the structure and behaviour of CESs.
There is an interesting question about the relationships between CESs and PNs. In [5] Raczunas states that every CES has strongly equivalent PN, i.e., two bijections exist: between the so-called firing components of CES and the transitions of PN, and between the nodes of CES and the places of PN; moreover, the bijections must preserve pre- and postsets of firing components and transitions. Raczunas investigated the converse mapping from PNs to CESs. He remarked that a strong equivalence is not the case for converse mapping. So he defines an equivalence relation between the places in PNs and, similarly, in CESs, as a coincidence of the presets of equivalent places as well as their postsets. Then he introduced an (ordinary) equivalence between PNs and CESs by means of weakening the requirement of bijective correspondence between places down to bijective correspondence between equivalent classes of places. But the issue remained open: to find a subclass of PNs or an extension of the class of CESs such that the strong equivalence will take place.
We have decided this problem in [7] by introducing an extension of cause-effect structures — two-level CESs (TCEs). TCEs are a convenient intermediate class between PNs and CESs, because they are strongly equivalent
to the class of PNs and we can transform any TCES into structurally equivalent CES with the help of folding-transformation. On the other hand, each CES has a strongly equivalent TCES.
Unfortunately, an expressive power of CESs is not sufficient for using them in real-life applications. Some supplementary constructions are necessary. Then the problem is to extend the obtained results to CESs with time and/or coloured nodes or to other high-level semantics of CESs. Note that the extension with time for CESs has been received in [2], and the relationship between time CESs and time PNs has been investigated in [6].
In ordinary CESs, a token or an active state of a node represents the presence of control and/or some resource in it. But it does not signify a qualitative difference between resources functioning in the CES. Moreover, each node should not have more than one token-resource at the same time. In some cases it is important to distinguish the resources qualitatively. This difference is represented by colours of tokens. Moreover, each node can have more than one differently coloured token.
This work is devoted to construction of the class of coloured CESs (CCESs). There are different ways of introducing the semantics of coloured tokens in CESs. We choose one of them that strictly correlates with the semantics of coloured tokens in Petri nets ([3]).
Then we give an algorithm of mapping of CCESs into CPNs. The correctness of this mapping is established. An example of running the algorithm to solve the problem of n dining philosophers is considered. The problem of the converse mapping from coloured PNs into CCESs is decided with the help of the class of two-level CESs.
1. Cause-effect structures
Cause-effect structures are represented as directed graphs with an additional structure imposed on the set of nodes. These graphs with operations \(+\) and \(*\), corresponding to nondeterministic choice and parallelism, constitute a near-semi-ring where "near" means that distributivity of \(*\) over \(+\) holds conditionally. Fig.1 presents a simple example of CES (with arrows annotated by some executable statements and conditions) representing a parallel program that computes a sum of natural numbers \(x\) and \(y\) by adding and subtracting 1 and testing for 0.
A CES is completely represented by the set of annotated nodes: each node \(x\) is subscribed by a formal polynomial \(E(x)\) built of (the names of) its successors and superscribed by a formal polynomial \(C(x)\) built of its predecessors; it may be either in an active or passive state. If a CES, like in the example, represents a program, then the active state of a node means the presence of control in it and its readiness for execution of statements assigned...
to outgoing arcs. We should note that the statements and conditions on arcs are used only with illustrative goals and they are absent in "real" CESs.
If a node is active, then we try to move control from it simultaneously to all its successors which form a product in its lower (subscript) polynomial — if they are passive. Symmetrically, if a node is passive, then we try to move control to it simultaneously from all its predecessors which form a product of its upper (superscript) polynomial — if they are active (if no predecessors or successors exist, then the upper or lower polynomial is $\emptyset$, sometimes omitted). This rule generally gives complex interdependences between nodes in the aspect of control flow: a group of nodes must "negotiate" the possibility of changing their state with each other. Such groups of nodes will play a role analogous to that of transitions in PNs. They are called firing components. The set of all firing components of the CES $\mathcal{U}$ is denoted by $FC[\mathcal{U}]$.
Let us introduce these notions more formally.
**Definition 1.1.** Let $X$ be a set called a space of nodes and let $\theta$ be a symbol called neutral. The least set $Y$ such that
\begin{align*}
\theta & \in Y, \\
X & \subseteq Y,
\end{align*}
if $K \in Y$ and $L \in Y$, then $(K + L) \in Y$ and $(K + L) \in Y$
is a set of polynomials over $X$ denoted by $F[X]$.
**Definition 1.2.** We say that the algebraic system $A = (F[X], +, *, \theta)$ is a near-semi-ring of polynomials over $X$ if the following axioms hold for all $K \in F[X], L \in F[X], M \in F[X], x \in X$:
\begin{align*}
(+) & \quad \theta + K = K + \theta = K \\
(++) & \quad K + K = K \\
(++++) & \quad K + L = L + K \\
(*) & \quad \theta * K = K * \theta = K \\
(* *) & \quad z * x = x \\
(* * *) & \quad K * L = L * K
\end{align*}
(+++++) $K + (L + M) = (K + L) + M$ (****) $K * (L * M) = (K * L) * M$
(+*) $K * (L + M) = K * L + K * M$
provided that either $L = M = \emptyset$ or $L \neq \emptyset$ and $M \neq \emptyset$
**Definition 1.3.** Let $X$ be a space of nodes and $(F[X], +, *, \theta)$ be a near-semi-ring of polynomials. A CES over $X$ is a pair $(C, E)$ of functions:
$C : X \rightarrow F[X]$ (cause function)
$E : X \rightarrow F[X]$ (effect function)
such that $x$ occurs in the polynomial $C(y)$ iff $y$ occurs in $E(x)$ (then $x$ is a cause of $y$ and $y$ is an effect of $x$). The set of all CESs over $X$ is denoted by $CE[X]$.
The CES is completely represented by the set of annotated nodes $x$.
**Definition 1.4.** Let us define addition and multiplication of functions by $(C1 + C2)(x) = C1(x) + C2(x)$, $(C1 * C2)(x) = C1(x) * C2(x)$, then an algebra of CES is obtained as follows. Let $\theta : X \rightarrow F[X]$ be a constant function $\theta(x) = \theta$, let, for brevity, the CES $(\theta, \theta)$ be denoted by $\theta$, and let $+$ and $*$ on CES be defined by
$$(C1, E1) + (C2, E2) = (C1 + C2, E1 + E2)$$
$$(C1, E1) * (C2, E2) = (C1 * C2, E1 * E2)$$
Obviously, if $Ui = (Ci, Ei) \in CE[X](i = 1, 2)$, then $U1 + U2 \in CE[X]$ and $U1 * U2 \in CE[X]$, that is, in the resulting structure, $x$ is a cause of $y$ iff $y$ is an effect of $x$.
**Definition 1.5.** A CES $U$ is decomposable iff there are CESs $V$ and $W$ such that $\theta \neq V \neq U, \theta \neq W \neq U$ and either $U = V + W$ or $U = V * W$.
**Definition 1.6.** Let $U$ and $V$ be CESs. $V$ is a substructure of $U$ iff $V + U = U$. Then we write $V \leq U$. $SUB[U] = \{V : V \leq U\}$. Easy checking ensures that $\leq$ is a partial order. The set of all minimal (wrt $\leq$) and not equal to $\theta$ elements of $SUB[U]$ is denoted by $MIN[U]$.
**Definition 1.7.** For a CES $U$, let $Q = (C_Q, E_Q)$ be a minimal substructure of $U$ such that for every node $x$ in $Q$:
(i) polynomials $C_Q(x)$ and $E_Q(x)$ do not comprise '+',
(ii) exactly one polynomial, either $C_Q(x)$ or $E_Q(x)$, is $\theta$.
Then, $Q$ is called a firing component of $U$. A set of firing components is denoted by $FC[U] = \{Q \in MIN[U] : (i), (ii) hold\}$. We denote by $FC[U]^*$ a set of all finite strings over $FC[U]$, an empty string including. We denote by $^*Q$ the set of nodes $x$ in $Q$ with $C_Q(x) = \theta$, and we denote by $Q^*$ the set of nodes $x$ in $Q$ with $E_Q(x) = \theta$.
Definition 1.8. A state $s$ is a subset of the space of nodes $X$. A node $x$ is active in the state $s$ iff $x \in s$, and it is passive, otherwise.
Definition 1.9. For $Q \in FC[U]$, let $[[Q]]$ denote a binary relation in the set of all states: $(s, t) \in [[Q]]$ iff $Q \subseteq s, Q \cap s = \emptyset, t = (s - Q) \cup Q^*$. The semantics $[[U]]$ of a CES $U$ is a union of relations:
$$[[U]] = \bigcup_{Q \in FC[U]} [[Q]]$$
The semantics $[[U]]^*$ of $U$ is a transitive extension of $[[U]]$.
Definition 1.10. A CES $U$ is a structural deadlock iff $FC[U] = \emptyset$, i.e., $U$ cannot change its state, regardless of the state.
2. Cause-effect structures with coloured tokens
In this section we suggest an extension of the set of CESs by semantics of coloured tokens. Each node of a coloured CES (briefly CCES) may have more than one token simultaneously iff all colours of its tokens are different.
A CCES, as well as CES, is completely represented by the set of annotated nodes. But its formal polynomials range over the extended set of pairs — $<\text{node, colour}>$. Moreover, each its polynomial is 'coloured', that is, each its monomial is associated with some colour-label. For instance, the record
$$\{x^{1<a,2>}, b^{1<1>}, +2^{a,3>, a_2^{<x,1>}, +3^{<x,2>, b_1^{<x,1>}}\}$$
means that:
- the node $x$ can receive a token of colour 1 simultaneously from the nodes $a$ and $b$ (if $a$ has a token of colour 2, $b$ has that of colour 1) or a token of colour 2 from the node $c$ (if it has a token of colour 1);
- symmetrically, the node $a$ can send a token of colour 2 or colour 3 to the node $x$, but $x$ will receive this token repaint in colours 1 or 2, respectively (the first case demands synchronization with the node $b$ iff it has a token of colour 1).
Thus, cause and effect functions in CCESs reflect the space of nodes $X$ not in the set of polynomials $F[X]$, as it is in CESs, but in the set of polynomials coloured by a special function $Cl \times F[X_C]$. According to these remarks, all formal definitions of CCESs are the same as those for CESs.
Moreover, a CCES can be seen as a CES over an extended space of nodes (of pairs $<\text{node, colour}>$). It allows us to introduce such high-level semantics as coloured tokens in a very simple manner. Let us introduce these notions more formally.
Definition 2.1. Let $X$ be a set called a space of nodes and let $Cl = [1..n]$ be a set of colours. Then an extended set $X_C = \{<x, i> \mid x \in X, i \in Cl\}$ is called a space of coloured nodes.
**Definition 2.2.** Let $X_C$ be a space of coloured nodes and let $\theta$ be a symbol called neutral. The least set $Y$ which satisfies the following conditions:
$\theta \in Y, X_C \subseteq Y,$
if $K \in Y$ and $L \in Y$, then $(K + L) \in Y$ and $(K + L) \in Y,$
is called a set of polynomials over $X_C$ and denoted by $F[X_C].$
**Definition 2.3.** We say that the algebraic system $A = (F[X_C], +, *, \theta)$ is a near-semi-ring of polynomials over $X_C$ if the axioms from Definition 1.2 hold for all $K \in F[X_C], L \in F[X_C], M \in F[X_C], x \in X_C.$
**Definition 2.4.** Let $P \in F[X_C]$ and its canonical form be $\sum M_i$, where $M_i$ is a monomial. The product of two sets $CI \times F[X_C]$ is a set of 'coloured' polynomials $\{\sum l_i M_i\}$, where $l_i$ is an arbitrary colour, some of which may be identical. Moreover, each monomial $M_i$ may be 'coloured', that is, $M_i = M_i^1 \cdot l_i^2 M_i^2 \cdot \ldots \cdot l_i^n M_i^n$, where monomials $M_i^k$ are arbitrary components of $M_i$ ('arbitrary', because decomposition of $M_i$ into components can be made in different ways).
**Definition 2.5.** Let $X_C$ be a space of coloured nodes and $(F[X_C], +, *, \theta)$ be a near-semi-ring of polynomials. A coloured CES (CCES) over $X$ is a pair $(C, E)$ of functions:
$C : X \rightarrow CI \times F[X_C]$ (cause function),
$E : X \rightarrow CI \times F[X_C]$ (effect function),
such that $\langle x, i \rangle$ occurs in the monomial $jC^i(y)$ from $C(y) = \sum jC^i(y)$ if $\langle y, j \rangle$ occurs in $iE^i(x)$ from $E(x)$ (then $\langle x, i \rangle$ is a cause of $\langle y, j \rangle$ and $\langle y, j \rangle$ is an effect of $\langle x, i \rangle$). The set of all CCESs over $X$ is denoted by $CCE[X].$ The CES is completely represented by the set of annotated nodes.
**Definition 2.6.** Addition and multiplication of cause functions are defined by:
$(C_1 + C_2)(x) = C_1(x) + C_2(x);$
$(C_1 \cdot C_2)(x) = C_1(x) \cdot C_2(x).$
They are the same for effect functions. Then an algebra of CCESs is obtained as follows. Let $\Theta : X \rightarrow F[X_C]$ be a constant function $\Theta(x) = \Theta$, for brevity, let the CES $(\Theta, \Theta)$ be denoted by $\Theta$, and let $+$ and $\cdot$ on CES be defined by:
$(C_1, E_1) + (C_2, E_2) = (C_1 + C_2, E_1 + E_2),$
$(C_1, E_1) \cdot (C_2, E_2) = (C_1 \cdot C_2, E_1 \cdot E_2).$
Obviously, if $U_i = (C_i, E_i) \in CCE[X](i = 1, 2)$, then $U_1 + U_2 \in CCE[X]$ and $U_1 \cdot U_2 \in CCE[X].$
**Definition 2.7.** A CCES $U$ is decomposable iff there are CCESs $V$ and $W$ such that $\Theta \neq V \neq U, \Theta \neq W \neq U$ and either $U = V + W$ or $U = V \cdot W.$
Definition 2.8. Let $U$ and $V$ be CCESs. $V$ is a substructure of $U$ iff $V + U = U$. Then we write $V \leq U$. $\text{SUB}[U] = \{V | V \leq U\}$. Easy checking ensures that $\leq$ is a partial order. The set of all minimal (wrt $\leq$) and $\not= \emptyset$ elements of $\text{SUB}[U]$ is denoted by $\text{MIN}[U]$.
Definition 2.9. For a CCES $U$, let $Q = (C_Q, E_Q)$ be a minimal substructure of $U$ such that for every node $x \in Q$:
(i) polynomials $C_Q(x), E_Q(x)$ do not comprise $+$,
(ii) exactly one polynomial, either $C_Q(x)$ or $E_Q(x)$, is $\emptyset$.
Then $Q$ is called a firing component of $U$. A set of firing components is denoted by $\text{FC}[U] = \{Q \in \text{MIN}[U]|(i)$ and $(ii)$ hold}. We denote by $^*Q$ the set of pairs $\{< x, i > | x_{iE_Q(x)} \in Q \}$, and we denote by $Q^*$ the set of pairs $\{< y, j > | y_{jC_Q(y)} \in Q \}$.
Remark 1. The set of firing components of a CCES may have groups of firing components whose sets of input and output nodes are identical but have tokens of different colours. Each such a group is analogous to some transition in a coloured PN, and each firing component of such a group is analogous to a binding from the set of all bindings of this transition. Thus, the set of firing components breaks down into groups of equivalent components.
Definition 2.10. A state $s$ is a subset of the space of coloured nodes $X_C$. A node $x$ is active in the state $s$ iff $\exists i \in Cl : < x, i > \in s$, and it is passive otherwise.
$s(x) = \{i | < x, i > \in s \}$.
Definition 2.11. For $Q \in \text{FC}[U]$, let $[Q]_C$ denote a binary relation in the set of all states:
$(s, t) \in [Q]_C$ iff $^*Q \subseteq s, Q^* \cap s = \emptyset, t = (s - ^*Q) \cup Q^*$.
The semantics $[U]_C$ of a CCES $U$ is a union of relations:
$[U]_C = \bigcup_{Q \in \text{FC}[U]} [Q]_C$.
Example 1. As an example of a CCES, we use the well-known dining philosophers' system. The philosophers' structure is given in Fig. 2. The nodes of the structure are $X = \{I(\text{idle}), L(\text{hasLeft}), E(\text{eating}), R(\text{hasRight}), F(\text{freeForks})\}$. There are $n$ colours according to the number of philosophers. There are four groups of equivalent firing components:
$Q_i^1 = \{< I, i >, < F, i > \} \cup \{< L, i > \}$ — the $i$-th philosopher takes his left fork iff he is idle and a necessary fork is free;
$Q_i^2 = \{< L, i >, < F, [i + 1] > \} \cup \{< E, i > \}$ — the $i$-th philosopher takes his right fork and begins to eat;
$Q^3_i = \{ < E, i > \} \cup \{ < R, i >, < F, i > \}$ — the $i$-th philosopher finishes eating and returns his left fork to freeForks;
$Q^4_i = \{ < R, i > \} \cup \{ < I, i >, < F, [i+1] > \}$ — the $i$-th philosopher returns his right fork and stays idle.
The initial state of this CCES is $s_0 = \{ < I, 1 >, ..., < I, n >, < F, 1 >, ..., < F, n > \}$.

Here $C(I) = \sum_i i < R, i >, E(I) = \sum_i i < L, i >$;
$C(L) = \sum_i i < I, i > \ast < F, i >, E(L) = \sum_i i < E, i >$;
$C(E) = \sum_i i < L, i > \ast < F, [i+1] >, E(E) = \sum_i i < R, i > \ast < F, i >$;
$C(R) = \sum_i i < E, i >, E(R) = \sum_i i < I, i > \ast < F, [i+1] >$;
$C(F) = \sum_i i (< E, i > + < R, [i-1] >),$
$E(F) = \sum_i i (< L, i > + < E, [i-1] >),$
where $i = 1, ..., n$.
One can note that an expressive power of this semantics is greater than Example 1 demonstrates. The semantics of coloured tokens allows each node to send or to receive more than one token simultaneously. This fact is denoted by presenting more than one colour-labels in some monomial of effect or, respectively, cause polynomial. For instance, this example can be simplified as follows:
$$\{ I \sum_i i < E, i >, L \sum_i i < I, i > \ast < F, i >, E \sum_i i < L, i > \ast < F, [i+1] >, F \sum_i i < E, i > \ast [i+1] \ast < E, i > \}$$
where $i = 1, ..., n$.
That is, a node $R$ is reduced and two groups of equivalent firing components $Q^3$ and $Q^4$ are replaced by the one:
$Q^3 = \{ < E, i > \} \cup \{ < I, i >, < F, i >, < F, [i+1] > \}$ — the $i$-th philosopher finishes eating and returns simultaneously both his forks to freeForks.
3. Relationships between CCEs and CPNs
3.1. Coloured Petri nets
CPNs were defined in [3]. In order to avoid unnecessary technical difficulties, we present here a definition of a CPN which is slightly different from that given in [3]. The differences are not essential but they help us to make this presentation simpler.
A CPN consists of the following components:
* $P$, a finite set of places.
* $T$, a finite set of transitions such that $P \cap T = \emptyset$.
* $A \subseteq P \times T \cup T \times P$, the set of arcs. As for P/T-nets, we define $t^* = \{ p \in P | (p, t) \in A \}$,
$t^* = \{ p \in P | (t, p) \in A \}$, $p^* = \{ t \in T | (p, t) \in A \}$.
* Each $p \in P$ has an associated non-empty set $C(p)$ of token colours.
* A marking $M$ is a function which assigns a value $M(p, c)$ which is equal to 0 or 1 to each $p \in P$ and each $c \in C(p)$. That is, the set $M(p)$ denotes colours of tokens in the place $p$.
* The initial marking $M_0$ is a distinguished marking. It represents the initial state of the net.
* Each $t \in T$ has an associated non-empty set $B(t)$ of bindings of $t$. Each binding is some variant of firing of the transition $t$.
* Each $a \in A$ such that $a = (p, t)$ or $a = (t, p)$, where $p \in P$ and $t \in T$, has an associated arc expression $W(a)$. The arc expression is a function from $B(t)$ to $\{0, 1\}^{C(p)}$. That is, given a binding $b$, the arc expression produces integer $W(a)(b)(c) \in \{0, 1\}$ for each $c \in C(p)$. The arc expression denotes what subset of coloured tokens is taken from or produced for $p$ when $t$ occurs with the binding $b$.
The dynamics of CPN is defined as follows:
* Let $t \in T$ and $b \in B(t)$. Thus, $t$ is enabled in a marking $M$ for a binding $b$ denoted by $M[(t, b)] >$ if and only if
$\forall p \in T : \forall c \in C(p) : M(p, c) \geq W(p, t)(b)(c)$,
That is, every input place $p$ of $t$ contains at least those coloured tokens which are required by the corresponding arc expression $E(a)$ for the binding $b$ in question.
* If $M[(t, b)] >$, then $t$ may occur with the binding $b$ producing a new marking $M'$ such that
$\forall p \in P : M'(p) = (M(p) - W(p, t)(b)) \cup W(t, p)(b)$.
3.2. Algorithm of mapping CCESs into CPNs
Let us consider CCES
\[ U = \{ x \sum_{i}^{iC(x)} \sum_{i}^{iB(s)} | x \in X \} \]
(1)
with an initial marking \( S_0 \subseteq X_C \) and with a set of colours \( C_l \). Let the set \( FC[U] \) break down into groups of equivalent firing components
\[ FC[U] = \{ Q^i | i = 1, \ldots, n \} \]
(2)
Since all firing components of such a group have identical sets of input and output nodes, we can define the sets of input and output nodes for each group \( Q_i \) as follows:
- \( *Q^i = \{ x | x \in car[U] \subset X \} \);
- \( Q^*= \{ y | y \in Q^i, Q \in Q^i \}, \)
where \( Q \in Q^i \) is arbitrary.
Then the strongly equivalent CPN \( N \) for \( U \) will be constructed as follows:
- \( P = \{ x | x \in car[U] \subset X \} \) is a set of places;
- \( T = \{ t_i \}_{i=1}^n \) is a set of transitions, where \( n \) is equal to the number of groups of equivalent firing components;
- \( A \subseteq P \times T \cup T \times P : A = \bigcup_{i=1}^n ( \bigcup_{j \in *Q^i} \{ (x_j, t_i) \} \cup \{ (t_i, y_k) \} ) \) is a set of arcs;
- \( \forall p \in P : C(p) = Cl; \)
- the initial marking: \( \forall x \in P : M_0(x) = S_0(x); \)
- \( \forall t_i \in T : \) the number of bindings in \( B(t_i) \) is equal to the number of equivalent firing components in \( Q^i \), i.e. \( \forall b \in B(t_i) : \exists ! Q_b \in Q^i; \)
- \( \forall p \in t^* : W(t, p)(b) = Cl^+(p, Q_b), \forall p \in t^* : W(p, t)(b) = Cl^-(p, Q_b), \)
where
\[ Cl^+(p, Q_b) = \{ i | p, i \in *Q^b \} \]
\[ Cl^-(p, Q_b) = \{ i | p, i \in *Q^b \} \]
We need to redefine the notion of a strong equivalence (see [4]) for the case of the coloured token semantics:
**Definition 3.1.** CCES \( U = (X_C, FC[U]) \) and
CPN \( N = (P, T, A, C(P), B(T), W(A, B(T))) \) are strongly equivalent iff there exist two bijections \( f : FC[U] \rightarrow T \times B(T) \) and \( g : X_C \rightarrow P \times C(P) \) such that \( g(\star Q) = \star f(Q) \) and \( g(Q^*) = f^*(Q) \) for any \( Q \in FC[U]. \)
**Theorem 1.** The algorithm constructed above builds a strongly equivalent CPN for any CCES.
**Proof.** Let us consider CCES in the form (1), with a set of firing components in the form (2). The algorithm gives rise to two bijections $f$ and $g$:
$$\forall \langle x, c \rangle \in X_C : g(\langle x, c \rangle) = (x, c).$$
$$\forall i = 1, \ldots, n : f : Q^i \longrightarrow t_i \times B(t_i),$$
such that each firing component $Q \in Q^i$ has an associated unique index, a binding $b$ from $B(t_i)$, i.e. $f(Q^i_b) = (t_i, b)$.
By construction of the bijections $f$ and $g$, we have:
$$g(Q^i_b) = \{(x, c) | \langle x, c \rangle \in Q^i_b\} = \{(x, c) | x \in t_i, c \in W(x, t_i)(b)\} =$$
$$\star(t_i, b) = f(Q^i_b);$$
$$g(Q^i_b) = \{(y, c) | \langle y, c \rangle \in Q^i_b\} = \{(y, c) | y \in t_i, c \in W(t_i, y)(b)\} =$$
$$(t_i, b) = f^*(Q^i_b),$$
i.e. the conditions of the definition of a strong equivalence hold.
**Example 2.** Let us consider the CCES from Example 1. The algorithm will construct the following CPN:
- $P = \{I, L, E, R, F\};$
- $T = \{t_i\}_{i=1}^4;$
- * the arcs, for instance, for the transition $t_1$ are as follows:
$$A(t_1) = \bigcup_{y_i \in Q^i} \{\langle x_j, t_1 \rangle \} \bigcup \{\langle t_1, y_k \rangle \} = \{(I, t_1), (F, t_1)\} \bigcup \{(t_1, L)\};$$
- $\forall p \in P : C(p) = \{1, \ldots, n\};$
- * the initial marking is as follows: $M_0(I) = \{1, \ldots, n\} = M_0(F)$, i.e. $n$ coloured tokens-philosophers are in the place $I$ and $n$ coloured tokens-forks are in the place $F$;
- * each $t_i \in T$ has $n$ bindings in $B(t_i)$;
- * for instance, $W(L, t_2)(b) = W(t_2, E)(b) = [W(F, t_2)(b) - 1]$ for any $b \in B(t_2)$, i.e. any philosopher $b$ which has his left fork (with the same number $b$) may take his right fork (with the number $b$ plus 1 over mod $n$) and move to the state 'Eating'.
We can see the resulting CPN in Fig.3.
4. A converse mapping from CPNs to CCESs
The problem is whether a converse mapping from CPNs to CCESs is possible in the sense of a strong equivalence. As Raczunas has shown in [5] for ordinary classes of PNs and CESs, the strong equivalence does not hold for converse mapping.
In [7] a two-level extension of CESs (TCESs) has been introduced. Any CES is completely represented by the set of annotated nodes $\{x_{E(x)}^{C(x)}\}$, where $E(x)$ and $C(x)$ are polynomials with operations $+$ and $\ast$. We propose to exclude the operation $+$ from formal polynomials, and by resulted elementary CES (or unalternative CES – UCES) we mean a two-level CES of the first syntactical level. Elementary CESs are united by the operation $\oplus$ into the
set called a two-level CES of the second syntactical level, or simply TCES. Thus, TCES is a set of the sets of annotated nodes.
So the operation $\oplus$ is a union of the sets of the upper level. It differs from the operation $+$ because it does not merge elementary CESs into a set of annotated nodes.
An operation $\otimes$ on the set of TCESs is the Cartesian product of the sets of the upper level. On the set of UCESs, the operation $\otimes$ is the same as the operation $*$ on the set of CESs.
A TCES in its canonical form is a sum of its firing components. Let us introduce the above notions more formally:
**Definition 4.1.** Let $X$ be a set called a space of nodes and let $\theta$ be a symbol called neutral. The least set $Y$ satisfying the following conditions:
- $\theta \in Y, X \subseteq Y$;
- if $K \in Y$ and $L \in Y$ then $(K * L) \in Y$,
is called a set of monomials over $X$ and denoted by $M[X]$.
**Definition 4.2.** An algebraic system $A = (M[X], *, \theta)$ is a semi-group of monomials over $X$ if the following axioms hold for all $K \in M[X], L \in M[X], M \in M[X], x \in X$:
- $(\ast) \quad \theta * K = K * \theta = K$
- $(\ast \ast) \quad x * x = x$
- $(\ast \ast \ast) \quad K * L = L * K$
- $(\ast \ast \ast \ast) \quad K * (L * M) = (K * L) * M$
**Definition 4.3.** Let $X$ be a space of nodes and $(M[X], *, \theta)$ be a semi-group of monomials. An 'unalternative' cause-effect structure (briefly UCES) over
$X$ is a pair $(C, E)$ of functions:
$C : X \rightarrow M[X]$ (cause function)
$E : X \rightarrow M[X]$ (effect function)
such that $x$ occurs in the monomial $C(y)$ iff $y$ occurs in $E(x)$ (then $x$ is a cause of $y$ and $y$ is an effect of $x$). The set of all UCESs over $X$ is denoted by $UCE[X]$. The UCES is completely represented by the set of annotated nodes $x$ which is called its formula.
**Definition 4.4.** The sum of any (finite) number of UCESs is called a TCES, where the operation $\oplus$ satisfies the following axioms for any UCESs $U, V$ and $W$:
$$
\begin{align*}
\text{(***)} & \quad U \oplus U = U \\
\text{ (++++)} & \quad U \oplus V = V \oplus U \\
\text{ (++++)} & \quad U \oplus (V \oplus W) = (U \oplus V) \oplus W
\end{align*}
$$
Another representation of a TCES $U$ is the set of UCESs:
$$
\{Y_i \in UCE[X] \mid \sum Y_i = U\}.
$$
The set of all TCESs over $X$ is denoted by $TCE[X]$.
The set of UCESs is a particular case of the set of CESs, when the operation $+$ is absent. So we may define a notion of a substructure on the sets of UCESs and TCESs.
**Definition 4.5.** Let $U$ and $V$ be UCESs. $V$ is a substructure of $U$ iff $V + U = U$, where the operation $+$ is an old one from the algebra of CESs. The TCES $V$ is a substructure of the TCES $U$ iff each UCES from $V$ is a substructure of any UCES from $U$.
**Definition 4.6.** For a TCES $U$, let UCES $Q = (C_Q, E_Q)$ be a substructure of $U$ such that for each node $x \in Q$ there exists only one monomial, either $C_Q(x)$ or $E_Q(x)$, being equal to $\theta$. Then $Q$ is called a firing component of $U$.
The set of all firing components is denoted by $FC[U]$. The set of all finite strings over $FC[U]$ including the empty one is denoted by $FC[U]^*$. The set of nodes $x \in Q$ with $C_Q(x) = \theta$, and the set of nodes $x \in Q$ with $E_Q(x) = \theta$ are denoted by $^*Q$ and $Q^*$, respectively.
**Definition 4.7.** A state $s$ is a subset of the space of nodes $X$. A node $x$ is active in the state $s$ iff $x \in s$ and passive otherwise.
**Definition 4.8.** For $Q \in FC[U]$, let $[[Q]]$ denote a binary relation in the set of all the states: $(s, t) \in [[Q]]$ iff $^*Q \subseteq s, Q^* \cap s = \emptyset, t = (s - ^*Q) \cup Q^*$. The semantics $[[U]]$ of a GCES $U$ is a union of relations:
\[ [[U]] = \bigcup_{Q \in FC[U]} [[Q]] \]
The semantics \([[[U]]]\) of \(U\) is a transitive extension of \([[U]]\).
**Definition 4.9.** A TCES in the form \(\{a_x, x^a\}\) is called a basic TCES.
**Definition 4.10.** Two operations are defined over the \(TCE[X]\):
- an operation of nondeterministic choice \(\odot\):
\(U \odot V = \{Y \in UCE[X] \mid Y \in U \text{or} Y \in V\}\);
- an operation of combination \(\otimes\): if \(U\) and \(V\) are UCESs, then \(U \otimes V = \{x_{E_U(x) \cdot E_V(x)} : x \in X\}\);
if \(U = U_1 \oplus U_2\), then \(U \otimes V = U_1 \otimes V \oplus U_2 \otimes V\) and also for \(V\).
**Definition 4.11.** The algebraic system \(\langle TCE[X], \odot, \otimes, \theta \rangle\) is a commutative semi-ring (with a unit \(\theta\)) of TCESs if the following equality axioms hold for all \(U, V, W \in TCE[X]\) and \(Y \in UCE[X]\):
\[
\begin{align*}
(++) & \quad U \odot U = U & (\ast) & \quad \theta \otimes U = U \otimes \theta = U \\
(++++) & \quad U \otimes V = V \odot U & (\ast\ast) & \quad Y \otimes Y = Y \\
(+++++) & \quad U \otimes (V \oplus W) = (U \otimes V) \oplus W & (\ast \ast \ast) & \quad U \otimes (V \otimes W) = (U \otimes V) \otimes W \\
(++) & \quad U \otimes (V \odot W) = U \otimes V \oplus U \otimes W
\end{align*}
\]
The fulfillment of the equalities directly follows from Definitions 4.2 and 4.10.
This class preserves both the illustrative possibilities of PNs and the compact algebraic form of CESs. The problem of converse mapping is solved for the class of TCESs. But a TCES has only structural distinctions from a CES, their semantics are the same. So the semantics of coloured tokens is extended to the class of TCESs without essential changes. Thus, each CPN has a strongly equivalent coloured TCES.
**Theorem 2.** Any CPN has a strongly equivalent coloured TCES.
**Proof.** Let CPN \(N = (P, T, A, C(P), B(T), W(A), M_0)\), then CTCES \(U = (X_C, FC[U], S_0)\) will be strongly equivalent to \(N\), where:
- the set of nodes \(X_C\) is equal to the set \(P\) of places of \(N\);
- the set of coloured nodes \(X_C = \{< x, i > \mid x \in P, i \in C(x)\}\);
- the initial state \(S_0 = \{< x, i > \mid x \in P, i \in M_0(x)\}\);
- the set \(FC[U]\) is \(\{Q_t\}\) such that
\[
\forall t \in T : Q_t = \{x_{E(x)}(x, t) \in A\} \cup \{y^{C(t)}(t, y) \in A\},
\]
where $E(x) = \prod_{(t,y) \in A} y, C(y) = \prod_{(x,t) \in A} x$;
- we replace each firing component $Q_t \in FC[U]^g$ by a group of equivalent coloured firing components: $\forall b \in B(t)$:
$\cdot Q_t^b = \{ <x, i> | x_{E(x)} \in Q_t, i \in W(x, t)(b) \}$;
$\cdot Q_t^{*b} = \{ <y, j> | y_{C(y)} \in Q_t, j \in W(t, y)(b) \}$.
But a TCES in its canonical form is the sum of its firing components, so we complete our construction.
Finally, we check the condition of the Definition 3.1. Bijections $g$ and $f$ are as follows:
$\cdot g((x, i)) = <x, i>; f((t, b)) = Q_t^b$
and we have:
$\cdot g((x, i)) = g(\{(x, i) | (x, t) \in A, i \in W(x, t)(b)\}) = \{ <x, i> | x \in Q_t, i \in W(x, t)(b) \} = Q_t^b$
$\cdot g((t, b)^*) = g(\{(y, j) | (t, y) \in A, j \in W(t, y)(b)\}) = \{ <y, j> | y \in Q_t^*, j \in W(t, y)(b) \} = Q_t^{*b}$
i.e. the conditions of the definition of a strong equivalence are true.
It is easy to ensure that, applying the algorithm from the proof of Theorem 2 to the CPN from Example 2, we obtain the CCES from Example 1 in the two-level form. That is, this CCES is presented by the sum of all its firing components without operation $+$ in its cause and effect functions.
Conclusion
In the paper we present the extension of the class of cause-effect structures by the semantics of coloured tokens. This semantics correlates with that introduced by K. Jensen in [3] for Petri nets. But possibilities of CESs allow us to introduce it in a more simple and convenient way.
We investigate the relationships of this extended class with the class of coloured PNs. A simple algorithm is constructed that gives us a strongly equivalent CPN for each CCES. The problem is in the fact that not any CPN has a strongly equivalent CCES. We solve this problem by mapping CPNs into an extended class, TCESs, introduced in [7].
Acknowledgements. The author is grateful to Valery Nepomniashchy for useful discussions and Irene Virbitskaite for valuable remarks.
This work is supported by the Grant of the Presidium of the Siberian Division of the Russian Academy of Sciences.
References
|
{"Source-Url": "https://nccbulletin.ru/files/article/ustimenko.pdf", "len_cl100k_base": 11051, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 17150, "total-output-tokens": 12379, "length": "2e13", "weborganizer": {"__label__adult": 0.0003726482391357422, "__label__art_design": 0.0006985664367675781, "__label__crime_law": 0.0004429817199707031, "__label__education_jobs": 0.00185394287109375, "__label__entertainment": 0.00013685226440429688, "__label__fashion_beauty": 0.00021791458129882812, "__label__finance_business": 0.0007042884826660156, "__label__food_dining": 0.0005927085876464844, "__label__games": 0.0010738372802734375, "__label__hardware": 0.0015153884887695312, "__label__health": 0.001003265380859375, "__label__history": 0.0004954338073730469, "__label__home_hobbies": 0.0002727508544921875, "__label__industrial": 0.0011720657348632812, "__label__literature": 0.000888824462890625, "__label__politics": 0.0004534721374511719, "__label__religion": 0.0008211135864257812, "__label__science_tech": 0.32958984375, "__label__social_life": 0.00016629695892333984, "__label__software": 0.01059722900390625, "__label__software_dev": 0.6455078125, "__label__sports_fitness": 0.0002944469451904297, "__label__transportation": 0.001079559326171875, "__label__travel": 0.00024437904357910156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34733, 0.0152]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34733, 0.77806]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34733, 0.83743]], "google_gemma-3-12b-it_contains_pii": [[0, 2344, false], [2344, 5113, null], [5113, 6943, null], [6943, 9411, null], [9411, 11954, null], [11954, 14636, null], [14636, 17136, null], [17136, 18762, null], [18762, 20970, null], [20970, 23107, null], [23107, 25666, null], [25666, 27123, null], [27123, 29440, null], [29440, 31790, null], [31790, 33896, null], [33896, 34733, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2344, true], [2344, 5113, null], [5113, 6943, null], [6943, 9411, null], [9411, 11954, null], [11954, 14636, null], [14636, 17136, null], [17136, 18762, null], [18762, 20970, null], [20970, 23107, null], [23107, 25666, null], [25666, 27123, null], [27123, 29440, null], [29440, 31790, null], [31790, 33896, null], [33896, 34733, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34733, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34733, null]], "pdf_page_numbers": [[0, 2344, 1], [2344, 5113, 2], [5113, 6943, 3], [6943, 9411, 4], [9411, 11954, 5], [11954, 14636, 6], [14636, 17136, 7], [17136, 18762, 8], [18762, 20970, 9], [20970, 23107, 10], [23107, 25666, 11], [25666, 27123, 12], [27123, 29440, 13], [29440, 31790, 14], [31790, 33896, 15], [33896, 34733, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34733, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
a34c0cc93f0a8761d38a8717c840708cf9f10f12
|
The newest release of the Java language allows classes to be defined in any scope. This paper specifies how the language has been extended to permit this, and shows how Java programmers can benefit from the change.
For more up-to-date and detailed information about the Java language, platform, and development environment, refer to the JavaSoft web site http://java.sun.com/products/JDK/1.1/.
Java is developed by JavaSoft, an operating company of Sun Microsystems, Inc.
Contents
• What are top-level classes and inner classes? ............................................. 3
– Example: A simple adapter class ......................................................... 4
– Example: A local class ................................................................. 6
– Anonymous classes ................................................................. 7
• How do inner classes work? .......................................................... 8
– References to local variables ....................................................... 9
• Why does Java need inner classes? .................................................. 11
– Why anonymous classes? .......................................................... 12
– What about dynamic typing and computed selectors (“perform”)? .... 12
• How do inner classes affect the idea of this in Java code? ................. 13
– Enclosing classes and instantiation .............................................. 14
• Do inner classes affect the correct synchronization of Java code? .... 15
• Can a nested class be declared final, private, protected, or static? ... 16
– Members that can be marked static ............................................. 16
• How do inner classes affect the organization of the Java Virtual Machine? ... 17
– Class name transformations ....................................................... 17
– Names of generated variables and methods .................................. 18
– Security implications .............................................................. 18
• How does the Java Language Specification change for inner classes? ... 19
• Other changes in the Java 1.1 language ......................................... 21
– Instance initializers ............................................................... 21
– Anonymous array expressions .................................................. 21
– Class literals .............................................................................. 22
– Blank finals and final local variables ......................................... 23
• What are the new binary compatibility requirements for Java 1.1 classes? ... 24
– Bytecode names of classes and interfaces .................................... 24
– The class attribute InnerClasses ............................................. 25
– The member attribute Synthetic ............................................. 26
• Further Example: Sample AWT code ............................................ 27
• Further Example: An API with coordinated inner classes .......... 28
• Further Example: Multi-threaded task partitioning ..................... 29
What are top-level classes and inner classes?
In previous releases, Java supported only *top-level classes*, which must be members of packages. In the 1.1 release, the Java 1.1 programmer can now define *inner classes* as members of other classes, locally within a block of statements, or (anonymously) within an expression.
Here are some of the properties that make inner classes useful:
- The inner class’s name is not usable outside its scope, except perhaps in a qualified name. This helps in structuring the classes within a package.
- The code of an inner class can use simple names from enclosing scopes, including both class and instance members of enclosing classes, and local variables of enclosing blocks.
Inner classes result from the combination of block structure with class-based programming, which was pioneered by the programming language Beta. Using block structure with inner classes makes it easier for the Java programmer to connect objects together, since classes can be defined closer to the objects they need to manipulate, and can directly use the names they need. With the removal of restrictions on the placement of classes, Java’s scoping rules become more regular, like those of classical block structured languages such as Pascal and Scheme.
In addition, the programmer can define a class as a *static* member of any top-level class. Classes which are *static* class members and classes which are package members are both called top-level classes. They differ from inner classes in that a top-level class can make direct use only of its own instance variables. The ability to nest classes in this way allows any top-level class to provide a package-like organization for a logically related group of secondary top-level classes, all of which share full access to private members.
Inner classes and nested top-level classes are implemented by the compiler, and do not require any changes to the Java Virtual Machine. They do not break source or binary compatibility with existing Java programs.
All of the new nested class constructs are specified via transformations to Java 1.0 code that does not use inner classes. When a Java 1.1 compiler is producing Java virtual machine bytecodes, these bytecodes must represent the results of this (hypothetical) source-to-source transformation, so that binaries produced by different Java 1.1 compilers will be compatible. The bytecodes must also be tagged with certain attributes to indicate the presence of any nested classes to other Java 1.1 compilers. This is discussed further below.
Example: A simple adapter class
Consider the design of an adapter class, which receives method invocations using a specified interface type on behalf of another object not of that type. Adapter classes are generally required in order to receive events from AWT and Java Bean components. In Java 1.1, an adapter class is most easily defined as an inner class, placed inside the class which requires the adapter.
Here is an incomplete class FixedStack which implements a stack, and is willing to enumerate the elements of the stack, from the top down:
```java
public class FixedStack {
Object array[];
int top = 0;
FixedStack(int fixedSizeLimit) {
array = new Object[fixedSizeLimit];
}
public void push(Object item) {
array[top++] = item;
}
public boolean isEmpty() {
return top == 0;
}
// other stack methods go here...
/** This adapter class is defined as part of its target class,
* It is placed alongside the variables it needs to access.
*/
class Enumerator implements java.util.Enumeration {
int count = top;
public boolean hasMoreElements() {
return count > 0;
}
public Object nextElement() {
if (count == 0)
throw new NoSuchElementException("FixedStack");
return array[--count];
}
public java.util Enumeration elements() {
return new Enumerator();
}
}
}
```
The interface `java.util Enumeration` is used to communicate a series of values to a client. Since `FixedStack` does not (and should not!) directly implement the `Enumeration` interface, a separate adapter class is required to present the series of elements, in the form of an `Enumeration`. Of course, the adapter class will need some sort of access to the stack’s array of elements. If the programmer puts the definition of the adapter class inside of `FixedStack`, the adapter’s code can directly refer to the stack object’s instance variables.
In Java, a class’s non-static members are able to refer to each other, and they all take their meaning relative to the current instance `this`. Thus, the instance variable `array` of `FixedStack` is available to the instance method `push` and to the entire body of the inner class `FixedStack Enumerator`. Just as instance method bodies “know” their current instance `this`, the code within any inner class like `Enumerator` “knows” its enclosing instance, the instance of the enclosing class from which variables like `array` are fetched.
One of the ways in which the `FixedStack` example is incomplete is that there is a race condition among the operations of the `FixedStack` and its `Enumerator`. If a sequence of pushes and pops occurs between calls to `nextElement`, the value returned might not be properly related to previously enumerated values; it might even be a “garbage value” from beyond the current end of the stack. It is the responsibility of the programmer to defend against such race conditions, or to document usage limitations for the class.
This point is discussed later. One defense against races looks like this:
```java
public class FixedStack {
...
synchronized public void push(Object item) {
array[top++] = item;
}
class Enumerator implements java.util Enumeration {
...
public Object nextElement() {
synchronized (FixedStack.this) {
if (count > top) count = top;
if (count == 0)
throw new NoSuchElementException("FixedStack");
return array[--count];
}
}
}
}
```
The expression `FixedStack.this` refers to the enclosing instance.
Example: A local class
When a class definition is local to a block, it may access any names which are available to ordinary expressions within the same block. Here is an example:
```java
Enumeration myEnumerate(final Object array[]) {
class E implements Enumeration {
int count = 0;
public boolean hasMoreElements() {
return count < array.length;
}
public Object nextElement() {
return array[count++];
}
}
return new E();
}
```
For the moment, we say nothing about how this code works, but Java’s rules of scoping and variable semantics precisely require what this code does. Even after the method `myEnumerate` returns, `array` can still be used by the inner object; it does not “go away” as in C. Instead, its value continues to be available wherever that value is required, including the two methods of E.
Note the final declaration. Local final variables such as `array` are a new feature in 1.1. In fact, if a local variable or parameter in one class is referred to by another (inner) class, it must be declared final. Because of potential synchronization problems, there is by design no way for two objects to share access to a changeable local variable. The state variable `count` could not be coded as a local variable, unless perhaps it were changed a one-element array:
```java
Enumeration myEnumerate(final Object array[]) {
final int count[] = {0}; // final reference to mutable array
class E implements Enumeration {
public boolean hasMoreElements() {
return count[0] < array.length;
}
}
return new E();
}
```
(Sometimes the combination of inheritance and lexical scoping can be confusing. For example, if the class E inherited a field named `array` from Enumeration, the field would hide the parameter of the same name in the enclosing scope. To prevent ambiguity in such cases, Java 1.1 allows inherited names to hide ones defined in enclosing block or class scopes, but prohibits them from being used without explicit qualification.)
Anonymous classes
In the previous example, the local class name E adds little or no clarity to the code. The problem is not that it is too short: A longer name would convey little additional information to the maintainer, beyond what can be seen at a glance in the class body. In order to make very small adapter classes as concise as possible, Java 1.1 allows an abbreviated notation for local objects. A single expression syntax combines the definition of an anonymous class with the allocation of the instance:
```java
Enumeration myEnumerate(final Object array[]) {
return new Enumeration() {
int count = 0;
public boolean hasMoreElements() {
return count < array.length;
}
public Object nextElement() {
return array[count++];
}
};
}
```
In general, a new expression (an instance creation expression) can end with a class body. The effect of this is to take the class (or interface) named after the new token, and subclass it (or implement it) with the given body. The resulting anonymous inner class has the same meaning as if the programmer had defined it locally, with a name, in the current block of statements.
Anonymous constructs like these must be kept simple, to avoid deeply nested code. When properly used, they are more understandable and maintainable than the alternatives—named local classes or top-level adapter classes.
If an anonymous class contains more than a line or two of executable code, then its meaning is probably not self-evident, and so a descriptive local name should be given to either the class or (via a local variable) to the instance.
An anonymous class can have initializers but cannot have a constructor. The argument list of the associated new expression (often empty) is implicitly passed to a constructor of the superclass.
As already hinted, if an anonymous class is derived from an interface I, the actual superclass is Object, and the class implements I rather than extending it. (Explicit implements clauses are illegal.) This is the only way an interface name can legally follow the keyword new. In such cases, the argument list must always be null, to match the constructor of the actual superclass, Object.
How do inner classes work?
Inner class code is typically defined relative to some enclosing class instance, so the inner class instance needs to be able to determine the enclosing instance.
The JavaSoft Java 1.1 compiler arranges this by adding an extra private instance variable which links the inner class to the enclosing class. This variable is initialized from an extra argument passed to the inner class constructor. That argument, in turn, is determined by the expression which creates the inner class instance; by default it is the object doing the creation.
The Java 1.1 Language Specification specifies that the name of a type which is a class member, when transformed into Java 1.0 code for the purpose of generating Java virtual machine bytecodes, consists of the fully qualified name of the inner class, except that each ‘.’ character following a class name is replaced by a ‘$’. In addition, each inner class constructor receives the enclosing instance in a prepended argument. Here is how the transformed source code of the FixedStack example might look:
```java
public class FixedStack {
...
public java.util.Enumeration elements() {
return new FixedStack$Enumerator(this);
}
}
class FixedStack$Enumerator implements java.util.Enumeration {
private FixedStack this$0; // saved copy of FixedStack.this
FixedStack$Enumerator(FixedStack this$0) {
this.this$0 = this$0;
this.count = this$0.top;
}
int count;
public boolean hasMoreElements() {
return count > 0;
}
public Object nextElement() {
if (count == 0)
throw new NoSuchElementException("FixedStack");
return this$0.array[--count];
}
}
```
Anyone who has already programmed with Java or C++ adapter classes has written code similar to this, except that the link variables must be manually defined and explicitly initialized in top-level adapter classes, whereas the Java 1.1 compiler creates them automatically for inner classes.
When the Enumerator needs to refer to the top or array fields of the enclosing instance, it indirections through a private link called this$0. The spelling of this name is a mandatory part of the transformation of inner classes to the Java 1.0 language, so that debuggers and similar tools can recognize such links easily. (Most programmers are happily unaware of such names.)
(Note: There is a limitation in some implementations of Java 1.1, under which the initialization of this$0 is delayed until after any superclass constructor is run. This means that up-level references made by a subclass method may fail if the method happens to be executed by the superclass constructor.)
References to local variables
A class definition which is local to a block may access local variables. This complicates the compiler’s job. Here is the previous example of a local class:
```java
Enumeration myEnumerate(final Object array[]) {
class E implements Enumeration {
int count = 0;
public boolean hasMoreElements() {
return count < array.length;
}
public Object nextElement() {
return array[count++];
}
}
return new E();
}
```
In order to make a local variable visible to a method of the inner class, the compiler must copy the variable’s value into a place where the inner class can access it. References to the same variable may use different code sequences in different places, as long as the same value is produced everywhere, so that the name consistently appears to refer to the same variable in all parts of its scope.
By convention, a local variable like array is copied into a private field val$array of the inner class. (Because array is final, such copies never contain inconsistent values.) Each copied value is passed to the inner class constructor as a separate argument of the same name.
Here is what the resulting transformed code looks like:
```java
Enumeration myEnumerate(final Object array[]) {
return new MyOuterClass$19(array);
}
...
class MyOuterClass$19 implements Enumeration {
private Object val$array[];
int count;
MyOuterClass$19(Object val$array[]) {
this.val$array = val$array; count = 0;
}
public boolean hasMoreElements() {
return count < val$array.length;
}
public Object nextElement() {
return val$array[count++];
}
}
```
A compiler may avoid allocating an inner class field to a variable, if it can determine that the variable is used only within the inner class constructors.
Notice that a class defined by a block, like E, is not a member of its enclosing class, and so it cannot be named outside of its block. This is the same scoping restriction as applies to local variables, which also cannot be named outside of their blocks. In fact, any class contained in a block (whether directly or inside an intervening local class) cannot be named outside the block. All such classes are called inaccessible. For purposes of linking, the compiler must generate a unique externally visible name for every inaccessible class. The overall form of these names is a class name, followed by additional numbers or names, separated by $ characters.
Also, variable names synthesized by the compiler beginning with this$ and val$ must follow the usage patterns described here.
These names and conventions must be recognized by 1.1-compliant tools, and are strongly suggested for most compilation purposes. They are discussed further in the section on binary compatibility.
It must be emphasized that these oddly-named “this$” and “val$” fields and extra constructor arguments are added by the compiler to the generated bytecodes, and cannot be directly referenced by Java source code. Likewise, bytecode-level class names like MyOuterClass$19 cannot be used by source code (except under pre-1.1 compilers, which know nothing of inner classes).
Why does Java need inner classes?
From the very beginnings of Java, its designers have recognized the need for a construct like a “method pointer,” which (in all its various forms) amounts to a handle on an individual block of code which can be used without reference to the object or class containing the code. In languages (like C or Lisp) where functions are free standing, independent of objects, function pointers serve this role. For example, these pointers often serve to connect a “callback” or “event” in one module to a piece of code in another. In a more object oriented style, Smalltalk has “blocks,” which are chunks of code that behave like little objects. As with C or Lisp function pointers, Smalltalk blocks can be used to organize complex control flow patterns, such as iteration over collections.
In Java, the same complex control flow patterns, including event management and iteration, are expressed by classes and interfaces. Java uses interfaces with one method where other languages might use separate “function types.” The Java programmer creates the equivalent of a callback or a Smalltalk block by wrapping the desired code in an adapter class which implements the required interface. With inner classes, the notation for adapters is about as simple as that of Smalltalk blocks, or of inner functions in other languages. However, since classes are richer than functions (because they have multiple entry points), Java adapter objects are more powerful and more structured than function pointers.
So, whereas C, Lisp, and Smalltalk programmers use variations of “method pointers” to encapsulate chunks of code, Java programmers use objects. Where other languages have specialized function types and notations to encapsulate behavior as functions, Java has only class and interface types. In Java, “the class is the quantum of behavior.” One benefit of this approach is simplicity and stability for the Java Virtual Machine, which needs no special support for inner classes or function pointers.
Without inner classes, Java programmers can create callbacks and iterators by means of adapter classes defined at top-level, but the notation is so clumsy as to be impractical. By means of inner classes, Java programmers can write concise adapter classes which are coded precisely where they are needed, and operate directly on the internal variables and methods of a class or a block.
Thus, inner classes make adapter classes practical as a coding style. In the future, inner classes will also be more efficient than equivalent top-level adapter classes, because of increased opportunities for optimization, especially of (externally) inaccessible classes.
Why anonymous classes?
An anonymous class is an abbreviated notation for creating a simple local object “in-line” within any expression, simply by wrapping the desired code in a “new” expression.
As noted previously, not every inner class should be anonymous, but very simple “one-shot” local objects are such a common case that they merit some syntactic sugar.
Anonymous classes are useful for writing small encapsulated “callbacks,” such as enumerations, iterators, visitors, etc. They are also helpful for adding behavior to objects which already have names, such as AWT components (to which anonymous event handlers are added), and threads. In both cases, an intervening class name can detract from the clarity of the code.
Several other languages from which Java derives inspiration, such as Smalltalk and Beta, offer similar shorthands for anonymous objects or functions.
What about dynamic typing and computed selectors (“perform”)?
In order to support the construction of robust and secure systems, Java is statically typed. In other languages, callbacks sometimes take a form which is untyped, or dynamically typed. C callbacks usually work with an untyped “client data” address, while Smalltalk classes sometimes plug into each other by means of symbolic method references computed at run time, which are passed to an interpretive “perform” method.
The closest equivalent to a C void* pointer in Java is a reference of type Object. As in C, it is possible to program in Java with such “untyped” references. A generic “argument” field in an event descriptor might be an undifferentiated Object, as is the element type of java.util.Vector. Coding with untyped references is sometimes a workable technique, despite the execution costs of dynamic type checking, but the lack of static declarations can make programs hard to understand and maintain.
Also, some applications for “method pointer” constructs, such as application builders or the Java Beans component framework, have needed the ability to invoke a method of a computed name on an arbitrary object. This capability is provided by the Java Core Reflection API, java.lang.reflect, a new Java 1.1 API.
How do inner classes affect the idea of this in Java code?
Recall that the code of a top-level class \( T \) can make use of the current instance, either directly by means of the keyword \texttt{this}, or indirectly, by naming one of the instance members of \( T \). The idea of a current instance has been extended, so that inner classes have more than one current instance. This allows the code of an inner class \( C \) to execute relative to an enclosing instance of its outer class, as well as the current instance of \( C \).
In our first example of adapter classes, the \texttt{Enumerator} code had two current instances, the enclosing \texttt{FixedStack} and the \texttt{Enumerator} object itself. More generally, within the entire body of an inner class \( C \), there is a current instance for \( C \), another current instance for every inner class enclosing \( C \), and finally a current instance for the innermost enclosing top-level class. (A \texttt{static} class is a top-level class, not an inner class. Therefore, our enumeration of current instances stops at the first \texttt{static} keyword.)
Top-level classes do not have multiple current instances. Within the non-\texttt{static} code of a top-level class \( T \), there is one current instance of type \( T \). Within the \texttt{static} code of a top-level class \( T \), there are no current instances. This has always been true of top-level classes which are package members, and is also true of top-level classes which are \texttt{static} members of other top-level classes. It is as if all package members have been implicitly \texttt{static} all along.
In all classes, each current instance can be named explicitly or can play an implicit part when its members are used. Any current instance can be referred to by explicitly qualifying the keyword \texttt{this} as if it were a name: \texttt{FixedStack.this}, \texttt{Enumerator.this}, etc. (This notation is always effective, since the language prohibits an inner class from having the same name as any of its enclosing classes.) As always, the innermost current instance can be named with the unqualified keyword \texttt{this}.
Remember that an instance variable reference \( m \) has the same meaning as a field reference expression \texttt{this.m}, so the current instance is implicitly used. In a given piece of code, all members of all current classes are in scope and usable (except for name hiding by intervening scopes). The simple name of a member is implicitly qualified by the current instance in whose class the name was found. (All \texttt{static} members of enclosing classes are always usable.)
In particular, Java code can directly use all methods of all current instances. Class scoping does not influence overloading: If the inner class has one \texttt{print} method, the simple method name \texttt{print} refers to that method, not any of the ten \texttt{print} methods in the enclosing class.
Enclosing classes and instantiation
It is sometimes useful to speak of an *enclosing instance* of an inner class C. This is defined as any current instance within C, other than the instance of C itself. Every instance of C is permanently associated with its enclosing instances.
When a constructor is invoked, the new object must be supplied with an enclosing instance, which will become a current instance for all the code executed by the new object. (If there are layers of enclosing instances, the innermost is required, and it in turn determines all the others.) The enclosing instance may be specified explicitly, by qualifying the keyword `new`:
```java
class Automobile {
class Wheel {
String hubcapType;
float radius;
}
Wheel leftWheel = this. new Wheel();
Wheel rightWheel = this. new Wheel();
Wheel extra;
static void thirdWheel(Automobile car) {
if (car.extra == null) {
car.extra = car. new Wheel();
}
return car.extra;
}
}
class WireRimWheel extends Automobile.Wheel {
WireRimWheel(Automobile car, float wireGauge) {
car. super();
}
}
```
A subclass of an inner class C must pass an enclosing instance to C’s constructor. This may be done, as just shown, by explicitly qualifying the keyword `super`. By default, a current instance of the caller becomes the enclosing instance of a new inner object. In an earlier example, the expression `new Enumerator()` is equivalent to the explicitly qualified `this. new Enumerator()`. This default is almost always correct, but some applications (such as source code generators) may need to override it from time to time.
Do inner classes affect the correct synchronization of Java code?
An inner class is part of the implementation of its enclosing class (or classes). As such, it has access to the private members of any enclosing class. This means that the programmer must be aware of the possibility of concurrent access to state stored in private variables, and ensure that non-private methods are correctly synchronized. Sometimes this just means that the enclosing method needs to be declared with the synchronized keyword.
When more than one object is involved, as with FixedStack and its enumerator, the programmer must choose which instance to synchronize upon, and write an explicit synchronized statement for the enclosing instance:
```java
public Object nextElement() {
...
synchronized (FixedStack.this) {
return array[--count];
}
}
```
There is no special relation between the synchronized methods of an inner class and the enclosing instance. To synchronize on an enclosing instance, use an explicit synchronized statement.
When writing multi-threaded code, programmers must always be aware of potential asynchronous accesses to shared state variables. Anonymous inner classes make it extremely easy to create threads which share private fields or local variables. The programmer must take care either to synchronize access to these variables, or to make separate copies of them for each thread. For example, this for-loop needs to make copies of its index variable:
```java
for (int ii = 0; ii < getBinCount(); ii++) {
final int i = ii; // capture a stable copy for each thread
Runnable r = new Runnable() {
public void run() { processBin(i); }
};
new Thread(r, "processBin(*i*)").start();
}
```
It is a common mistake to try to use the loop index directly within the inner class body. Since the index is not final, the compiler reports an error.
Can a nested class be declared final, private, protected, or static?
All the existing access protection and modification modes apply in a regular fashion to types which are members of other classes. Classes and interfaces can be declared private or protected within their enclosing classes.
A class which is local to a block is not a member, and so cannot be public, private, protected, or static. It is in effect private to the block, since it cannot be used outside its scope.
Access protection never prevents a class from using any member of another class, as long as one encloses the other, or they are enclosed by a third class.
Any class (if it has a name) can be declared final or abstract, and any accessible non-final named class or interface can serve as a supertype. A compiler may also change a class to be final if it can determine that it has no subclasses, and that there is no way for subclasses to be added later. This is possible when a private or block-local class has no subclasses in its scope.
Members that can be marked static
The static declaration modifier was designed to give programmers a way to define class methods and class variables which pertain to a class as a whole, rather than any particular instance. They are “top-level” entities.
The static keyword may also modify the declaration of a class C within the body of a top-level class T. Its effect is to declare that C is also a top-level class. Just as a class method of T has no current instance of T in its body, C also has no current instance of T. Thus, this new usage of static is not arbitrary.
As opposed to top-level classes (whether nested or not), inner classes cannot declare any static members at all. To create a class variable for an inner class, the programmer must place the desired variable in an enclosing class.
It is helpful at this point to abuse the terminology somewhat, and say, loosely, that the static keyword always marks a “top-level” construct (variable, method, or class), which is never subject to an enclosing instance.
This shows why an inner class cannot declare a static member, because the entire body of the inner class is in the scope of one or more enclosing instances.
While the C language allows block-local static variables, the same effect can be obtained in Java, more regularly and maintainably, by defining the desired long-lived variable in the scope which corresponds to the required lifetime.
How do inner classes affect the organization of the Java Virtual Machine?
There are no changes to the class file format as processed by the Java Virtual Machine, or to the standard class libraries. The new features are implemented by the compiler. The organization of the resulting bytecodes is specified with enough precision that all 1.1-conforming compilers will produce binary compatible class files.
A single file of Java source code can compile to many class files. Although this is not a new phenomenon, the power of the inner class notation means that the programmer can end up creating a larger number of class files with relatively less code. In addition, adapter classes tend to be very simple, with few methods. This means that a Java program which uses many inner classes will compile to many small class files. Packaging technologies for such classes process them reasonably efficiently. For example, the class file for the example class FixedStackEnumeration occupies about three quarters of a kilobyte, of which about 40% is directly required to implement its code. This ratio is likely to improve over time as file formats are tuned. The memory usage patterns in the virtual machine are comparable.
Class name transformations
Names of nested classes are transformed as necessary by the compiler to avoid conflicts with identical names in other scopes. Names are encoded to the virtual machine by taking their source form, qualified with dots, and changing each dot '`.` after a class name into a dollar sign '$'. (Mechanical translators are allowed to use dollar signs in Java.)
When a class name is private or local to a block, it is globally inaccessible. A compiler may opt to code such an inaccessible name by using an accessible enclosing class name as a prefix, followed by a '$' separator and a locally unique decimal number. Anonymous classes must be encoded this way.
So, an inner class pkg.Foo.Bar gets a run-time name of pkg.Foo$Bar, or perhaps something like pkg.Foo$23, if Bar is a private member or local class. Implementations must conform to the format of names, even globally inaccessible ones, so that debuggers and similar tools can recognize them.
Any class file which defines or uses a transformed name also contains an attribute (as supported by the 1.0 file format) recording the transformation. These attributes are ignorable by the virtual machine and by 1.0 compilers. The format of this attribute is described in the section on binary compatibility.
Names of generated variables and methods
As we have seen previously, if an inner class uses a variable from an enclosing scope, the name expression will be transformed, into a reference either to a field of an enclosing instance, or to a field of the current instance which provides the value of a final local variable. A reference to an enclosing instance, in turn, is transformed into a reference to a field in a more accessible current instance. These techniques require that the compiler synthesize hidden fields in inner classes.
There is one more category of compiler-generated members. A private member $m$ of a class $C$ may be used by another class $D$, if one class encloses the other, or if they are enclosed by a common class. Since the virtual machine does not know about this sort of grouping, the compiler creates a local protocol of access methods in $C$ to allow $D$ to read, write, or call the member $m$. These methods have names of the form `access$0`, `access$1`, etc. They are never public. Access methods are unique in that they may be added to enclosing classes, not just inner classes.
All generated variables and methods are declared in a class file attribute, so that the 1.1 compilers can prevent programs from referring to them directly.
Security implications
If an inner class $C$ requires access to a private member $m$ of an enclosing class $T$, the inserted access method for $m$ opens up $T$ to illegal access by any class $K$ in the same package. There at present are no known security problems with such access methods, since it is difficult to misuse a method with package scope. The compiler can be instructed to emit warnings when it creates access methods, to monitor the creation of possible loopholes.
If a class $N$ is a protected member of another class $C$, then $N$'s class file defines it as a public class. A class file attribute correctly records the protection mode bits. This attribute is ignored by the current virtual machine, which therefore will allow access to $N$ by any class, and not just to subclasses of $C$. The compiler, of course, will correctly diagnose such errors, because it looks at the attribute. This is not a security hole, since malicious users can easily create subclasses of $C$ and so gain access to $N$, protected or not.
Likewise, if a class is a private member of another class, its class file defines it as having package scope, and an attribute declares the true access protection, so that 1.1 compilers can prevent inadvertent access, even within the package.
How does the Java Language Specification change for inner classes?
There are few significant changes, since the new features primarily relax restrictions in the existing language, and work out new implications for the old design. The key change is that types can now have types as members. (But type names can’t contain instance expressions.) The basic definitions of scope, name scoping, member naming, and member access control are unchanged.
Here are the extensions to the class body and block syntax:
```
ClassMemberDeclaration, InterfaceMemberDeclaration:
...
ClassDeclaration
InterfaceDeclaration
BlockStatement:
...
ClassDeclaration
```
A type which is a type member is inherited by subtypes, and may be hidden in them by type declarations of the same name. (Types are never “virtual.”) Members which are types may be declared `private` or `protected`.
A non-static member class, or a class defined by a block or expression, is an inner class. All other classes are top-level. Inner classes may not declare `static` members, `static` initializers, or member interfaces. Package members are never `static`. But a class which is a member of a top-level class may be declared `static`, thereby declaring it also to be a top-level class. Interfaces are always `static`, as are their non-method members.
A class may not have the same simple name as any of its enclosing classes.
The keyword `this` can be qualified, to select one of possibly several current instances. (Inner classes have two or more current instances.)
```
PrimaryNoNewArray:
...
ClassName . this
```
The syntax for class instance creation extended to support anonymous classes and enclosing instances:
```
ClassInstanceCreationExpression:
new typeName ( ArgumentListOpt ) ClassBodyOpt
Primary . new Identifier ( ArgumentListOpt ) ClassBodyOpt
```
A `new` expression may define an anonymous class by specifying its body. Independently, the type of a `new` expression may specified as the simple name of an inner class, if an instance of the immediately enclosing class is given as a qualifying expression before the keyword `new`. The qualifying instance becomes the enclosing instance of the new object. A corresponding qualification of `super` allows a subclass constructor to specify an enclosing instance for a superclass which is an inner:
```
ExplicitConstructorInvocation: ...
Primary . super ( ArgumentListOpt ) ;
```
If an inner class is constructed by an unqualified `new` or `super` expression, the enclosing instance will be the (innermost) current instance of the required type.
Some of the detailed descriptions of name binding in the 1.0 Java Language Specification require amendment to reflect the new regularity in lexical scoping. For example, a simple variable name refers to the innermost lexically apparent definition, whether that definition comes from a class or a block. The same is true for simple type names. The grammar for a qualifier name (i.e., an `AmbiguousName`) is extended to reflect the possibility of class names qualifying other type names. The initial simple name in a qualified type name is taken to be a class name if a class of that name is in scope; otherwise it is taken to be a package name, as in Java 1.0.
Any inherited member `m` of a subclass `C`, including any inner classes within `C`. If `C` itself is an inner class, there may be definitions of the same kind (variable, method, or type) for `m` in enclosing scopes. (The scopes may be blocks, classes, or packages.) In all such cases, the inherited member `m` hides the other definitions of `m`. Additionally, unless the hidden definition is a package member, the simple name `m` is illegal; the programmer must write `C.this.m`.
Nested classes of all sorts (top-level or inner) can be imported by either kind of `import` statement. Class names in `import` statements must be fully package qualified, and be resolvable without reference to inheritance relations. As in Java 1.0, it is illegal for a class and a package of the same name to co-exist.
A `break` or `continue` statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.
The checking of definite assignment includes classes defined by blocks and expressions, and extends to occurrences of variables within those classes. Any local variable used but not defined in an inner class must be declared `final`, and must be definitely assigned before the body of the inner class.
Other changes in the Java 1.1 language
The Java 1.1 language includes four additional extensions which fill small holes in the language, and make certain kinds of APIs easier to use.
Instance initializers
The static initializer syntax is extended to support instance initialization also:
\begin{verbatim}
ClassBodyDeclaration:
Block
\end{verbatim}
Initialization code introduced without the \texttt{static} keyword is executed by every constructor, just after the superclass constructor is called, in textual order along with any instance variable initializations.
An instance initializer may not return, nor throw a checked exception, unless that exception is explicitly declared in the \texttt{throws} clause of each constructor. An instance initializer in an anonymous class can throw any exceptions.
Instance initializers are useful when instance variables (including blank finals) must be initialized by code which must catch exceptions, or perform other kinds of control flow which cannot be expressed in a single initializer expression. Instance initializers are required if an anonymous class is to initialize itself, since an anonymous class cannot declare any constructors.
Anonymous array expressions
The array allocation syntax is extended to support initialization of the elements of anonymous arrays. Just as a named array can be initialized by a brace-enclosed list of element expressions, an array creation expression can now be followed by such a brace-enclosed list. In both cases, the array type is not allowed to include any dimension expressions; the dimension is computed by counting the number of element expressions. Here is the new syntax:
\begin{verbatim}
ArrayCreationExpression:
new Type Dims ArrayInitializer
\end{verbatim}
The equivalence of the following two statements illustrates the new syntax:
\begin{verbatim}
T v[] = {a};
T v[] = new T[] {a};
\end{verbatim}
Class literals
PrimaryNoNewArray:
...
Type.class
void.class
A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a ‘.’ and the token class. It evaluates to an object of type Class, the class object for the named type (or for void).
For reference types, a class literal is equivalent to a call to Class.forName with the appropriate string, except that it does not raise any checked exceptions. (Its efficiency is likely to be comparable to that of a field access, rather than a method call.) The class literal of a reference type can raise NoClassDefFoundError, in much the same way that a class variable reference can raise that error if the variable’s class is not available.
The class literal of a primitive type or void is equivalent to a static variable reference to a pre-installed primitive type descriptor, according to this table:
<table>
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>boolean.class == Boolean.TYPE</td>
<td></td>
</tr>
<tr>
<td>char.class == Character.TYPE</td>
<td></td>
</tr>
<tr>
<td>byte.class == Byte.TYPE</td>
<td></td>
</tr>
<tr>
<td>short.class == Short.TYPE</td>
<td></td>
</tr>
<tr>
<td>int.class == Integer.TYPE</td>
<td></td>
</tr>
<tr>
<td>long.class == Long.TYPE</td>
<td></td>
</tr>
<tr>
<td>float.class == Float.TYPE</td>
<td></td>
</tr>
<tr>
<td>double.class == Double.TYPE</td>
<td></td>
</tr>
<tr>
<td>void.class == Void.TYPE</td>
<td></td>
</tr>
</tbody>
</table>
Java APIs which require class objects as method arguments are much easier to use when the class literal syntax is available. Note that the compiler is responsible for taking into account the ambient package and import statements when processing the TypeName of a class literal.
The older usage of Class.forName requires the programmer to figure out the desired package prefix and write it in a class name string. The difficulty of getting the string spelled right becomes greater in the presence of inner classes, since their names (as processed by Class.forName) are encoded with ‘$’ characters instead of dots.
Note that a class literal never contains an expression, only a type name.
Blank finals and final local variables
A blank final is a final variable declaration (of any kind) which lacks an initializer. A blank final must be assigned an initial value, at most once.
The definite assignment rules are extended to record variables which are "definitely unassigned," and an assignment to a blank final is prohibited unless the final is definitely unassigned before the assignment statement. Subsequently, it is definitely assigned, and, being a final, it cannot be re-assigned along the same execution path.
The definite unassignment rules take into account back-branches of loops, so that a variable occurrence in a loop body may not be definitely unassigned if the loop makes an assignment which can reach the occurrence via a back-branch. The definite assignment checks work as if the first iteration of the loop had been unrolled into an if statement.
A blank final class variable must be definitely assigned by a static initializer (in the same class). This is the only context where class variables are checked for definite assignment.
A blank final instance variable must be definitely assigned by a non-static initializer, or else by every constructor. These are the only contexts in which definite assignment checking is done on instance variables. Within these contexts, an assignment to this.\(V\) is recognized as performing an assignment to the name \(V\) for purposes of definite assignment checking.
Local variables and parameters of all sorts can now be declared final:
\[
\text{LocalVariableDeclaration:} = \begin{align*}
\text{ModifiersOpt} & \quad \text{Type} \quad \text{VariableDeclarators} \\
\text{FormalParameter:} & \quad \text{ModifiersOpt} \quad \text{Type} \quad \text{VariableDeclaratorId}
\end{align*}
\]
Such a variable is subject to the usual definite assignment rules governing local variables. In addition, it cannot be assigned to, except for initialization.
A method parameter or catch formal parameter may be declared final. This has no effect on the method signature or the caught exception type. Within the body of the method or catch, the parameter may not be assigned to.
The final declaration modifier may be used to make local variables and parameters available to inner classes.
What are the new binary compatibility requirements for Java 1.1 classes?
In order to binary ensure compatibility between bytecodes output for Java 1.1 compilers from different vendors, and to ensure proper applicability of debuggers and similar tools to those bytecodes, Java makes certain requirements on the form of the bytecodes produced. This section describes the requirements, new in Java 1.1, which pertain to the implementation of various kinds of inner and nested top-level classes.
Bytecode names of classes and interfaces
Instances of the Java Virtual Machines, and Java bytecodes, refer to reference types by means of bytecode names which differ in detail from the names used in Java source code. The bytecode name of a package member $T$ is defined as the name of the package, with every ‘.’ replaced by ‘/’, followed (if the package name is not null) by another ‘/’, and then by the simple name of $T$. The bytecode name of $T$ also serves as a prefix for the bytecode name of every class defined within the body of $T$.
The bytecode name of a class $C$ which is a non-private member of another class, and which is not contained (directly or indirectly) in any block or private class, is defined as the bytecode name of the immediately-enclosing class, followed by ‘$’, followed by the simple name of $C$.
All other classes are called inaccessible. No inaccessible class $N$ can ever be referenced by the code of any other compilation unit. Thus, as long as the name of $N$ is chosen by the compiler in such a way as not to conflict with any other class in the same compilation unit, the name will be globally unique, because (as required previously) its prefix is unique to the package member in which it occurs.
For the sake of tools, there are some additional requirements on the naming of an inaccessible class $N$. Its bytecode name must consist of the bytecode name of an enclosing class (the immediately enclosing class, if it is a member), followed either by ‘$’ and a positive decimal numeral chosen by the compiler, or by ‘$’ and the simple name of $N$, or else by both (in that order). Moreover, the bytecode name of a block-local $N$ must consist of its enclosing package member $T$, the characters ‘$1$’, and $N$, if the resulting name would be unique.
The string produced by the getName method of Class is derived, in all of these cases, from the bytecode name, by replacing ‘/’ by ‘.’. There is no attempt to “clean up” the name to make it resemble Java source code.
The class attribute InnerClasses
The bytecode output of a Java 1.1 compiler may refer (via CONSTANT_Class entries) to bytecode names of classes or interfaces which are not package members. If so, the bytecodes must also contain an class attribute called InnerClasses which declares the encoding of those names. This attribute contains an array of records, one for each encoded name:
```
InnerClasses_attribute {
u2 attribute_name_index;
u4 attribute_length;
u2 number_of_classes;
{
u2 inner_class_info_index; // CONSTANT_Class_info index
u2 outer_class_info_index; // CONSTANT_Class_info index
u2 inner_name_index; // CONSTANT_Utf8_info index
u2 inner_class_access_flags; // access_flags bitmask
classes[number_of_classes]
}
}
```
Each array element records a class with an encoded name, its defining scope, its simple name, and a bitmask of the originally declared, untransformed access flags. If an inner class is not a member, its outer_class_info_index is zero. If a class is anonymous, its inner_name_index is zero.
If a class C was declared protected, the public access flag bit is cleared in its InnerClasses record, even though it is set in C’s access_flags field.
If the outer_class_info_index of a record refers to a class E which itself is not a package member, then an earlier record of the same InnerClasses attribute must describe E.
If a class has members which are types, it must have an InnerClasses attribute, with a record for each of the types. The rules already given imply that a class which is not a package member has an InnerClasses attribute which has a record for it and all of its enclosing classes, except the outermost.
These rules ensure that compilers and debuggers can correctly interpret bytecode names without parsing them, and without opening additional files to examine inner class definitions. Compilers are allowed to omit InnerClasses records for inaccessible classes, but they are encouraged to include records for all classes, especially when the code is being compiled for use with a debugger.
The member attribute Synthetic
As discussed previously, the compiler synthesizes certain hidden fields and methods in order to implement the scoping of names. These fields are private unless noted otherwise, or they are at most of package scope.
Java 1.1 compilers are required, when producing bytecodes, to mark any field or member not directly defined in the source code with an attribute named Synthetic. (At present, the length must be zero.) This will allow other compilers to avoid inadvertent source-level references to non-private hidden members, and will allow tools to avoid displaying them unnecessarily.
(A corresponding mechanism for declaring a local variable to be Synthetic may also be introduced.)
Java 1.1 compilers are strongly encouraged, though not required, to use the following naming conventions when implementing inner classes. Compilers may not use synthetic names of the forms defined here for any other purposes.
A synthetic field pointing to the outermost enclosing instance is named this$0. The next-outermost enclosing instance is this$1, and so forth. (At most one such field is necessary in any given inner class.) A synthetic field containing a copy of a constant \( v \) is named val$\( v \). These fields are final.
All these synthetic fields are initialized by constructor parameters, which have the same names as the fields they initialize. If one of the parameters is the innermost enclosing instance, it is the first. All such constructor parameters are deemed to be synthetic. If the compiler determines that the synthetic field’s value is used only in the code of the constructor, it may omit the field itself, and use only the parameter to implement variable references.
A non-private final synthetic method which grants access to a private member or constructor has a name of the form access$\( N \), where \( N \) is a decimal numeral. The organization of such access protocols is unspecified.
Debuggers and similar tools which are 1.1 compatible must recognize these naming conventions, and organize variable displays and symbol tables accordingly. Note that tools may need to parse these names. Compilers are strongly encouraged to use these conventions, at least by default.
Implementations of the Java Virtual Machine may verify and require that the synthetic members specified here are defined and used properly. It is reasonable to exploit the nature of synthetic members by basing optimization techniques on them.
Further Example: Sample AWT code
The 1.1 version of the Java Abstract Window Toolkit provides a new event handling framework, based on “event listener” interfaces, to which the programmer must write callback objects. The callbacks amount to a flexible new layer between the GUI and the application’s data structures. These adapters must be subclassed to hook them up to the application. The point of this is to avoid the need to subclass the GUI components themselves, or to write complicated if/else and switch statements to interpret event codes.
This design requires that the adapter classes be simpler to write and maintain than the corresponding if/else and switch code! This is where inner classes become important.
Here is an typical example of AWT event handling code. It uses a named inner class App.GUI to organize the GUI code, and anonymous adapters to tie individual GUI components to the application’s methods:
```java
public class App {
void search() { ...do search operation...}
void sort() { ...do sort operation ... }
static public void main(String args[]) {
App app = new App(args);
GUI gui = app.new GUI(); // make a new GUI enclosed by app
}
class GUI extends Frame { // App.GUI is enclosed in an App.
public GUI() {
setLayout(new FlowLayout());
Button b;
add(b = new Button("Search"));
b.addActionListener(
new ActionAdaptor() {
public void actionPerformed(ActionEvent e) {
search(); // App.this.search()
}
}
);
... build a Sort button the same way ...
pack(); show();
}
}
...
}
```
Further Example: An API with coordinated inner classes
Sometimes a class-based API will include as an essential feature secondary classes or interfaces. These latter can be structured quite naturally as static inner classes of the main class.
To see an example of this, imagine a hypothetical utility Sort with an interface Comparer which virtualizes the comparison operation, and a handful of standard reusable comparison implementations. (This example has a flaw: Comparer is generic enough to stand alone.) The code might look like this:
```java
public class Sorter {
public interface Comparer {
/** Returns <0 if x < y, etc. */
int compare(Object x, Object y);
}
public static void sort(Object keys[], Comparer c) {...}
public static void sort(Object keys[], Comparer c,
Object values[]) {...}
public static void sort(String keys[], Object values[])
{ sort(keys, stringComparer, values); }
public static class StringComparer implements Comparer {
public int compare(Object x, Object y) {
if (x == null) return (y == null) ? 0 : -1;
if (y == null) return 1;
return x.toString().compareTo(y.toString());
}
}
public static final Comparer stringComparer
= new StringComparer();
public static class LongComparer implements Comparer {
... long lx = ((Number)x).longValue(); ...
}
public static final Comparer longComparer
= new LongComparer();
/** Compose 2 comparisons, presumably on distinct sub-keys. */
public static class CombinedComparer implements Comparer {...}
public static Comparer combine(Comparer c1, Comparer c2) {...}
}
```
Further Example: Multi-threaded task partitioning.
It is sometimes useful to parallelize a task with independent sub-tasks, by assigning each sub-task to a thread. This can make the whole task finish sooner, if multiple processors are involved. (This will be the case, if the sub-tasks perform network traffic.) In interactive Java programs, multithreading is also used to enable partial results from sub-tasks to be pushed through to the end user, while slower sub-tasks continue to grind away.
The code below (based on an example from Doug Lea) shows a very simple way to control the rendering of several pictures in such a way that each picture is delivered to a displayer as soon as it’s ready, but the original requester blocks until all rendering is finished. Each sub-task is coded by an anonymous implementation of Runnable which is at the heart of each thread.
```java
public class GroupPictureRenderer {
private PictureRenderer renderer;
private PictureDisplayer displayer;
...
public Picture[] render(final byte[][] rawPictures)
throws InterruptedException {
Thread workers[] = new Thread[rawPictures.length];
final Picture results[] = new Picture[rawPictures.length];
// start one thread per rendering sub-task
for (int ii = 0; ii < rawPictures.length; ii++) {
final int i = ii; // capture ii for each new thread
Runnable work = new Runnable() {
public void run() {
results[i] = renderer.render(rawPictures[i]);
displayer.display(results[i]);
}
};
workers[i] = new Thread(work, "Renderer");
workers[i].start();
}
// all threads are running; now wait for them all to finish
for (int i = 0; i < workers.length; i++)
workers[i].join();
// give all the finished pictures to the caller, too:
return results;
}
}
```
|
{"Source-Url": "https://jcp.org/aboutJava/communityprocess/maintenance/JLS/innerclasses.pdf", "len_cl100k_base": 12671, "olmocr-version": "0.1.50", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 63252, "total-output-tokens": 14114, "length": "2e13", "weborganizer": {"__label__adult": 0.0003185272216796875, "__label__art_design": 0.00020635128021240232, "__label__crime_law": 0.0002605915069580078, "__label__education_jobs": 0.0005354881286621094, "__label__entertainment": 3.516674041748047e-05, "__label__fashion_beauty": 0.0001327991485595703, "__label__finance_business": 0.00016605854034423828, "__label__food_dining": 0.00027489662170410156, "__label__games": 0.0003657341003417969, "__label__hardware": 0.0004453659057617187, "__label__health": 0.00022685527801513672, "__label__history": 0.0001380443572998047, "__label__home_hobbies": 6.842613220214844e-05, "__label__industrial": 0.0002290010452270508, "__label__literature": 0.00016701221466064453, "__label__politics": 0.00020635128021240232, "__label__religion": 0.0004010200500488281, "__label__science_tech": 0.0012693405151367188, "__label__social_life": 5.841255187988281e-05, "__label__software": 0.003543853759765625, "__label__software_dev": 0.990234375, "__label__sports_fitness": 0.0002428293228149414, "__label__transportation": 0.0003066062927246094, "__label__travel": 0.00016689300537109375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61762, 0.004]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61762, 0.75677]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61762, 0.87228]], "google_gemma-3-12b-it_contains_pii": [[0, 474, false], [474, 3155, null], [3155, 5723, null], [5723, 7199, null], [7199, 9455, null], [9455, 11531, null], [11531, 13767, null], [13767, 15484, null], [15484, 17651, null], [17651, 19680, null], [19680, 22364, null], [22364, 24538, null], [24538, 27489, null], [27489, 29167, null], [29167, 31060, null], [31060, 33501, null], [33501, 36002, null], [36002, 38551, null], [38551, 40392, null], [40392, 43055, null], [43055, 44966, null], [44966, 46913, null], [46913, 49167, null], [49167, 51670, null], [51670, 53786, null], [53786, 56261, null], [56261, 58018, null], [58018, 59787, null], [59787, 61762, null]], "google_gemma-3-12b-it_is_public_document": [[0, 474, true], [474, 3155, null], [3155, 5723, null], [5723, 7199, null], [7199, 9455, null], [9455, 11531, null], [11531, 13767, null], [13767, 15484, null], [15484, 17651, null], [17651, 19680, null], [19680, 22364, null], [22364, 24538, null], [24538, 27489, null], [27489, 29167, null], [29167, 31060, null], [31060, 33501, null], [33501, 36002, null], [36002, 38551, null], [38551, 40392, null], [40392, 43055, null], [43055, 44966, null], [44966, 46913, null], [46913, 49167, null], [49167, 51670, null], [51670, 53786, null], [53786, 56261, null], [56261, 58018, null], [58018, 59787, null], [59787, 61762, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61762, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61762, null]], "pdf_page_numbers": [[0, 474, 1], [474, 3155, 2], [3155, 5723, 3], [5723, 7199, 4], [7199, 9455, 5], [9455, 11531, 6], [11531, 13767, 7], [13767, 15484, 8], [15484, 17651, 9], [17651, 19680, 10], [19680, 22364, 11], [22364, 24538, 12], [24538, 27489, 13], [27489, 29167, 14], [29167, 31060, 15], [31060, 33501, 16], [33501, 36002, 17], [36002, 38551, 18], [38551, 40392, 19], [40392, 43055, 20], [43055, 44966, 21], [44966, 46913, 22], [46913, 49167, 23], [49167, 51670, 24], [51670, 53786, 25], [53786, 56261, 26], [56261, 58018, 27], [58018, 59787, 28], [59787, 61762, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61762, 0.01964]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
56ae5efdabd60852ac30634f48848f42974e79e5
|
SYSTEMATIC SYNTHESIS OF $\lambda$-TERMS
PIETER KOOPMAN AND RINUS PLASMEIJER
Institute for Computing and Information Sciences, Radboud University Nijmegen, The Netherlands
e-mail address: pieter@cs.ru.nl
Institute for Computing and Information Sciences, Radboud University Nijmegen, The Netherlands
e-mail address: rinus@cs.ru.nl
ABSTRACT. In this paper we show how to generate terms in the $\lambda$-calculus that match a given number of function argument result pairs. It appears that the number of $\lambda$-terms is too large to find terms reasonably fast based on the grammar of $\lambda$-calculus alone. By adding knowledge such as the desired number of arguments it is possible to synthesize $\lambda$-terms effectively for some interesting examples. This yields surprising terms that are unlikely to be found by a human.
An interesting subproblem is the determination of suitability of candidate terms based on equivalence of terms. We used an approximation of equivalence by a finite number of reduction steps. This implies that the test for equivalence can also yield the value undefined. Fortunately the test system used is able to handle undefined test results.
For Henk Barendregt on his sixtieth birthday
1. Introduction
In computer science one often looks for reducts of $\lambda$-expressions (the $\lambda$-expression is seen as a functional program representing the desired value), or general properties of $\lambda$-calculus (like the famous Church-Rosser property). The construction of $\lambda$-terms possessing some desirable property is commonly done manually. In this paper we describe a technique to synthesize such $\lambda$-terms automatically. Typical examples are: find a term $Y$ such that $\forall f. Y f = f (Y f)$, or find a term $s$ such that $\forall n \geq 0. s \ n = \sum_{i=0}^{n} i$. This technique can be used to find rather complicated terms, or terms that are not very intuitive. Although the (mathematical) examples shown in this paper are merely a proof of concept. There exists also serious applications of this kind of synthesis techniques, like the generalization of behavior in adaptive systems. In this paper we concentrate on untyped $\lambda$-terms as described by Barendregt in [1] extended with numbers and some operations on numbers. See [3] for an introduction to typed $\lambda$-calculus.
2000 ACM Subject Classification: D.1.2, I.2.2.
Key words and phrases: Program Synthesis, Automatic Programming, $\lambda$-Terms, programming by example.
The approach to generate λ-terms obeying some property is inspired by our previous work [9]. In that paper we described how one can synthesize functions matching a property such as \( f \ 4 = 5 \land f \ 5 = 8 \). In general there are umpteen functions matching a given set of input-output pairs. In program synthesis it is our goal to find small functions that generalize the given behavior. We prefer a nonrecursive function over a recursive function, and a recursive function is highly preferred over a sequence of conditionals that exactly coincides with the given argument result pairs (like \( f \ x = \text{if} \ (x == 4) 5 \ (\text{if} \ (x == 5) 8 0) \)).
The approach in [9] is to define a data type that represents the grammar of the candidate functions, for our example primitive recursive functions of type \( \text{Int} \rightarrow \text{Int} \) will do. Using the generic generation of instances of this type, abstract syntax trees of candidate functions are generated [8]. Such a syntax tree is turned into the equivalent function. The suitability of these functions is determined by the automatic test system \( \text{GVst} \) [7]. The test system is used to find functions \( f \) matching the desired property, by stating that such a function does not exists, e.g. \( \forall f . \neg(f \ 4 = 5 \land f \ 5 = 8) \). The counterexamples found by \( \text{GVst} \) are exactly the functions wanted. For \( f \ 4 = 5 \land f \ 5 = 8 \) the test system finds the function \( f \ x = \text{if} \ (x<1) 1 \ (f(x-2)+f(x-1)) \), the well known Fibonacci function.
In this paper we do not define a specific grammar for candidate functions, since we want to find ordinary λ-terms matching the given property. For the synthesis of λ-terms we start with the same approach. First we define a data type representing λ-terms and synthesize instances of this type from small to large as candidates. Then we check with the test system if these instances of the data type represent a function (λ-term) obeying the given constraints. However, there are some significant differences compared to the generation of the functions mentioned above. These difference corresponds to problems that needs to be tackled in order to make the systematic synthesis of λ-terms work. First, the termination of computations needed to determine the suitability of candidate λ-terms is an issue. In the generation of ordinary functions, we constructed the functions such that termination of reduction is guaranteed. In our new approach it is not possible to guarantee termination of reduction without too serious restrictions on the terms considered. Second, in order to obtain interesting λ-terms (corresponding to recursive functions) it is essential to have higher order functions. The use of higher order and potentially nonterminating expressions makes the equivalence of λ-terms an issue. Theoretically it is known that the equivalence of λ-terms is in general undecidable. Third, the λ-terms corresponding to recursive functions like the Fibonacci function mentioned above are relative large as well. This is caused by the fine grain computations in λ-calculus. Experience shows that the number of candidate terms to be considered becomes impractically large. Hence we need some guidance in the generation of candidate terms. A fourth difference with previous work is that we will use also logical properties like \( \forall x, y . k \ x \ y = x \) instead of only input-output pairs like \( k \ 1 \ 2 = 1 \).
Problem one and two are covered by using normal order (left most) single step reduction in the comparison of equations. If equivalence is not found in a given number of steps, the equivalence is decided to be undefined. The test system \( \text{GVst} \) is well equipped to handle these undefined test results. The third problem is handled by a simple yet effective and flexible generation algorithm for candidate terms. Although the data type used allows more terms, the synthesis algorithm used generates only instances of a grammar that allows a smaller number of terms. Since we still handle terms prescribing potentially infinite computations, transforming the terms to ordinary expressions and evaluating these is unsafe. For the reduction algorithm however, it is crucial that all terms used are described by a small and simple data type.
In the remainder of this paper we first give a quick overview of testing logical properties using the test tool \texttt{Gvst}. In section 3 we introduce the data structure that will be used to represent $\lambda$-terms. The equivalence of $\lambda$-terms is treated in section 4. Next we use the generic algorithm from \texttt{Gvst} to generate $\lambda$-terms in section 5 and look at the effectiveness of this approach with some examples. In section 6 we introduce more effective algorithms to generate $\lambda$-terms matching a given condition. Finally, there is a conclusion and a discussion of related work in section 7.
2. Testing logical properties with the test tool \texttt{Gvst}
The test system \texttt{Gvst} checks properties in first order logic by evaluating the property for a (large) number of arguments. \texttt{Gvst} is implemented as a library for the functional programming language \texttt{Clean} [10]. This library provides operators corresponding to the logical operators from logic as well as a class of functions called \texttt{test} to check properties.
The test system treats every ordinary function argument as a universally quantified variable if the function is used as a logical property. Consider the function $pAbs \ n = \text{abs} \ n > 0$, where \texttt{abs} is a function from the standard library that computes the absolute value of integer arguments. This function is interpreted by \texttt{Gvst} as the property $\forall n \in \text{Int}. pAbs \ n$. By unfolding the function definition this is $\forall n \in \text{Int}. \text{abs} n > 0$. This property can be tested by executing \texttt{Start = test pAbs}. By the type of the function $pAbs$ to be tested \texttt{Int \rightarrow Bool}, the test system determines that the property should be evaluated for a large number of integers. These test values are synthesized systematically (from small to large for recursive types) by the generic function $ggen$. If \texttt{Gvst} finds a counterexample within the first $\texttt{maxTest}$ tests, the test result is \texttt{CE}. Apart from this test result, the test system gives also information about the counterexample found (like the number of tests done and the values used to find this counterexample). $\texttt{maxTest}$ is the default number of tests, by default 1000. It is easy to change this number in general or in a specific test. Otherwise, the result is \texttt{OK} if \texttt{Gvst} detects that the number of test values is less than $\texttt{maxTest}$ and the property holds for all these test values. If no counterexample is found in the first $\texttt{maxTest}$ tests and there are more than $\texttt{maxTest}$ values in the list generated by $ggen$, the test result is \texttt{Pass}. The test result \texttt{Pass} is weaker than \texttt{OK}: doing additional test might show a counter example if the result is \texttt{Pass}, while \texttt{OK} indicates proof by exhaustive testing.
In the example $pAbs \ n = \text{abs} \ n > 0$ the test system finds a counterexample corresponding to the minimum integer value in the domain for \texttt{test pAbs}. The instance of the generic test suite generator, $ggen$, for integers generates test values like $0$, $1$, $-1$, \texttt{maxint}, and \texttt{minint} that are known to cause often issues somewhere in the beginning of each test suite for integers.
With the operator $\exists$ we can test existentially qualified expressions like $\exists x. f \ x = x$. The operator $\exists$ takes a function as argument. The type of the argument determines the type of test arguments generated by $ggen$ in \texttt{Gvst}. In the example \texttt{pFix} above, we used a nameless function ($\lambda$-expression) as argument for the operator $\exists$. Compared with the ordinary logical notation, we have to write only an additional $\lambda$ between $\exists$ and the variable. Of course one can use any function as argument for the operator $\exists$. \texttt{Clean}'s type inference system detects in this example that $x$ must be an integer. Hence, \texttt{Gvst} will generate integer values.
The test system \texttt{Gvst} is used to handle undefined values. For any function $f :: \text{Int} \rightarrow \text{Int}$ we can test if the function has a fixed point ($\exists x. f \ x = x$) by defining the property:
\[
pFix :: (\text{Int} \rightarrow \text{Int}) \rightarrow \text{Property}
pFix \ f = \exists \lambda x. f \ x = x \quad // \text{the type of x is determined by the context, here Int}
\]
We can test if the function $g \ x = x+1$ has a fixed point by executing $\text{Start} = \text{test} \ (\text{pFix} \ g)$. The test system generates a fixed number of integer values (by default 500) and checks if one of these values makes $g \ x = x$ true. If such a value does not occur the test system can neither decide that the property holds, nor that there is a counterexample. The test system uses the value $\text{Undef}$ to indicate that a positive test result has not been encountered within the tests to be done, but such a value might exist. Hence, the possible test results are:
$$\text{Result} = \text{Pass} | \text{OK} | \text{CE} | \text{Undef}$$
The difference between this test system and a model checker is that the test system evaluates properties using the ordinary evaluation mechanism. A model checker uses an abstraction of the system (the model) as basis for reasoning rather than actual code. A model checker uses also abstract evaluating steps to check the validity of the model (e.g. $\forall x. x = x$). This implies that a model checker is able to prove properties that can only be tested partially by a test system. Advantages of a test system are that no separate model is needed and that the actual code is used rather than a model of this code.
3. A DATA TYPE TO REPRESENT $\lambda$-TERMS
The first step is to construct a data type to represent $\lambda$-terms. Apart from variables, abstraction, and application we introduce numerical constants and constructors $\text{Plus}$ and $\text{If}$ for a primitive addition and conditional in the terms treated. We use the functional programming language Clean for the algorithms in this paper.
```
:: Expr = Var V | Abs V Expr | Ap Expr Expr | Const C | Plus | If // $\lambda$-expression
:: V = V Int // variable
:: C = C Int // constant
```
The additional types $V$ and $C$ are superfluous for the syntax trees describing $\lambda$-terms, but are convenient to control the generation of variables and constants.
Although that it is known that the numerical constants and the constants $\text{Plus}$ and $\text{If}$ are theoretical superfluous [1], it is convenient to introduce them. The use of these constants makes computations much more efficient. Moreover, this representation is much more compact than the representation of constants by Church numbers.
By using tailor made instances of the generic show function, instances of these types can be printed as usual in $\lambda$-calculus. The term $\text{Abs} \ (V \ 1) \ (\text{Ap} \ (\text{Var} \ (V \ 0)) \ (\text{Ap} \ (\text{Var} \ (V \ 1)) \ (\text{Var} \ (V \ 1)))$ will be printed as $\lambda a. (b \ b)$. This is more compact and better readable.
4. EQUIVALENCE OF $\lambda$-TERMS AND REDUCTION
A key step in the search for $\lambda$-terms is determination of the equivalence of terms. Looking for some term $I$ such that $I \ x = x$ the system needs to be able to determine that $(\lambda a. a) \ x$ and $x$ are equivalent. If we write $N = M$ we mean equality modulo reduction: $N =_\beta M$. The terms $M$ and $N$ are $\beta$-convertible if they are equal, if one reduces to the other (i.e. $M \to_\beta N$ or $N \to_\beta M$), or there is a common reduct $L$ of $M$ and $N$ (i.e. $\exists L \in \Lambda. M \to_\beta L \wedge N \to_\beta L$). In general checking whether $N =_\beta M$ is undecidable [1].
The undecidability of convertibility does not imply that it is impossible to look for equivalent terms. It just says that there are terms where the convertibility is unknown. For many terms we can determine whether they are convertible by reducing them a finite number of steps. We will use the normal order (left most) reduction strategy for these reductions.
since it is known to find a normal form if it exists \[1\]. If we find a common reduct (modulo \(\alpha\)-conversion) within this finite number of reduction steps the terms are clearly convertible. If we obtain unequal normal forms the terms are obviously not convertible. If one of the terms shows a cyclic reduction (like \(w w\) where \(w = \lambda x. x\)) that has the property that \(w w \rightarrow^\beta w w\) and the other is not a reduct the terms are also unconvertible. In all other situations the convertibility is considered to be undefined.
To reduce the space consumption in this paper we will only list the rules for the traditional \(\lambda\)-calculus here and ignore the constants. Adding constants is straightforward: two constants are convertible if they are syntactically equal, otherwise they are unconvertible. A constant is unconvertible to any other term in normal form. The convertibility of a constant to a reduct is undefined. The system will do a finite number of reduction steps to determine if it is possible to determine convertibility. We use the constructor \texttt{OK} from the type \texttt{Result} to represent convertibility and \texttt{CE} to indicate inconvertibility.
A single reduction step on an expression is done by the function \texttt{hnf} :\(\text{Expr} \rightarrow (\text{Bool}, \text{Expr})\). The Boolean in the resulting tuple indicates whether a reduction step is done.
\begin{verbatim}
hnf1 :: Expr -> (Bool, Expr)
hnf1 (Ap (Abs v e) a) = (True, sub e v a)
hnf1 (Ap n a) = (r, m) = hnf1 n
/ / the symbol # introduces a let definition in Clean
hnf1 e = (False, e) / / reduction to weak head normal form: no reduction under an abstraction.
\end{verbatim}
The notion of substitution, \(e[v := a]\), in \(\lambda\)-calculus is implemented as \texttt{sub e v a}. The function \texttt{sub} :\(\text{Expr} \rightarrow\text{Expr} \rightarrow\text{Expr}\) replaces each free occurrence of the second argument in the first argument by the third argument.
\begin{verbatim}
sub m=(Var v) x n = if (v==x) n m
sub m=(Abs y e) x n |
| x==y = m
| isMember y (freeVars n) / / x \neq y: makes this \(\lambda y\) an undesirable binding in m?
| = Abs v (sub (sub e y (Var v)) x n) / / yes, rename y to v in m before actual substitution
| = Abs y (sub e x n) / / no, continue with substitution in e
where v = newVar startVal |x:freeVars m++freeVars n] / / a fresh variable
\end{verbatim}
The function \texttt{freeVars} yields a list containing the free variables in the given expression. The expression \texttt{newVar n 1} yields the first variable starting at \(v n\) that does not occur in the list of variables \(1\). This is used to prevent undesirable binding of variables in examples such as \(\lambda a. a b[b := a c]\). By the renaming of variables this is transformed to \(\lambda d.d b[b := a c]\).
The complete function \texttt{hnf1} also contains alternatives for the constants \texttt{Plus} and \texttt{If}. When both arguments of the \texttt{Plus} are constants the expression is replaced by a new constant, otherwise \texttt{hnf1} tries to evaluate arguments of the addition. For the conditional expression numbers are interpreted as Booleans. Positive numbers are interpreted as the Boolean value True, all other values as False. If the subterm \(c\) in a term \(\texttt{Ap (Ap (Ap If c) t)}\) is not a constant, the function \texttt{hnf1} tries to reduce it.
As a first step to determine convertibility we define \(\alpha\)-equality. Two expressions are \(\alpha\)-equal (result \texttt{OK}) if they can be made identical by \(\alpha\)-conversion of variables introduced by abstractions within the expressions. If the expressions are not \(\alpha\)-equal and are not in normal
form the result is undefined (\texttt{Undef}). Otherwise the expressions are clearly not \(\alpha\)-equal, and the result is \texttt{CE}.
\begin{verbatim}
alphaEQ :: Expr Expr -> Result
alphaEQ (Var x) (Var y) = if (x==y) OK CE
alphaEQ (Var x) (Abs v e) = CE
alphaEQ (Abs v e) (Var y) = CE
alphaEQ (Abs x e1) (Abs y e2)
| x == y
= alphaEQ e1 e2
| not (isMember x (freeVars e2))
= alphaEQ e1 (sub e2 y (Var x)) // \(\alpha\)-conversion: \(e2[y:=x]\)
| not (isMember y (freeVars e1))
= alphaEQ (sub e1 x (Var y)) e2 // \(\alpha\)-conversion: \(e1[x:=y]\)
= alphaEQ (sub e1 x (Var v)) (sub e2 y (Var v)) // \(\alpha\)-conversion: \(e1[x:=v]\) and \(e2[y:=v]\)
where v = newVar startVal (freeVars e1++freeVars e2) // a fresh variable
alphaEQ e1=:(Ap f x) e2=:(Ap g y)
= case alphaEQ f g of
OK = case alphaEQ x y of
CE = if (isRedex e1 || isRedex e2) Undef CE
r = r
CE = if (isRedex e1 || isRedex e2) Undef CE
Undef = Undef
alphaEQ e1 e2 = Undef
\end{verbatim}
The equivalence (convertability) of expressions is determined by the infix operator \(=\).
\begin{verbatim}
(\equiv) infix 4 :: Expr Expr -> Result
(\equiv) x y = redEQ maxReductions [x] [y]
\end{verbatim}
The constant \texttt{maxReductions} determines the maximum number of reductions done on the expressions. This is a trade-off between speed and the ability to determine the convertibility of expressions. In the tests reported in this paper the value 500 was used to full satisfaction. If we use examples where more reductions are needed to determine equality, the constant \texttt{maxReductions} should be increased. For most examples a value of 50 is more than enough.
The real work to determine convertibility is done by \texttt{redEQ}.
The function \texttt{redEQ} gets the number of reduction steps to be done and two stacks of expressions as arguments. If the number of steps to be done is zero, the result of determining equality is \texttt{Undef} unless one of the terms shows cyclic reduction and the other is in head normal form (in that case the result is \texttt{CE}). If the number of steps to be done is not zero, the function \texttt{redEQ} determines \(\alpha\)-equality of the top of one stack (the most recent expression) and one of the elements in the other stack is unequal to \texttt{Undef}. Any results unequal to \texttt{Undef} determines the result of \texttt{redEQ}. If all comparisons for \(\alpha\)-equality yield \texttt{Undef}, we try to reduce the most recent expressions one single step. If such a reduction is possible for at least one of the terms, the function \texttt{redEQ} continues recursively with the new expressions. Otherwise we decompose an application or abstraction if it occurs in both expressions to be compared, and continue with the fragments of the expressions to be compared. In all other situations the given expressions are unequal under reduction: the result is \texttt{CE}.
\begin{verbatim}
redEQ :: Int [Expr] [Expr] -> Result
redEQ n lx=:[x:xs] ly=:[y:ys]
| n==0
| (isMem x xs == OK && ~(isRedex y)) || (isMem y ys == OK && ~(isRedex x))
| x==y = alphaEQ e1 e2
| not (isMember x (freeVars e2))
= alphaEQ e1 (sub e2 y (Var x)) // \(\alpha\)-conversion: \(e2[y:=x]\)
| not (isMember y (freeVars e1))
= alphaEQ (sub e1 x (Var y)) e2 // \(\alpha\)-conversion: \(e1[x:=y]\)
= alphaEQ (sub e1 x (Var v)) (sub e2 y (Var v)) // \(\alpha\)-conversion: \(e1[x:=v]\) and \(e2[y:=v]\)
where v = newVar startVal (freeVars e1++freeVars e2) // a fresh variable
\end{verbatim}
The function \texttt{isMem} looks for a result unequal to \texttt{Undef} in the list of results. If such a value exists, the result of the application is the value of the first list element unequal to \texttt{Undef}, otherwise the result is \texttt{Undef}.
\begin{verbatim}
let isMem x [] = Undef
isMem x [a:x] = case alphaEQ x a of
Undef = isMem x r
result = result
\end{verbatim}
This is sufficient to compare \(\lambda\)-terms. In a number of examples the result of comparison might be undefined, but for each property the test system will generate a lot of test arguments. Usually some of these arguments will show whether the property holds or not. Some improvements of the algorithm to compare expressions are possible. For instance, expressions with a different type, such as \(\lambda a. a\) and 0, will always be unequal.
5. \textbf{Generic generation of \(\lambda\)-terms}
In order to find \(\lambda\)-terms matching some property, the test system needs to generate candidate expressions. Since \texttt{Gyst} contains a generic algorithm to generate the members of a type, we can completely derive the generation of candidates. In order to limit the search space (and hence speed up the finding of matching \(\lambda\)-terms) we limit the number of variables to 3, and use only the often occurring constants \(-1, 1\) and \(2\):
The generation of expressions is done by the generic algorithm. We derive an instance of this algorithm for this type by:
derive ggen Expr
If we would have used the generic algorithm to derive the generation of values for the types V and C, values like V minint and C maxint would have been generated. We considered this undesirable in this situation and hence we used a tailor made instance of ggen for these types. This is all we need to get started.
5.1. Some examples. Let's start with a very simple example: a \( \lambda \text{-term } i \) with the property \( \forall x. i x = x \). We state that such a term does not exist: \( \forall i : \text{A} . \neg \forall x : \text{A} (i x = x) \). The test system will try to find counterexamples of this properties. The counterexample found are exactly the \( \text{A} \)-terms obeying \( i x = x \). The property expressed in \text{GVst} reads:
\[
p_{\text{I}} :: \text{Expr} \rightarrow \text{Property}
p_{\text{I}} i = \neg (\forall \lambda x. \text{Ap} i x \equiv x)
\]
\text{GVst} uses the generic algorithm to generate candidate expressions for \( i \) and \( d \). The first ten identity functions found by testing this property are: \( \lambda a. a \), \( \lambda b. b \), \( \lambda c. c \), \( \lambda a. a \), \( \lambda a. ((\lambda b. a) \text{Plus}) \), \( \lambda b. ((\lambda a. b) \text{Plus}) \), \( \lambda a. ((\lambda b. a) \text{Plus}) \), and \( \lambda a. ((\lambda c. a) \text{Plus}) \). For these ten matching \( \lambda \)-terms the system had to generate only 464 candidate expressions. Note that we use here a property with a universal quantifier rather than some input-output pairs (like \( i 1 = 1 \), \( i (\lambda a. a) = \lambda a. a \) and \( i ((\lambda a. a) (\lambda a. a)) = ((\lambda a. a) (\lambda a. a)) \)). After the preparations described above, \text{GVst} is very well capable of testing this kind of properties. In our opinion the property shown above is clearer and more elegant than the explicit input-output pairs of the function \( i \). Of course it is still possible to search for functions using input-output pairs.
In the same spirit we can look for terms representing the K-combinator by:
\[
p_{\text{K}} :: \text{Expr} \rightarrow \text{Property}
p_{\text{K}} k = \neg (\forall \lambda x y. \text{Ap} (\text{Ap} k x) y \equiv x)
\]
As expected the system produces terms like \( \lambda a. \lambda b. a \) and \( \lambda a. \lambda b. b \) within the same number of candidates. The system finds also some less obvious terms like \( \lambda a. \lambda b. ((\lambda a. a) \text{Plus}) \) and \( \lambda a. \lambda b. \text{If } a \text{ - } 1 \).
For functions that only have to work on arguments of a specific type, e.g. numeric constants of the form \( \text{Const } (c \ i) \), the \( \forall \) operator will generate undesired arguments if the type of arguments is \text{Expr}. It is not relevant to know what a plus operator does on free variables or arguments like \( \lambda a. a \), hence we should exclude them from the property and the tests. This problem can easily be tackled by using a quantification over type \text{Int} and the needed type conversion in the property.
\[
p_{\text{Plus}} :: \text{Expr} \rightarrow \text{Property}
p_{\text{Plus}} p = \neg (\forall \lambda a b. \text{Ap} (\text{Ap} p (\text{Const } (c a))) (\text{Const } (c b)) \equiv \text{Const } (c (a b)))
\]
This will produce correct \( \lambda \)-terms for \( p \) like \( \text{Plus}, (\lambda a. a) \text{Plus}, \lambda a. \text{Plus } a, \lambda a. \text{Plus } b, (\lambda a. \text{Plus}) a, \) and \( (\lambda a. \text{Plus}) (-1 -1) \). If we do not want to use all integers in the property or have only specific input-output combination available, the property will not contain a \( \forall \)-operator. We use the given input-output pairs in the property. For example:
The operator \( \& \& \& \) is the logical and for values of type Result. Matching \( \lambda \)-terms found are \( \lambda a.\lambda b.(\text{Plus} b) \; b \), \( \lambda a.\lambda b.(\text{Plus} a) \; b \), \( \lambda a.\lambda b.(\text{Plus} b) \; a \), and \( \lambda a.\lambda b.(\text{Plus} ((\text{Plus} b) \; b)) \; 0 \).
Although these examples work fine, they show also that expressions are generated that are usually considered undesirable like \( \lambda a.\text{Plus} \; b \) (where \( b \) is a free variable) and \( (\lambda a.\text{Plus}) \; (-1 \; -1) \) (with the constant \(-1\) at a function position). In these examples these terms are only curious, but they do occupy space in the search space and hence time during the search for the desired \( \lambda \)-terms. If we search \( \lambda \)-terms implementing the Y-combinators by testing:
\[
\text{pY} :: \text{Expr} \rightarrow \text{Result}
\]
\[
\text{pY} \; y = \neg((\forall x.\text{Ap} \; y \; f) \equiv \text{Ap} \; f \; (\text{Ap} \; y \; f))
\]
no success is found in the first 1,000,000 tests. The search space is simply too large to find a suitable term in a reasonable time.
### 6. Smarter Generation of \( \lambda \)-terms
There are umpteen way to reduce the search space. An unattractive alternative is to reject candidates that represent wrongly typed \( \lambda \)-terms in a property, as these terms will still be generated and hence consume resources. It will be better to prevent the generation of terms that are clearly unsuitable. Take care not to eliminate the wanted terms. In this section we describe an approach to generate better candidate terms.
With a few simple restrictions we can generate much better candidate \( \lambda \)-terms. First, we will always generate a number of abstractions that corresponds to the number of arguments needed by the function at hand. Second, there is no need to generate open \( \lambda \)-terms. In the generation we keep track of the bound variables and only generate them at applied occurrences. In principle that can be further improved by keeping track of the type of these variables, as done by Katayama [6]. Third, we will generate the right number of arguments for constants like Plus and If. Forth, it is useless to generate numerical constants as first argument of an Ap. Fifth, if the right constants are generated then there is no need to generate complex subexpressions containing only constants.
For \( \text{pY} \) defined above we clearly need a higher order function. Hence we add the introduction of new abstractions in the generated expressions. The function \( \text{ho} \) generates higher order candidate functions. The first argument of \( \text{ho} \) is the number of arguments needed, the second argument a list of the bound variables, and the last argument the name (number) of the next argument.
\[
\text{ho} :: \text{Int} \; \text{[V]} \; \text{Int} \rightarrow \text{[Expr]}
\]
\[
\text{ho} \; 0 \; \text{vs} \; x = r
\]
where
\[
\begin{align*}
\text{r} & = 1 \mid [\text{Const} \; (\text{C} \; i) \; \mid i \, \in \, [-1,1]] \\
\text{l} & = [\text{Var} \; v \quad \mid v \, \in \, \text{vs}] \\
& \quad | [\text{Ap} \; e1 \; e2 \quad \mid (e1,e2) \, \leftarrow \, \text{diag2} \; 1 \; r] \\
& \quad | [\text{Abs} \; (\text{V} \; x) \; e \quad \mid e \, \leftarrow \, \text{ho} \; (i-1) \; \text{[V} \; x:\text{vs}] \; (x+1)] \\
& \quad | [\text{Ap} \; (\text{Ap} \; \text{Plus} \; e1) \; e2 \quad \mid (e1,e2) \, \leftarrow \, \text{diag2} \; 1 \; r]
\end{align*}
\]
\[
\text{ho} \; i \; \text{vs} \; x = [\text{Abs} \; (\text{V} \; x) \; e \quad \mid e \, \leftarrow \, \text{ho} \; (i-1) \; \text{[V} \; x:\text{vs}] \; (x+1)]
\]
As a grammar this is:
\[
ho \ n \ m = \lambda v_n \ldots \lambda v_1 . r
\]
where \( r = l | -1 | 1 \)
\[
l = v_m | \ldots | v_1 | l \ r | \lambda v_{n+1}.ho0 \ (m+1) | (plus \ l) \ r
\]
The infix operator \(| .\) merges two lists into a single list by taking elements from the argument lists in turn.
\[
[| .] \text{infixl } 4 :: [x] [x] \rightarrow [x]
\]
\[
[| .] \ [a:x] \ y = [a: y | . x] \quad // \text{note the swap of argument}
\]
\[
[| .] \ [] y = y
\]
Now the first 1,000,000 candidates generated contain 7 Y-combinators. Some examples are
\[
\lambda a.((\lambda b. b) ((\lambda b. a (b b)) (\lambda b. a (b b)))) \quad \lambda a.((\lambda b. b) ((\lambda b. a (b b)) (\lambda b. a (b b)))).
\]
Most interesting functions are recursive. However, this does not imply that we need to
generate higher order \(\lambda\)-terms. It is sufficient to generate terms containing an application of
a predefined Y-combinator. Moreover, for recursive functions that yield a nonrecursive type,
like Int, it is essential to contain a stop condition. That is, after the Y-combinator there
should be a conditional (an If) before the recursive occurrence of the recursive function.
This is exactly what the generator of \(\lambda\)-terms fun does.
\[
\text{fun} :: \text{Int} \rightarrow [\text{Expr}]
\]
\[
\text{fun} \ n = [\text{abs} 1 \ n \ e \ \langle e \leftarrow r \rangle \ | \ [\text{Ap exprY} \ (\text{abs} \ 0 \ (n+1) \ e) \ \langle e \leftarrow r\text{Fun} \rangle]
\]
where
\[
\text{vars} = [\text{Var} (V v) \ \langle v \leftarrow [1..n] \rangle] \quad // \text{V 0 is the recursive fun if it exists}
\]
\[
r \ c = [\text{Const} \ (C i) \ \langle i \leftarrow [-1,1,-2] \rangle \ | \ e \ c]
\]
\[
e \ c = \text{vars} \ | \ [\text{Ap} \ (\text{Ap plus} \ e1) \ e2 \ \langle e1,e2 \leftarrow \text{diag2} \ (e \ c) \ (r \ c) \rangle \ | \ c]
\]
\[
r\text{Fun} = [\text{Ap} \ (\text{Ap if} \ c \ t) \ e]
\]
\[
\langle c,t,e \rangle \leftarrow \text{diag3 simple} \ (e \ (r\text{App} \ n)) \ [(\text{Const} \ (C i) \ \langle i \leftarrow [0,1] \ | \ \text{vars})]
\]
\[
r\text{App} \ 0 = [\text{Var} \ (V 0)]
\]
\[
r\text{App} \ n = [\text{Ap} \ f \ a \langle f,a \rangle \leftarrow \text{diag2} \ (r\text{App} \ (n-1)) \ \text{simple}]
\]
\[
simple = \text{vars} \ | \ [\text{Ap} \ (\text{Ap plus} \ v) \ \langle v,c \rangle \leftarrow \text{diag2} \ \text{vars} \ [\text{Const} \ (C i) \ \langle i \leftarrow [-1,-2] \rangle]
\]
\[
\text{abs} \ n \ e = e
\]
\[
\text{abs} \ n \ n \ e = \text{Abs} \ (V n) \ (\text{abs} \ (n+1) \ (n-1) \ e)
\]
Using this generation function we will look for a term that implements multiplication by
repeated addition. Since we want to prevent (very) large values as arguments for this
multiplication function (it is \(O(n)\)), we select some test values manually rather than using
a quantification over all integers.
\[
p\text{Times} = \langle f 0 \ 3 \ && f 2 \ 4 \ && f 7 \ 5 \ && f 3 \ 0 \rangle
\]
\[
\text{where} \ f \ a \ b = \text{Ap} \ (\text{Ap p} \ (\text{Const} \ (C a))) \ (\text{Const} \ (C b)) \ \equiv \ \text{Const} \ (C \ (a*b))
\]
We look for 2-argument terms generated by the function \(\text{fun}\) by testing \(p\text{Times}\) For \((\text{fun} \ 2)\).
The system produces multiplication functions for non-negative numbers of the form:
\[
Y \ (\lambda a.\lambda b.\lambda c.((\text{if} \ c) \ (\text{plus} \ ((a \ (\text{plus} \ c \ -1)) \ b)) \ b)) \ 0),
\]
\[
Y \ (\lambda a.\lambda b.\lambda c.((\text{if} \ c) \ (\text{plus} \ ((a \ (\text{plus} \ c \ -1)) \ b)) \ b)) \ c)
\]
and terms that a human is more likely to write
\[
Y \ (\lambda a.\lambda b.\lambda c.((\text{if} \ c) \ (\text{plus} \ ((a \ b) \ ((\text{plus} \ c \ -1))) \ b)) \ 0),
\]
\[
Y \ (\lambda a.\lambda b.\lambda c.((\text{if} \ b) \ (\text{plus} \ ((a \ ((\text{plus} \ b \ -1)) \ c)) \ 0)) \ 0)
\]
In these expressions we use $y$ as abbreviation of the term $(\lambda a. (\lambda b. a (b b)) (\lambda b. a (b b)))$. The first two terms are somewhat peculiar due to the swap of arguments. As a direct recursive function the second term is:
$$f b c = \text{if } (c > 0) (b+f (c-1) b) c$$
Although this function looks extraordinary through the swap of arguments, it computes the desired product of non-negative arguments.
Terms for $s n = \sum_{i=0}^{n} i$ are found by testing $p\text{Sum For (fun 1)}$ with
$$p\text{Sum } p = \neg(f 3 \&\& f 5) \text{ where } f a = Ap p (\text{Const } (C a)) \equiv \text{Const } (C (\text{sum } [1..a]))$$
The first term found is $Y (\lambda a. \lambda b. ((\text{If } b) ((\text{Plus } (a ((\text{Plus } b) -1))) b)) 0$.
In the same way we can look for $\lambda$-terms matching $f 4 = 5 \land f 5 = 8$ from the introductions by looking for counterexamples for:
$$p\text{Fib } p = \neg(f 4 5 \&\& f 5 8) \text{ where } f a b = Ap p (\text{Const } (C a)) \equiv \text{Const } (C b)$$
The first solutions found by testing $p\text{Fib For (fun 1)}$ are not the Fibonacci function found in our earlier work, but nonrecursive terms such as
$$Ab. ((\text{Plus } ((\text{Plus } ((\text{Plus } ((\text{Plus } b) -1))) -1)) -1)) b)$$
and some single-recursive term like
$$Y (\lambda a. \lambda b. ((\text{If } ((\text{Plus } b) -2)) ((\text{Plus } (a ((\text{Plus } b) -1))) ((\text{Plus } ((\text{Plus } b) -1)) -1))) b)$$
Counterexample 13 found after 1583 test is the first (double-recursive) Fibonacci function:
$$Y (\lambda a. \lambda b. ((\text{If } ((\text{Plus } b) -1)) ((\text{Plus } (a ((\text{Plus } b) -2))) (a ((\text{Plus } b) -1)))) 1)$$
By adding $f 6 = 13$ to the patterns to be matched, this is the first term found.
The speed of generating and testing candidate functions depends strongly on the condition that has to be evaluated and the size of the expression. On a rather slow (1GHz) Windows XP laptop we measured a speed of 500 to 200,000 candidate terms per second.
7. Discussion and related work
In this paper we demonstrate that it is possible to find $\lambda$-terms matching some condition by systematic synthesis of candidate expressions. Since we want to be able to find terms like the $Y$-combinator, restricting ourselves to terminating expressions is no option. This implies that testing the suitability of a candidate expression is rather delicate. The equivalence of terms is known to be undecidable. In this paper we used a simple approximation: a finite (and rather small) normal order reduction steps are done on the terms to be compared. If the reduction sequences contains elements that are $\alpha$-equal the terms are obviously $\alpha$-equivalent. If the terms are unequal normal forms the terms are non-equivalent. Otherwise the equivalence has the value undefined.
It appears that the number of $\lambda$-terms is too large to find most interesting terms by brute force search in reasonable time. We have introduced two rather simple but effective generators for expressions. The first one generates higher order terms like the famous $Y$-combinator. The second one generates (recursive) functions like multiplication by repeated addition and the Fibonacci function. By using type information it is possible to generate candidate functions even more effectively. Katayama [6] uses this in his generation of functions matching examples. He generates only first order terms, all other things (like recursion) have to be defined as a recursion pattern in a library of primitive functions.
Broda [5] and Wang [11] discuss algorithms to generate \( \lambda \)-terms randomly. Broda uses a grammar to specify the type of the terms, somewhat similar to our generation functions. Henk Barendregt has touched the generation of \( \lambda \)-terms via enumeration in [1, 2, 4].
By adding constructs like the \( Y \)-combinator and multiplication to the terms, the generated terms become more powerful. Hence complex functions will be found quicker.
Without the struggle for nontermination, it is more elegant to introduce a type class \texttt{eval} to evaluate instances of various grammars represented as type [9]. The grammar of the candidate terms can then elegantly and effectively be determined by more specific types. The types control the generation of candidate functions at a higher level of abstraction than the generation functions used in section 6. When intermediate terms in the reduction need to be compared, as needed to compare \( \lambda \)-terms for equivalence, this is not possible.
We find \( \lambda \)-terms generalizing the behavior of the given input-output pairs or properties. Both the obvious functions and more surprising \( \lambda \)-terms are synthesized. If the goal is to find only primitive recursive functions the direct approach in [9] is more effective. This paper shows that it is possible to find the primitive recursive functions as well as other \( \lambda \)-term-like the \( Y \)-combinator. The advantage of the approach introduced in this paper is that it is able to synthesize \( \lambda \)-terms for general properties without the need to define a very precise grammar for the candidate functions. Some guidance is needed to find larger terms, but the generators might produce totally wrong candidates (like ill-typed terms or terms with nonterminating reduction sequences) without causing any trouble.
**Acknowledgement**
The authors wish to thank the anonymous referees, the editors and Peter Achten for their suggestions to improve this paper.
**References**
|
{"Source-Url": "http://repository.ubn.ru.nl/bitstream/handle/2066/36536/36536.pdf?sequence=1", "len_cl100k_base": 11094, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 31876, "total-output-tokens": 12729, "length": "2e13", "weborganizer": {"__label__adult": 0.0005054473876953125, "__label__art_design": 0.00067138671875, "__label__crime_law": 0.0004529953002929687, "__label__education_jobs": 0.0019502639770507812, "__label__entertainment": 0.00014472007751464844, "__label__fashion_beauty": 0.00023674964904785156, "__label__finance_business": 0.00034356117248535156, "__label__food_dining": 0.0006322860717773438, "__label__games": 0.0008029937744140625, "__label__hardware": 0.0012521743774414062, "__label__health": 0.001110076904296875, "__label__history": 0.000461578369140625, "__label__home_hobbies": 0.00017440319061279297, "__label__industrial": 0.0006399154663085938, "__label__literature": 0.000713348388671875, "__label__politics": 0.0004527568817138672, "__label__religion": 0.0009136199951171876, "__label__science_tech": 0.12109375, "__label__social_life": 0.0001883506774902344, "__label__software": 0.005191802978515625, "__label__software_dev": 0.8603515625, "__label__sports_fitness": 0.0004470348358154297, "__label__transportation": 0.0008969306945800781, "__label__travel": 0.0002655982971191406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42580, 0.01274]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42580, 0.73227]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42580, 0.7997]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2508, false], [2508, 6855, null], [6855, 11352, null], [11352, 15087, null], [15087, 18836, null], [18836, 22400, null], [22400, 23747, null], [23747, 27629, null], [27629, 31339, null], [31339, 35173, null], [35173, 38750, null], [38750, 42580, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2508, true], [2508, 6855, null], [6855, 11352, null], [11352, 15087, null], [15087, 18836, null], [18836, 22400, null], [22400, 23747, null], [23747, 27629, null], [27629, 31339, null], [31339, 35173, null], [35173, 38750, null], [38750, 42580, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42580, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42580, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2508, 2], [2508, 6855, 3], [6855, 11352, 4], [11352, 15087, 5], [15087, 18836, 6], [18836, 22400, 7], [22400, 23747, 8], [23747, 27629, 9], [27629, 31339, 10], [31339, 35173, 11], [35173, 38750, 12], [38750, 42580, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42580, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
055e4d9d52aa8291d834ba7d313e040bcebd0d2c
|
An Exploratory Study of the Pull-based Software Development Model
Georgios Gousios, Martin Pinzger, and Arie van Deursen
Report TUD-SERG-2014-005
An Exploratory Study of the Pull-Based Software Development Model
Georgios Gousios
Delft University of Technology
Delft, The Netherlands
G.Gousios@tudelft.nl
Martin Pinzger
University of Klagenfurt
Klagenfurt, Austria
martin.pinzger@aau.at
Arie van Deursen
Delft University of Technology
Delft, The Netherlands
Arie.vandeursen@tudelft.nl
ABSTRACT
The advent of distributed version control systems has led to the development of a new paradigm for distributed software development; instead of pushing changes to a central repository, developers pull them from other repositories and merge them locally. Various code hosting sites, notably Github, have tapped on the opportunity to facilitate pull-based development by offering workflow support tools, such as code reviewing systems and integrated issue trackers. In this work, we explore how pull-based software development works, first on the Github torrent corpus and then on a carefully selected sample of 291 projects. We find that the pull request model offers fast turnaround, increased opportunities for community engagement and decreased time to incorporate contributions. We show that a relatively small number of factors affect both the decision to merge a pull request and the time to process it. We also examine the reasons for pull request rejection and find that technical ones are only a small minority.
Categories and Subject Descriptors
D.2.7 [Software Engineering]: Distribution, Maintenance, and Enhancement—Version control; D.2.9 [Software Engineering]: Management—Programming teams
General Terms
Management
Keywords
Pull-based development, pull request, distributed software development, empirical software engineering
1. INTRODUCTION
Pull-based development is an emerging paradigm for distributed software development. As more developers appreciate isolated development and branching [7], more projects, both closed source and, especially, open source, are being migrated to code hosting sites such as Github and Bitbucket, which provide support for pull-based development [2]. A unique characteristic of such sites is that they allow any user to clone any public repository. The clone creates a public project that belongs to the user that cloned it, so the user can modify the repository without being part of the development team. Furthermore, such sites automate the selective contribution of commits from the clone to the source through pull requests.
Pull requests as a distributed development model in general, and as implemented by Github in particular, form a new method for collaborating on distributed software development. The novelty lays in the decoupling of the development effort from the decision to incorporate the results of the development in the code base. By separating the concerns of building artifacts and integrating changes, work is cleanly distributed between a contributor team that submits, often occasional, changes to be considered for merging and a core team that oversees the merge process, providing feedback, conducting tests, requesting changes, and finally accepting the contributions.
Previous work has identified the processes of collaboration in distributed development through patch submission and acceptance [23, 5, 32]. There are many similarities to the way pull requests work; for example, similar work team structures emerge, since typically pull requests go through an assessment process. What pull requests offer in addition is process automation and centralization of information. With pull requests, the code does not have to leave the revision control system, and therefore it can be versioned across repositories, while authorship information is effortlessly maintained. Communication about the change is context-specific, being rooted on a single pull request. Moreover, the review mechanism that Github incorporates has the additional effect of improving awareness [9]; core developers can access in an efficient way all information that relates to a pull request and solicit opinions of the community ("crowd-source") about the merging decision.
A distributed development workflow is effective if pull requests are eventually accepted, and it is efficient if the time this takes is as short as possible. Advancing our insight in the effectiveness and efficiency of pull request handling is of direct interest to contributors and developers alike. The goal of this work is to obtain a deep understanding of pull request usage and to analyze the factors that affect the efficiency of the pull-based software development model. Specifically, the questions we are trying to answer are:
RQ1 How popular is the pull based development model?
RQ2 What are the lifecycle characteristics of pull requests?
RQ3 What factors affect the decision and the time required to merge a pull request?
RQ4 Why are some pull requests not merged?
Our study is based on data from the Github collaborative development forge, as made available through our GHTorrent project [16]. Using it, we first explore the use of almost 2 million pull requests across all projects in Github. We then examine 291 carefully selected Ruby, Python, Java and Scala projects (in total, 166,884 pull requests), and identify, using qualitative and quantitative analysis, the factors that affect pull request lifetime, merging and rejection.
2. BACKGROUND
Since the appearance of the first open source implementations in 2001, distributed version control systems (DVCS), notably Git [8], have revolutionized the way distributed software development is carried out. Driven by pragmatic needs, most DVCSs were designed from scratch to work as advanced patch management systems, rather than versioned file systems, the then dominant version control paradigm. In most DVCSs, a file is an ordered set of changes, the serial application of which leads to the current state. Changes are stamped by globally unique identifiers, which can be used to track the commit’s content across repositories. When integrating changes, the change sets can originate from a local filesystem or a remote host; tools facilitate the acquisition and application of change sets on a local mirror. The distributed nature of DVCSs enables a pull-based development model, where changes are offered to a project repository through a network of project forks; it is up to the repository owner to accept or reject the incoming pull requests.
The purpose of distributed development is to enable a potential contributor to submit a set of changes to a software project managed by a core team. The development models afforded by DVCSs are a superset of those in traditional control environments [31, 6]. With respect to receiving and processing external contributions, the following strategies can be employed with DVCSs:
**Shared repository.** The core team shares the project’s repository, with read and write permissions, with the contributors. To work, contributors clone it locally, modify its contents, potentially introducing new branches, and push their changes back to the central one. To cope with multiple versions and multiple developers, larger projects usually adopt a branching model, i.e., an organized way to inspect and test contributions before those are merged to the main development branch [7].
**Pull requests.** The project’s main repository is not shared among potential contributors; instead, contributors fork (clone) the repository and make their changes independent of each other. When a set of changes is ready to be submitted to the main repository, they create a pull request, which specifies a local branch to be merged with a branch in the main repository. A member of the project’s core team is then responsible to inspect the changes and pull them to the project’s master branch. If changes are considered unsatisfactory, more changes may be requested; in that case, contributors need to update their local branches with new commits. Furthermore, as pull requests only specify branches from which certain commits can be pulled, there is nothing that forbids their use in the shared repository approach (cross-branch pull requests). An overview of the pull request process can be seen in Figure 1.
**Pull Requests in Github.** Github supports all types of distributed development outlined above; however, pull requests receive special treatment. The site is tuned to allow easy forking of projects by contributors, while facilitating the generation of pull requests through automatic comparison of project branches. Github’s pull request model follows the generic pattern presented above; in addition it provides tools for contextual discussions and in-line code reviews. An example pull request on Github can be seen in Figure 2.
A Github pull request contains a branch (local or in another repository) from which a core team member should pull commits. Github automatically discovers the commits to be merged and presents them in the pull request. By default, pull requests are submitted to the base (“upstream” in Git parlance) repository for inspection. The inspection is either a code review of the commits submitted with the pull request or a discussion about the features introduced by the pull request. Any Github user can participate to both types of inspection. As a result of the inspection, pull requests can be updated with new commits or be closed as redundant, uninteresting or duplicate. In case of an update, the contributor creates new commits in the forked repository, while Github automatically updates the displayed commits. The code inspection can then be repeated on the refreshed commits.
When the inspection process finishes and the pull requests are deemed satisfactory, the pull request can be merged. A pull request can only be merged by core team members. The versatility of Git enables pull requests to be merged in three ways, presented below sorted by the amount of preservation of the original source code properties:
1. **Through Github facilities.** Github can automatically verify whether a pull request can be merged without conflicts to the base repository. When a merge is requested, Github will automatically apply the commits in the pull request and record the merge event. All authorship and history information is maintained in the merged commits.
2. **Using Git merge.** When a pull request cannot be applied cleanly or when project-related policies do not permit automatic merging, a pull request can be merged using plain Git utilities, using the following techniques:
- **Branch merging:** The branch in the forked repository containing the pull request commits is merged into a branch in the base repository. Both history and authorship information are maintained, but Github cannot detect the merge in order to record a merge event [8, Chapter 3.2].
- **Cherry-picking:** Instead of merging all commits, the merger picks specific commits from the remote branch, which then applies to the upstream branch. The unique commit identifier changes, so exact history cannot be maintained, but authorship is preserved [8, Chapter 5.3].
A technique that complements both of the above is **commit squashing**: if the full history is not of interest to the project, several
issues. Moreover, issue discussions can include links to pull requests, which can be managed using the same facilities used for issues.
This duality enables the core team to treat pull requests as work items to convert them to pull requests (albeit with external tools). An issue is opened automatically. Commits can also be attached to an issue, making changes to eliminate the conflicts and extending the pull request. The conflict resolution process involves pulling new commits from the project's main repository, making changes to eliminate the conflicts and extending the pull request with the resulting conflict eliminating commits.
Issues and pull requests are dual on Github; for each pull request, an issue is opened automatically. Commits can also be attached to issues to convert them to pull requests (albeit with external tools). This duality enables the core team to treat pull requests as work items, which can be managed using the same facilities used for issues. Moreover, issue discussions can include links to pull requests and vice versa, while specific commit message formats can be used to automatically close issues or pull requests when commits are merged to the project's main branch.
The open nature of Github's pull requests lends itself to a variety of usage patterns. Except from basic patch submission, pull requests can be used as a requirements and design discussion tool or as a progress tracking tool towards the fulfillment of a project release. In the first case, a pull request serves as a discussion board for soliciting the opinions of other developers while a new feature is being implemented. In the second case, pull requests are associated with milestones in Github's issue tracker.
3. RESEARCH DESIGN
The main focus of this study is to understand and explain how pull requests are used by projects to enable collaboration. To answer our research questions, we use a sequential mixed-methods approach, a procedure for collecting, analyzing, and integrating both quantitative and qualitative data at some stage of the research process within a single study for the purpose of gaining a better understanding of the problem [17]. For each research question, we first explore the domain quantitatively, and then highlight interesting cases by exploring cases qualitatively. Below, we present how we approached each research question.
RQ1 To assess the popularity of the pull-based development model, we provide and analyze descriptive statistics on the use of pull requests in Github. In particular, we investigate such questions as how many projects actually make use of pull requests, how many of the projects are original repositories (versus, e.g., forks), and how pull requests relate to Github's issue tracking facilities. The outcomes are presented in Section 5.
RQ2 and RQ3 Identifying the lifecycle characteristics of pull requests and determining the factors that affect them calls for a dedicated dataset of projects that have a sufficiently long history of using pull requests. This dataset is described in Section 4.2.
Given this dataset, we answer RQ2 and RQ3 by determining a set of suitable candidate features through consultation of related work in the fields of patch submission, bug triaging, code reviewing, and distributed collaboration. Then, we clean it up through cross-correlation analysis to obtain a set of features with maximum predictive power. Using the data from the extracted features, we perform a detailed statistical analysis of pull request characteristics to answer RQ2 (Section 6).
Next, we use machine learning to retrieve the dominant features. Prior to running the classification algorithms, we automatically labeled each pull request with an outcome factor; in the case of the merge decision classification task, the label signifies whether the pull request has been merged. For the merge time task, we first filter out pull requests that have not been merged and then split the remaining data points into three classes (hour, day, more than a day) according to the time required to merge the pull request. The split points were chosen to reflect the results of RQ2, and split the available data points into roughly equally sized bins.
At a high level, the process to retrieve the dominant features for both classification tasks consists of two steps. First, we run each dataset through 6 classification algorithms, namely Random Forests (randomforest), variants of Logistic Regression (logreg) (binary for the merge decision task, multinomial for the merge time task) and Naive Bayes (naivebayes), Support Vector Machines (svm), decision trees (dtree) and AdaBoost with decision trees (adaboost). We used those algorithms as they
---
1 Github uses this internally: https://github.com/blog/1124
2 https://github.com/blog/831
Figure 2: An example Github pull request (667 from junit-team/junit — edited for space). The participants first interact in a code review, the result of which is a new commit. The second reviewer then merges the pull request.
are known to perform well in large datasets [21] and have been used in previous work involving prediction models [13]. We do not perform any additional tuning to the classification algorithms. We only report results on the first three, as those performed best. Then, we select the best classifier and apply a classifier-specific process to rank features according to their importance in the classification process.
To evaluate the classification performance, we use the Accuracy (ACC) and Area Under the receiver operating characteristic Curve (AUC) metrics. To select the appropriate classification algorithm, we run a 10-fold random selection cross-validation and aggregate the mean values for each classification metric. At each iteration, the algorithm randomly samples half of the available data points, trains a classifier with 90% percent of the input and uses it to predict the remaining 10%. The 10-fold run results also allowed us to evaluate the metric stability across runs (Section 7).
RQ4 To examine why some pull requests are not merged, we qualitatively analyze a set of randomly chosen non-merged pull requests in depth. We use open coding (a grounded theory tool) to come up with an inclusive set of reasons of why pull requests are not merged as follows: the first author read the pull request discussion on Github for randomly selected pull requests and summarized the reasons for closing them into one sentence per sample; during a second pass, the descriptions were aggregated and codes were extracted. To validate the identified codes, all three authors applied them on a different set of pull requests, compared results, identified inconsistencies and retrofitted the initial selection of codes. The final set of codes was then applied on a third sample which we used to draw results from. The sampling process is described in Section 4.3.
4. DATA
4.1 Github Data
We used Github data as provided through our GHTorrent project [16], an off-line mirror of the data offered through the Github API. The Github API data come in two forms; a streaming data flow lists events, such as forking or creating pull requests, happening on repositories in real time, while a static view contains the current state of entities. To obtain references to the roots of the static view entities, the GHTorrent project follows the event stream. From there, it applies a recursive dependency-based parsing approach to yield all data offered through the API. The data is stored in unprocessed format, in a MongoDB database, while metadata is extracted and stored in a MySQL relational database. The GHTorrent dataset covers a broad range of development activities on Github, including pull requests and issues. The project has been collecting data since February 2012. Up to August 2013, 1.9 million pull requests from more than two hundred thousand projects have been collected.
4.2 Pull Request Project Sample
Project selection. To make the analysis practical, while avoiding to examine toy projects, we use a dataset consisting of all projects for which GHTorrent recorded more than 200 pull requests in the period between February 2012 and August 2013. The initial selection resulted in 374 projects. The following criteria were then applied to exclude projects from the initial selection:
• Projects should have at least one commit coming from a pull request, to ensure that the project is open to external contributions and that pull requests are not just used by developers inside the project.
• Projects should be developing software frameworks or applications, rather than documentation or programming languages. We excluded documentation projects, because we are interested in distributed software development. We excluded programming language implementation projects because we wanted to avoid cases where the developed programming language’s core library was overshadowing the metrics of the actual implementation. This is especially true for the 5 Ruby implementations hosted on Github.
After selection, the full history (including pull requests, issues and commits) of the included projects was downloaded and features were extracted by querying the GHTorrent databases and analyzing each project’s Git repository. Furthermore, for these selected projects we collected all merges and the values for all factors that we use in our machine learning experiment, as described below.
Merge detection. To identify merged pull requests that are merged outside Github, we resorted to the following heuristics, listed here in order of application:
1. At least one of the commits associated with the pull request appears in the target project’s master branch.
2. A commit closes the pull request (using the fixes: convention advocated by Github) and that commit appears in the project’s master branch. This means that the pull request commits were squashed on one commit and this commit was merged.
3. One of the last 3 (in order of appearance) discussion comments contain a commit unique identifier, this commit appears in the project’s master branch and the corresponding comment can be matched by the following regular expression:
4. The latest comment prior to closing the pull request matches the regular expression above.
If none of the above heuristics identifies a merge, we mark the pull request as unmerged.
After creating the data files, we investigated projects where the pull request merge ratio was significantly less than the one we calculated across Github (73%), and in any case less than 40%, as this means that our heuristics are not good enough for this project. This way, we filtered out 2 projects, which we did not replace.
The final dataset consisted of 291 projects (99 Python, 91 Java, 87 Ruby, 14 Scala) and 166,884 pull requests (59,970; 55,468; 43,870 and 7.576 for Python, Ruby, Java and Scala projects respectively). Both distributions are representative of the contemporarypeularity of each respective programming language on both Github and other sites.
Feature Extraction. The feature selection was based on prior work in the areas of patch submission and acceptance [24, 4, 32, 3], code reviewing [28], bug triaging [1, 14] and also on semi-structured interviews of Github developers [9, 26, 22]. The selected features are split into three categories:
Pull request characteristics. These features attempt to quantify the impact of the pull request on the affected code base. When examining external code contributions, the size of the patch is affecting both acceptance and acceptance time [32]. There are various metrics to determine the size of a patch that have been used by researchers: code churn [24, 27], changed files [24] and number of commits [11]. In the particular case of pull requests, developers reported that the presence of tests in a pull request increases their
To investigate this, we split the churn feature into two features, namely src_churn and test_churn. The number of participants has been shown to influence the time to process of code reviewing [28]. Finally, through our own experience analyzing pull requests, we have found that in many cases conflicts are reported explicitly in pull request comments while in other cases pull requests include links to other related pull requests.
Project characteristics. These features quantify how receptive to pull requests the project is. If the project’s process is open to external contributions, then we expect to see an increased ratio of external contributors over team members. The project’s size may be a detrimental factor to the speed of processing a pull request, as its impact may be more difficult to assess. Also, incoming changes tend to cluster over time (the “yesterday’s weather” change pattern [15]), so it is natural to assume that pull requests affecting a part of the system that is under active development will be more likely to merge. Testing plays a role in speed of processing: according to [26], projects struggling with a constant flux of contributors use testing, manual or preferably automated, as a safety net to handle contributions from unknown developers.
Developer. Developer-based features quantify the influence that the person who created the pull request has on the decision to merge it and the time to process it. In particular, the developer who created the patch has been shown to influence the patch acceptance decision [19]. To abstract the results across projects with different developers, we include features that quantify the developer’s track record [9], namely the number of previous pull requests and their acceptance rate; the former has been identified as a strong indicator of pull request quality [26]. Bird et al. [5], presented evidence that social reputation has an impact on whether a patch will be merged; in our dataset, the number of followers on Github can be seen as a proxy for reputation.
All features are calculated at the time a pull request has been closed or merged, to evaluate the effect of intermediate updates to the pull request as a result of the ensuing discussion. Features that contain a temporal dimension in their calculation (e.g., team_size or commits_on_files_touched) are calculated over the three-month time period before the pull request was opened.
The initial selection contained 25 features. To check whether the selected features are sufficiently independent, we conducted a pairwise correlation analysis using the Spearman rank correlation \( \rho \) metric across all features. We set a threshold of \( \rho = \pm 0.7 \), above which we eliminated features. Using this cutoff, we removed 2 features, asserts_per_kloc and test_cases_per_kloc as they where very strongly correlated \( \rho > 0.92 \) with the included test_lines_per_kloc feature. We also removed features that could not be calculated reliably at the time a pull request was done (followers and stars). Finally, we merged similar features (i.e. doc_files and src_files were merged to files_changed).
The post processing phase left us with 15 features, which can be seen in Table 1. In general, very few features are correlated at a statistically significant level (\( \rho > 0.2 \), only two, src_churn and files_changed, are strongly correlated at \( \rho = 0.63 \)). While the correlation is strong, it is below our threshold and it is not definite; therefore we do not remove either feature from the dataset. All results are statistically significant \((n = 166, 884, p < 0.001)\).
4.3 Qualitative Data
To investigate how pull requests are used in practice and why some pull requests are not merged, we performed in-depth examination of random samples of pull requests followed by coding and thematic analysis. 100 pull requests were initially used by the first coder to identify discrete reasons for closing pull requests (bootstrapping sample), while a different set of 100 pull requests were used by all three coders to validate the identified categories (cross-validation sample). After cross validation, the two datasets were merged and a further 150 randomly selected pull requests were added to the bootstrapping sample to construct the finally analyzed dataset for a total of 350 pull requests.
5. Popularity of Pull-based Development
As of August 2013, Github reports more than 7 million repositories and 4 million users. However, not all those projects are active: in the period Feb 2012 — Aug 2013, the GHTorrent dataset captured events initiated by (approximately) 2,281,000 users affecting 4,880,000 repositories. The majority of registered repositories are forks of other repositories, special repositories hosting user web pages program configuration files and temporary repositories for evaluating Git. In the GHTorrent dataset, less than half (1,877,660 or 45%) of the active repositories are original repositories.
Pull requests are enabled by default on all repositories opened on Github; however, not all projects are using them to collaborate. In the period from February to August 2012, 315,522 original repositories received a single commit. From those, 53,866 (17%) received at least one pull request, while 54,205 (18%) used the shared repository approach, having received commits by more than one developer and no pull requests. The situation is similar during the same period in 2013: from the 1,157,625 repositories that received a single commit, 120,104 (10%) repositories received a pull request while 124,316 (11%) used the shared repository approach exclusively. In both cases, the remaining 65% and 79% are single developer projects. Across both years, 14% of the active repositories use pull requests. While pull request usage is increasing overall, partially reflecting Github’s growth, the relative number of repositories using the pull request model has decreased slightly. An almost equal number of projects use pull requests and shared repositories for distributed collaboration.
For those projects that received pull requests in 2013, the mean number of pull requests per project is relatively low at 8.1 (median: 2, percentiles: 5%: 1, 95%: 21); however, the distribution of the number of pull requests in projects is highly skewed. Projects exist, such as Ruby on Rails and the Homebrew package manager, that have more than 5,000 pull requests. From the pull requests that have been opened in 2013, 73.07% have been merged using Github facilities, thereby indicating that pull requests in principle can work as a means for obtaining external contributions. Moreover, even though one might expect that it is the well known projects that receive most pull requests, this is only moderately supported by our data: the Spearman rank correlation between the number of stars of a project and the number of pull requests it has received is \( \rho = 0.36 \) \((p < 0.001, n = 239, 131)\).
Reviews on a pull request can either target the pull as whole or the individual commits, thereby resembling a code review. On average, each pull request receives 2.89 (quantiles: 5%: 0, 95%: 11, median: 1) discussion and code review comments. Even though any Github user can participate in the review process, usually it is the project community members that do so: only 0.011% of pull request comments come from users that have not committed to the project repository. Across projects that received pull requests in 2012, 35% also received a bug report (not pull-request based) on the Github issue tracker, indicating moderate use of Github’s collaboration facilities by both the project and the project community.
An Exploratory Study of the Pull-based Software Development Model
Table 1: Selected features and descriptive statistics. Histograms are in log scale.
<table>
<thead>
<tr>
<th>Feature</th>
<th>Description</th>
<th>5 %</th>
<th>mean</th>
<th>median</th>
<th>95 %</th>
<th>Histogram</th>
</tr>
</thead>
<tbody>
<tr>
<td>num_commits</td>
<td>Number of commits in the pull request</td>
<td>1.00</td>
<td>4.47</td>
<td>1.00</td>
<td>12.00</td>
<td></td>
</tr>
<tr>
<td>src_churn</td>
<td>Number of lines changed (added + deleted) by the pull request</td>
<td>0.00</td>
<td>300.72</td>
<td>10.00</td>
<td>891.00</td>
<td></td>
</tr>
<tr>
<td>test_churn</td>
<td>Number of test lines changed in the pull request</td>
<td>0.00</td>
<td>88.88</td>
<td>0.00</td>
<td>282.00</td>
<td></td>
</tr>
<tr>
<td>files_changed</td>
<td>Number of files touched by the pull request</td>
<td>1.00</td>
<td>12.12</td>
<td>2.00</td>
<td>31.00</td>
<td></td>
</tr>
<tr>
<td>num_comments</td>
<td>Discussion and code review comments</td>
<td>0.00</td>
<td>2.77</td>
<td>1.00</td>
<td>12.00</td>
<td></td>
</tr>
<tr>
<td>num_participants</td>
<td>Number of participants in the pull request</td>
<td>0.00</td>
<td>1.33</td>
<td>1.00</td>
<td>4.00</td>
<td></td>
</tr>
<tr>
<td>conflict</td>
<td>The word conflict appears in the pull request comments.</td>
<td>—</td>
<td>—</td>
<td>—</td>
<td>—</td>
<td></td>
</tr>
<tr>
<td>forward_link</td>
<td>Pull request includes links to other pull requests</td>
<td>—</td>
<td>—</td>
<td>—</td>
<td>—</td>
<td></td>
</tr>
<tr>
<td>sloc</td>
<td>Executable lines of code at pull request creation.</td>
<td>1.39</td>
<td>6.0897</td>
<td>26.036</td>
<td>302,156</td>
<td></td>
</tr>
<tr>
<td>team_size</td>
<td>Number of active core team members during the last 3 months prior to the pull request creation.</td>
<td>1.00</td>
<td>15.37</td>
<td>7.00</td>
<td>65.00</td>
<td></td>
</tr>
<tr>
<td>perc_ext_contribs</td>
<td>The ratio of commits from external members over core team members in the last 3 months.</td>
<td>8.00</td>
<td>52.81</td>
<td>54.00</td>
<td>95.00</td>
<td></td>
</tr>
<tr>
<td>commits_files_touched</td>
<td>Number of total commits on files touched by the pull request within 3 months prior to pull request creation.</td>
<td>0.00</td>
<td>52.39</td>
<td>5.00</td>
<td>210.00</td>
<td></td>
</tr>
<tr>
<td>test_lines_per_kloc</td>
<td>A proxy for the project’s test coverage.</td>
<td>1.39</td>
<td>1,002.61</td>
<td>440.80</td>
<td>2,147.43</td>
<td></td>
</tr>
<tr>
<td>Developer</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>prev_pullreqs</td>
<td>Number of pull requests submitted by a specific developer, prior to the examined pull request.</td>
<td>0.00</td>
<td>45.11</td>
<td>14.00</td>
<td>195.00</td>
<td></td>
</tr>
<tr>
<td>requester_succ_rate</td>
<td>% of the developer’s pull requests that have been merged up to the creation of the examined pull request.</td>
<td>0.00</td>
<td>0.59</td>
<td>0.78</td>
<td>1.00</td>
<td></td>
</tr>
</tbody>
</table>
RQ1: 14% of repositories are using pull requests on Github. Pull requests and shared repositories are equally used among projects. Pull request usage is increasing in absolute numbers, even though the proportion of repositories using pull requests has decreased slightly.
6. PULL REQUEST LIFECYCLE
Lifetime of pull requests. After being submitted, pull requests can be in two states: merged or closed (and therefore not-merged). In our dataset, most pull requests (84.73%) are eventually merged. This result is higher than the overall we calculated for Github; we attribute this to the fact that the dataset generation process employs heuristics to detect merges in addition to those happening with Github facilities.
For merged pull requests, an important property is the time required to process and merge them. The time to merge distribution is highly skewed, with the great majority of merges happening very fast. Measured in days, 95% of the pull requests are merged in 26, 90% in 10 and 80% in 3.7 days. 30% of pull requests are merged in under one hour; the majority of such pull requests (60%) come from external contributors. To answer it, we performed an unpaired Mann-Whitney test among the times to merge pull requests from each group. The result is that while the two groups differ in a statistically significant manner ($n_1 = 51,829, n_2 = 89,454, p < 0.001$), the apparent difference is negligible (Cliff’s $d = -0.09$). This means that merged pull requests received no special treatment, irrespective whether they came from core team members or from the community.
On a per project basis, if we calculate the median time to merge a pull request, we see that in the vast majority of projects (97%), the median time to merge a pull request is less than 7 days. The mean time to merge is not correlated with the project’s size ($\rho = -0.05$), nor the project’s test coverage ($\rho = 0.27$). It is however, strongly correlated ($\rho = -0.69$) with the contributor’s track record: the more pull requests a developer has submitted to the same project, the lower the time to process each one of them. Moreover, projects are not getting faster at pull request processing by processing more pull requests; the correlation between the mean time to merge and the number of pull requests the project received is weak ($\rho = -0.23, n = 291, p < 0.01$).
Sizes of pull requests. A pull request bundles together a set of commits; the number of commits on a pull request is generally less than 10 (95% percentile: 12, 90% percentile: 6, 80% percentile: 3), with a median of 1. The number of files that are changed by a pull request is generally less than 20 (95% percentile: 36, 90% percentile: 17, 80% percentile: 7), with median number of 2. The number of total lines changed by pull requests is on average less than 500 (95% percentile: 1227, 90% percentile: 497, 80% percentile: 168) with a median number of 20.
Tests and pull requests. Except from the project’s source code, pull requests also modify test code. In our sample, 33% of the pull requests included modifications in test code, while 4% modified test code exclusively. Of the pull requests that included modifications to test code, 83% were merged, which is similar to the aver-
age. This seems to go against the findings by Pham et al. [26], who interviewed developers identified the presence of tests in pull requests as a major factor for their acceptance. The presence of tests in a pull request does not seem to affect the merge time either: an unpaired Mann-Whitney test shows that while there is a statistically significant difference in the means of the pull request merge time between pull requests that include tests (median: 17 hours) and those that do not (median: 5 hours) \((pr\_tests = 45, 488, pr\_no\_tests = 95, 980, p < 0.001)\), the effect size is small \((\delta = 0.18)\).
**Discussion and code review.** Once a pull request has been submitted, it is open for discussion until it is merged or closed. The discussion is usually brief: 95% of pull requests receive 12 comments or less (80% less than 4 comments). Similarly, the number of participants in the discussion is also low (95% of pull requests are discussed by less than 4 people). The number of comments in the discussion is moderately correlated with the time to merge a pull request \((\rho = 0.48, n = 141,468)\) and the time to close a non-merged pull request \((\rho = 0.37, n = 25,416)\).
Code reviews are integrated in the pull request process. While the pull request discussion can be considered an implicit form of code review, 12% of the pull requests in our sample have also been through explicit code reviewing, by having received comments on source code lines in the included commits. Code reviews do not seem to increase the probability of a pull request being merged (84% of reviewed pull requests are merged), but they do slow down the processing of a pull request: the unpaired Mann-Whitney test between the time required to merge reviewed (median: 2719 minutes) and non-reviewed (median: 295 minutes) pull requests gives a statistically significant difference with a significant effect size \((\delta = 0.41)\). Projects that employ code reviews feature larger code bases and bigger team sizes than those that do not.
Any Github user can participate in the discussion of any pull request. Usually, the discussion occurs between core team members trying to understand the changes introduced by the pull request and community members (often, the pull request creator) who explain it. In most projects, more than half of the participants are community members. This is not true however for the number of comments; in most projects the majority of the comments come from core team members. One might think that the bigger the percentage of external commenters on pull requests, the more open the project is and therefore the higher the percentage of external comments; a Spearman test indicates that it is not true \((\rho = 0.22, n = 291, p < 0.05)\).
**RQ2:** Most pull requests are less than 20 lines long and processed (merged or discarded) in less than 1 day. The discussion spans on average to 3 comments, while code reviews affect the time to merge a pull request. Inclusion of test code does not affect the time or the decision to merge a pull request. Pull requests receive no special treatment, irrespective whether they come from contributors or the core team.
### 7. MERGING AND MERGE TIME
To understand which factors affect the decision to merge and the time it takes to make this decision, we run the classification processes according to the method specified in Section 3. Each classifier attempts to predict the dependent variable (merge decision, merge time class) based on the features presented in Table 1. For the `mergetime` experiment, we excluded the `num_comments`, `num_commits` and `num_participants` features as they could not be measured at the pull request arrival time. Based on the results presented in Table 2, we selected the `randomforest` classification algorithm for both our experiments. For the `mergetime` experiment, `randomforest` achieved an AUC of 0.73, with a prior probability of 31%, 35% and 34% for each of the hour, day and more than a day classes respectively. For the `mergedecision` experiment, the prior probability for the dominant class was 84% which allowed the algorithm to achieve near perfect scores. In both cases, the stability of the AUC metric across folds was good (`mergetime`: \(sigma_{auc} = 0.019\), `mergedecision`: \(sigma_{auc} = 0.008\)).
To extract the features that are important for each classification task, we used the process suggested by Genuer et al. [12]. Specifically, we run the algorithm 50 times on a randomly selected sample of \(n = 83,442\) items, using a large number of generated trees (2000) and trying 5 random variables per split. We then used the mean across 50 runs of the Mean Decrease in Accuracy metric, as reported by the \texttt{randomForest} implementation of the random forest algorithm, to evaluate the importance of each feature. The results can be seen in Figure 3.
Finally, to validate our feature selection, we rerun the 10-fold cross-validation process with increasing number of predictor features starting from the most important one per case. In each iteration step, we add to the model the next most important feature. We stop the process when the mean AUC metric is within 2% from the value in Table 2 for each task. The selected set of features should then be enough to predict the classification outcome with reasonable accuracy, and therefore can be described as important [12]. For the `mergedecision` task, the feature importance result is dominated by the `commits_on_files_touched` feature. By re-running the cross validation process, we conclude that it suffices to use the features `commits_on_files_touched`, `sloc` and `files_changed` to predict whether a pull request will be merged (AUC: 0.94, ACC: 0.86). Therefore, we can conclude that the decision to merge a pull request is affected by whether it touches an actively developed part of the system (a variation of the “yesterday’s weather” hypothesis), how large the project’s source code base is and how many files the pull request changes.
For the `mergetime` task, there is no dominant feature; the classification model re-run revealed that at least 6 features are required to predict how fast a pull request will be merged. The classification accuracy was moderate (AUC: 0.74, ACC: 0.59), but still improved over random selection. The results provide evidence that the developer’s previous track record, the size of the project and its test coverage and the project’s openness to external contributions seem to play a significant role on how fast a pull request will be accepted.
**RQ3:** The decision to merge a pull request is mainly influenced by whether the pull request modifies recently modified code. The time to merge is influenced by the developer’s previous track record, the size of the project and its test coverage and the project’s openness to external contributions.
---
**Table 2:** Classifier performance for the merge decision and merge time classification tasks.
<table>
<thead>
<tr>
<th>classifier</th>
<th>AUC</th>
<th>ACC</th>
<th>PREC</th>
<th>REC</th>
</tr>
</thead>
<tbody>
<tr>
<td>mergedecision (n = 106,884)</td>
<td>0.73</td>
<td>0.61</td>
<td>0.95</td>
<td>0.55</td>
</tr>
<tr>
<td>binlogregr</td>
<td>0.75</td>
<td>0.61</td>
<td>0.95</td>
<td>0.55</td>
</tr>
<tr>
<td>naivebayes</td>
<td>0.71</td>
<td>0.59</td>
<td>0.94</td>
<td>0.55</td>
</tr>
<tr>
<td>randomforest</td>
<td>0.94</td>
<td>0.86</td>
<td>0.93</td>
<td>0.94</td>
</tr>
<tr>
<td>merge time (n = 141,468)</td>
<td>0.61</td>
<td>0.44</td>
<td>—</td>
<td>—</td>
</tr>
<tr>
<td>multinomregr</td>
<td>0.63</td>
<td>0.38</td>
<td>—</td>
<td>—</td>
</tr>
<tr>
<td>naivebayes</td>
<td>0.73</td>
<td>0.59</td>
<td>—</td>
<td>—</td>
</tr>
</tbody>
</table>
and is therefore submitting uninteresting changes. 10% of the contributions are rejected with reasons that have to do with project process and quality requirements (process, tests); this may be an indicator of processes not being communicated well enough or a rigorous code reviewing process. Finally, another 13% of the contributions are rejected because the code review revealed an error in the implementation.
Moreover, for 15% of the pull requests, the human examiners could not identify the cause of not merging them. This usually means that there was no discussion prior to closing the pull request or the pull request was automatically initiated and managed by external tools; incidentally, all but one project that had such pull requests in our random sample did not use Github’s issue tracking facilities. Consequently, the use of pull requests by such projects may be superficial, only complementing parts of a process managed by other tools. Finally, the human examiner could identify 19% of the pull requests as merged even though the automated heuristics could not; this means that the proportion of merged pull requests reported in this study (84%) may be slightly underrated, due to non-inclusive heuristics. By extrapolation, the total number of merged pull requests could be as high as 90%.
It is interesting to note that only 13% of the contributions are rejected due to technical issues, which is the primary reason for code reviewing, while a total 53% are rejected for reasons having to do with the distributed nature of the pull request process (concurrent modifications) or the way projects handle communication of project goals and practices. This may mean that the pull-based model (or at least the way Github implements it) may be transparent for the project’s core team [10] but not so much for potential contributors. The fact that human examiners could not understand why pull requests are rejected even after manually reviewing them supports this hypothesis further.
8. UNMERGED PULL REQUESTS
As most pull requests are indeed merged, it is interesting to explore why some pull requests are not merged. For that reason, we manually looked into 350 pull requests and classified the reasons in categories as described in Section 4.3. The cross-validation of the categories on a different set of pull requests revealed that the identified categories are enough to classify all reasons for closing a pull request, even though differences existed among the coders. The results are presented in Table 8.
The results show that there is no clearly outstanding reason for closing pull requests. However, if we group together close reasons that have a timing dimension (obsolete, conflict, superseded), we see that 27% of unmerged pull requests are closed due to concurrent modifications of the code in project branches. Another 16% (superfluous, duplicate, deferred) is closed as a result of the contributor not having identified the direction of the project correctly and is therefore submitting uninteresting changes. 10% of the contributions are rejected with reasons that have to do with project process and quality requirements (process, tests); this may be an indicator of processes not being communicated well enough or a rigorous code reviewing process. Finally, another 13% of the contributions are rejected because the code review revealed an error in the implementation.
Moreover, for 15% of the pull requests, the human examiners could not identify the cause of not merging them. This usually means that there was no discussion prior to closing the pull request or the pull request was automatically initiated and managed by external tools; incidentally, all but one project that had such pull requests in our random sample did not use Github’s issue tracking facilities. Consequently, the use of pull requests by such projects may be superficial, only complementing parts of a process managed by other tools. Finally, the human examiner could identify 19% of the pull requests as merged even though the automated heuristics could not; this means that the proportion of merged pull requests reported in this study (84%) may be slightly underrated, due to non-inclusive heuristics. By extrapolation, the total number of merged pull requests could be as high as 90%.
It is interesting to note that only 13% of the contributions are rejected due to technical issues, which is the primary reason for code reviewing, while a total 53% are rejected for reasons having to do with the distributed nature of the pull request process (concurrent modifications) or the way projects handle communication of project goals and practices. This may mean that the pull-based model (or at least the way Github implements it) may be transparent for the project’s core team [10] but not so much for potential contributors. The fact that human examiners could not understand why pull requests are rejected even after manually reviewing them supports this hypothesis further.
**Table 3: Reasons for closing pull requests without merging.**
<table>
<thead>
<tr>
<th>Reason</th>
<th>Description</th>
<th>%</th>
</tr>
</thead>
<tbody>
<tr>
<td>obsolete</td>
<td>The PR is no longer relevant, as the project has progressed.</td>
<td>4</td>
</tr>
<tr>
<td>conflict</td>
<td>There feature is currently being implemented by other PR or in another branch.</td>
<td>5</td>
</tr>
<tr>
<td>superseded</td>
<td>A new PR solves the problem better.</td>
<td>18</td>
</tr>
<tr>
<td>duplicate</td>
<td>The functionality had been in the project prior to the submission of the PR.</td>
<td>2</td>
</tr>
<tr>
<td>superfluous</td>
<td>PR doesn’t solve an existing problem or add a feature needed by the project.</td>
<td>6</td>
</tr>
<tr>
<td>deferred</td>
<td>Proposed change delayed for further investigation in the future.</td>
<td>8</td>
</tr>
<tr>
<td>process</td>
<td>The PR does not follow the correct project conventions for sending and handling pull requests.</td>
<td>9</td>
</tr>
<tr>
<td>tests</td>
<td>Tests failed to run.</td>
<td>1</td>
</tr>
<tr>
<td>incorrect implem.</td>
<td>The implementation of the feature is incorrect, missing or not following project standards.</td>
<td>13</td>
</tr>
<tr>
<td>merged</td>
<td>The PR was identified as merged by the human examiner</td>
<td>19</td>
</tr>
<tr>
<td>unknown</td>
<td>The PR could not be classified due to lacking information</td>
<td>15</td>
</tr>
</tbody>
</table>
**Figure 3: Random forest feature importance for predicting merge decision (a) and merge time (b)**
**RQ4: 53% of pull requests are rejected for reasons having to do with the distributed nature of pull based development. Only 13% of the pull requests are rejected due to technical reasons.**
9. DISCUSSION
9.1 The Pull-based Development Model
Development turnover. One of the promises of the pull request model is fast development turnover, i.e., the time between the submission of a pull request and its acceptance in the project’s main repository. In various studies of the patch submission process in projects such as Apache and Mozilla, the researchers found that the time to commit 50% of the contributions to the main project repository ranges from a few hours [30] to less than 3 days [32, 3]. Our findings show that the majority (80%) of pull requests are accepted within 4 days, 60% in less than a day, while 30% are merged within one hour (independent of project size). These numbers are indicating that pull-based development through pull requests may be more efficient than traditional email-based patches. Also, it is project-related factors that affect the turnover time, rather than characteristics of the pull request itself. This means that it is mostly up to the project to tune its processes (notably, testing coverage and process openness) for faster turnover.
Managing pull requests. The interviewees in Dabbish et al. [10] identify the management of pull requests as the most important project activity. Dabbish et al. mention that project managers “made inferences about the quality of a code contribution based on its style, efficiency, thoroughness (for example, was testing included?), and the submitter’s track record”. Some of the inspection points mentioned by project managers (testing code in pull requests, track record) are also included as features in our classification models, but they do not seem to affect the merge decision process as much. However, the developer track record is important for the speed of processing pull requests. Moreover, we found that from rejected pull requests, almost 53% are rejected due to the distributed nature of pull-based development. While the pull request process is transparent from the project manager’s side (and praised for that by Dabbish et al.’s interviewees), our findings suggest it is less so from the potential contributor’s point of view.
Attracting contributions. Pham et al. [26] mention that pull requests make casual contributions straightforward through a mechanism often referred to as “drive-by commits”. As the relative cost to fork a repository is negligible on Github (54% of the repositories are forks), it is not uncommon for developers to fork other repositories to perform casual commits. Such commits might be identified as pull requests that contain a single commit from users that are not yet part of the project’s community and comprise 7% of the total number of pull requests in 2012. Moreover, 3.5% of the forks were created for the sole purpose of creating a drive-by commit. More work needs to be done for the accurate definition and assessment of the implications of drive-by commits.
Crowd sourcing the code review. An important part of the contribution process to an open source project is the review of the provided code. Rigby and German [29], report that 80% of the core team members are also participating in the code reviews for patches, a number that is also in line with earlier findings by Mockus et al. [23]. In our dataset, we found that all core team members across all projects have participated in at least one discussion in a pull request. Moreover, we found that in all projects in our dataset, the community discussing pull requests is actually bigger than the core team members.
Democratizing development. One of the key findings of this work is that pull requests are not treated differently based on their origin: both core team members and external developers have equal chances to get their pull request accepted within the same time boundaries. Indeed, even the classification models we built assign to the corresponding feature low importance. In our opinion, this is a radical change in the way open source development is being carried out. Before pull requests, most projects employed membership promotion strategies [18] to promote interested third party developers to the core team. With pull requests, developers can contribute to any repository, without loss of authorship information. The chances that those contributions will get accepted are higher with pull requests; across Github, more than 70% of external contributions are merged (40% in other studies [29, 32]). Specialized sites such as Ohloh and CoderWall track developer activity and help developers advertise their expertise. We believe that the democratization of the development effort will lead to a substantially stronger commons ecosystem; this remains to be verified in further studies.
9.2 Implications
Contributors. Prospective project contributors want their contributions to be accepted. Our research shows that pull requests that affect parts of the project that have been changed often lately (are “hot”) are very likely to get merged. Also 80% of the merged pull requests modify three or less files and include patches less than 100 lines long. Therefore, our advice to contributors seeking to add a particular feature or fix a bug is to “keep it short”. If the contribution’s purpose is to make the contributor known to the project community, it is also beneficial to affect a project area that is “hot”.
Core team. The primary job of the core team is to evaluate a list of pull requests and decide whether to apply them or not. To make sure pull requests are processed on time, the obvious strategy is to invest in a comprehensive test suite and ensure that the project processes are sufficiently open and transparent. To avoid development concurrency related issues, core team members could ask contributors to communicate their intended changes by opening an issue that is then augmented by code and converted to a pull request. The project should include a clear articulation of what is expected from a pull request, for example tests or localized changes, on a prominent location in the project’s Github page.
A direct application of our results is the construction of tools to help the core team prioritize their work; since we can predict with very high accuracy whether a pull request will be merged or not, a potential tool might suggest which pull requests can be merged without further examination by the time they arrive. Other tools might examine the quality of the pull request at the contributor’s site, and based on the project’s profile, would provide automated suggestions for improvement (e.g., more tests, documentation).
9.3 Threats to Validity
Internal validity. Our statistical analysis uses random forests as a way to identify and rank cross-factor importance on two response variables. The classification scores in the merged/reject case are not perfect, so feature ranking may not be exactly the same given a different dataset. Further work is needed on validating the models on data from different sources (e.g., Bitbucket) or projects in different languages.
To analyze the projects, we extracted data from i) the GHTorrent relational database ii) the GHTorrent raw database iii) each project’s Git repository. Differences in the data abstraction afforded by each data source may lead to different results in the following cases: i) Number of commits in a pull request: During their lifecycle, pull requests may be updated with new commits. However, when developers use commit squashing, the number of commits is reduced to one. Therefore the number of commits metric used in our analysis is often an idealized version of the actual work that took place in the context of a pull request. ii) Number of files and commits on touched files: The commits reported in a pull request also con-
tain commits that merge branches, which the developer may have merged prior to performing his changes. These commits may contain several files not related to the pull request itself, which in turn affects our results. Therefore, we filtered out those commits, but this may not reflect the contents of certain pull requests.
**External validity.** In our study, we used merged data from several projects. The statistical analysis treated all projects as equal, even though differences do exist. For example, the larger project in our dataset, Ruby on Rails, has more than 7,000 pull requests while the smaller ones 200. While we believe that the uniform treatment of the samples led to more robust results in the classification experiment, variations in pull request handling among projects with smaller core teams may be ironed out. The fact that we performed random selection cross-validation (instead of the more common sliding window version) and obtained stable prediction results is, nevertheless, encouraging.
### 10. RELATED WORK
Arguably, the first study of *DVCS* systems as input for research was done by Bird et. al in [6]. One finding related to our work is that maintaining authorship information leads to better identification of the developer’s contributions. Bird and Zimmermann [7] investigated the use of branches in *DVCSs* (in Section 2, we refer to this *DVCS* use as “shared repository”) and found that excessive use of branching may have a measurable, but minimal, effect on the project’s time planning. On the other hand, Barr et al. [2] find that branches offer developers increased isolation, even if they are working on inter-related tasks. Finally, Shihab et al. [31] investigate the effect of branching on software quality: they find that misalignment of branching structure and organizational structure is associated with higher post-release failure rates.
This work builds upon a long line of work on patch submission and acceptance. In reference [23], Mockus et al. presented one of the first studies of how developers interact on large open source projects in terms of bug reporting. Bird et al. [4] introduced tools to detect patch submission and acceptance in open source projects. Weitgäber et al. presented an analysis of patch submission, where they find that small patches are processed faster and have higher change to be accepted into the repository. Baysal et al. [3] find that 47% of the total patches make it into the source code repository, a number much lower than our finding for pull requests (84%). Jiang et al. [20] analyzed patch submission and acceptance on the Linux kernel, which follows the pull-based development model in a more decentralized and hierarchical manner. They find that the reviewing time is becoming shorter through time while contributors can reduce it by controlling, among others, the number of affected subsystems and by being more active in their community. These findings are similar to ours, where we find that the contributor’s previous track record and number of lines in the pull request affect the time to merge it.
An inherent part of pull-based development is peer-reviewing the proposed changes. In that sense, our work complements the work by Rigby and Bird [28] and supports many of their findings. Both works find that the peer review discussion is usually short, that peer-reviewed changes are small and that reviews happen before the changes are committed and are very frequent. Rigby and Bird’s work examines industry-led projects and different code reviewing processes than ours. The fact that many aspects of the results are indeed similar leads us to hypothesize that it is the underlying process (pull-based development) that govern the reviewing process.
Recently, Github has been the target of numerous publications. Dabbish et al. [10] found that Github’s transparency helps developers manage their projects, handle dependencies more effectively, reduce communication needs, and decide what requires their attention. Peterson [25] finds that open source software (OSS) development on Github works mostly similarly to traditional OSS development, with the exception of faster turnaround times. Pham et al. [26] examined the testing practices of projects on Github and found that the lower barriers to submission hinders high-quality testing as the work load on project member increases. Finally, McDonald and Goggins [22] find that increased transparency in pull requests allows allows teams to become more democratic in their decisions.
### 11. CONCLUSION
The goal of this work is to obtain a deep understanding of the pull-based software development model, as used for many important open source projects hosted on Github. To that end, we have conducted a statistical analysis of millions of pull requests, as well of a carefully composed set of hundreds of thousands of pull requests from projects actively using the pull-based model.
Our main findings are as follows:
1. The pull-based model is not as popular as we had anticipated: Only 14% of the active projects use pull requests, but this number is equal to the number of projects using the shared repository approach (Section 5).
2. Most pull requests affect just a few dozen lines of code, and 60% are processed (merged or discarded) in less than a day. The merge decision is not affected by the presence of test code. Core members and external developers have equal chances to get their pull request accepted (Section 6).
3. The decision to merge is mainly affected by whether the pull request modifies recently modified code. The time to merge is influenced by various factors, including the developer’s track record, and the project’s test coverage.
4. 53% of non-merged pull requests are rejected for reasons related to the distributed nature of pull-based development. Only 13% of the pull requests are rejected due to technical reasons.
Our findings have the following implications:
1. The pull-based model calls for a revision of some of our current understanding of open source software development. Interesting research directions might include the formation of teams and management hierarchies, novel code reviewing practices and the motives of developers to work in a highly transparent workspace.
2. Teams seeking to attract external contributors and to speed up merging of contributions can do so not just by providing clear pull request processing guidelines, but also by incorporating a high coverage test suite.
3. Insufficient task articulation seems the most important cause for wasted (non-merged) work: Devising new ways for integrating task coordination into the pull-based model is a promising area of further research.
Last but not least, our dataset provides a rich body of information on open source software development. The dataset as well as custom-built Ruby and R analysis tools are available on the Github repository gousios/pullreqs, along with instructions on how to use them.
### 12. ACKNOWLEDGMENTS
We would like to thank the anonymous reviewers for their comments. This work is partially supported by the Marie Curie IEF 298930 — SEFUNC and the NWO 639.022.314 — TestRoots projects.
13. REFERENCES
|
{"Source-Url": "https://pure.tudelft.nl/portal/files/7416754/TUD_SERG_2014_005.pdf", "len_cl100k_base": 14285, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 45924, "total-output-tokens": 16794, "length": "2e13", "weborganizer": {"__label__adult": 0.00033855438232421875, "__label__art_design": 0.000274658203125, "__label__crime_law": 0.0002884864807128906, "__label__education_jobs": 0.0011043548583984375, "__label__entertainment": 4.00543212890625e-05, "__label__fashion_beauty": 0.00015211105346679688, "__label__finance_business": 0.0002455711364746094, "__label__food_dining": 0.0002703666687011719, "__label__games": 0.0004148483276367187, "__label__hardware": 0.00047469139099121094, "__label__health": 0.0003402233123779297, "__label__history": 0.00016891956329345703, "__label__home_hobbies": 8.440017700195312e-05, "__label__industrial": 0.00025916099548339844, "__label__literature": 0.0001804828643798828, "__label__politics": 0.00021708011627197263, "__label__religion": 0.00040268898010253906, "__label__science_tech": 0.003360748291015625, "__label__social_life": 9.554624557495116e-05, "__label__software": 0.00424957275390625, "__label__software_dev": 0.986328125, "__label__sports_fitness": 0.0002505779266357422, "__label__transportation": 0.0003619194030761719, "__label__travel": 0.0001595020294189453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71493, 0.03721]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71493, 0.06773]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71493, 0.92687]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 148, false], [148, 148, null], [148, 5009, null], [5009, 11366, null], [11366, 16412, null], [16412, 23250, null], [23250, 30952, null], [30952, 37090, null], [37090, 44664, null], [44664, 51409, null], [51409, 59161, null], [59161, 66351, null], [66351, 71493, null], [71493, 71493, null], [71493, 71493, null], [71493, 71493, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 148, true], [148, 148, null], [148, 5009, null], [5009, 11366, null], [11366, 16412, null], [16412, 23250, null], [23250, 30952, null], [30952, 37090, null], [37090, 44664, null], [44664, 51409, null], [51409, 59161, null], [59161, 66351, null], [66351, 71493, null], [71493, 71493, null], [71493, 71493, null], [71493, 71493, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71493, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71493, null]], "pdf_page_numbers": [[0, 0, 1], [0, 148, 2], [148, 148, 3], [148, 5009, 4], [5009, 11366, 5], [11366, 16412, 6], [16412, 23250, 7], [23250, 30952, 8], [30952, 37090, 9], [37090, 44664, 10], [44664, 51409, 11], [51409, 59161, 12], [59161, 66351, 13], [66351, 71493, 14], [71493, 71493, 15], [71493, 71493, 16], [71493, 71493, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71493, 0.16878]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
85b59a1927f3cbedbb5e9b45fb499994d1169083
|
4.2.2. Examples
\[ s := p[0] := n := n+1+s \]
\[ n := n+1 \]
\[ i := B/C-r-q\times s \]
\[ S[i,k+2] := 3-arc tan(s\times zeta) \]
\[ V := Q > Y \wedge Z \]
4.2.3. Semantics
Assignment statements serve for assigning the value of an expression to one or several variables or procedure identifiers. Assignment to a procedure identifier may only occur within the body of a procedure defining the value of a function designator (cf. section 5.4.4). The process will in the general case be understood to take place in three steps as follows:
4.2.3.1. Any subscript expressions occurring in the left part variables are evaluated in sequence from left to right.
4.2.3.2. The expression of the statement is evaluated.
4.2.3.3. The value of the expression is assigned to all the left part variables, with any subscript expressions having values as evaluated in step 4.2.3.1.
4.2.4. Types
The type associated with all variables and procedure identifiers of a left part list must be the same. If this type is Boolean, the expression must likewise be Boolean. If the type is real or integer, the expression must be arithmetic. If the type of the arithmetic expression differs from that associated with the variables and procedure identifiers, appropriate transfer functions are understood to be automatically invoked. For transfer from real to integer type, the transfer function is understood to yield a result equivalent to
\[ \text{entier}(E+0.5) \]
where E is the value of the expression. The type associated with a procedure identifier is given by the declarator which appears as the first symbol of the corresponding procedure declaration (cf. section 5.4.4).
4.3. Go To Statements
4.3.1. Syntax
\[(\text{go to statement}) ::= \text{go to} (\text{designational expression})\]
4.3.2. Examples
\[ \text{go to} 8 \]
\[ \text{go to} \text{exit} [n+1] \]
\[ \text{go to} \text{Town}[\text{if} y < 0 \text{ then} N \text{ else} N+1] \]
\[ \text{go to} \text{if} Ab < c \text{ then} 17 \text{ else} q[\text{if} w < 0 \text{ then} 2 \text{ else} n] \]
4.3.3. Semantics
A go to statement interrupts the normal sequence of operations, defined by the write-up of statements, by defining its successor explicitly by the value of a designational expression. Thus the next statement to be executed will be the one having this value as its label.
4.3.4. Restriction
Since labels are inherently local, no go to statement can lead from outside into a block. A go to statement may, however, lead from outside into a compound statement.
4.3.5. Go to an undefined switch designator
A go to statement is equivalent to a dummy statement if the designational expression is a switch designator whose value is undefined.
4.4. Dummy Statements
4.4.1. Syntax
\[(\text{dummy statement}) ::= \langle\text{empty}\rangle\]
4.4.2. Examples
\[ L: \]
\[ \text{begin} ... ; \text{John: end} \]
4.4.3. Semantics
A dummy statement executes no operation. It may serve to place a label.
4.5. Conditional Statements
4.5.1. Syntax
\[(\text{if clause}) ::= \text{if} (\text{Boolean expression}) \text{ then}\]
\[(\text{unconditional statement}) ::= (\text{basic statement})\]
\[(\text{compound statement})(\text{block})\]
\[(\text{if statement}) ::= (\text{if clause}) (\text{unconditional statement})\]
\[(\text{conditional statement}) ::= (\text{if statement}) (\text{else statement})(\text{if clause})(\text{for statement})\]
\[(\text{label}) :: (\text{conditional statement})\]
4.5.2. Examples
\[ \text{if } x > 0 \text{ then } n := n+1 \]
\[ \text{if } y > 0 \text{ then } y := n+m \text{ else go to } R \]
\[ \text{if } s < 0 \text{ or } P \leq Q \text{ then } AA: \text{begin} \text{ if } q < s \text{ then } a := s/q \]
\[ \text{else } y := 2 \times s \text{ end} \]
\[ \text{else if } r > s \text{ then } a := v-r \text{ else if } v < s-1 \]
\[ \text{then go to } S \]
4.5.3. Semantics
Conditional statements cause certain statements to be executed or skipped depending on the running values of specified Boolean expressions.
4.5.3.1. If statement. The unconditional statement of an if statement will be executed if the Boolean expression of the if clause is true. Otherwise it will be skipped and the operation will be continued with the next statement.
4.5.3.2. Conditional statement. According to the syntax two different forms of conditional statements are possible. These may be illustrated as follows:
\[ \text{if } B1 \text{ then } S1 \text{ else if } B2 \text{ then } S2 \text{ else } S3 \; ; \; S4 \]
and
\[ \text{if } B1 \text{ then } S1 \text{ else if } B2 \text{ then } S2 \text{ else if } B3 \text{ then } S3 \; ; \; S4 \]
Here B1 to B3 are Boolean expressions, while S1 to S3 are unconditional statements. S4 is the statement following the complete conditional statement.
The execution of a conditional statement may be described as follows: The Boolean expression of the if clauses are evaluated one after the other in sequence from left to right until one yielding the value true is found. Then the unconditional statement following this Boolean is executed. Unless this statement defines its successor explicitly the next statement to be executed will be S4, i.e. the state-
ment following the complete conditional statement. Thus the effect of the delimiter else may be described by saying that it defines the successor of the statement it follows to be the statement following the complete conditional statement.
The construction
```
else (unconditional statement)
```
is equivalent to
```
else if true then (unconditional statement)
```
If none of the Boolean expressions of the if clauses is true, the effect of the whole conditional statement will be equivalent to that of a dummy statement.
For further explanation the following picture may be useful:
```
if B1 then S1 else if B2 then S2 else S3 ; S4
```
```
B1 false B2 false
```
4.5.4. Go to into a conditional statement
The effect of a go to statement leading into a conditional statement follows directly from the above explanation of the effect of else.
4.6. For Statements
4.6.1. Syntax
```
(for list element) ::= (arithmetic expression)
(arithmetic expression) step (arithmetic expression) until (arithmetic expression) (arithmetic expression) while (Boolean expression)
```
```
(for list) ::= (for list element) (for list) , (for list element)
(for clause) ::= for (variable) := (for list) do (for statement)
(for statement) ::= (for clause) (statement)
(label) ::= (for statement)
```
4.6.2. Examples
```
for q := 1 step s until n do A[q] := B[q]
```
```
for k := 1, V1 XOR 2 while V1 < N do
for j := f+G, L, 1 step 1 until N, C+D do
A[k,j] := B[k,j]
```
4.6.3. Semantics
A for clause causes the statement S which it precedes to be repeatedly executed zero or more times. In addition it performs a sequence of assignments to its controlled variable. The process may be visualized by means of the following picture:
```
Initialize ; test ; statement S ; advance ; successor
```
```
for list exhausted
```
In this picture the word initialize means: perform the first assignment of the for clause. Advance means: perform the next assignment of the for clause. Test determines if the last assignment has been done. If so, the execution con-
tinues with the successor of the for statement. If not, the statement following the for clause is executed.
4.6.4. The for list elements
The for list gives a rule for obtaining the values which are consecutively assigned to the controlled variable. This sequence of values is obtained from the for list elements by taking these one by one in the order in which they are written. The sequence of values generated by each of the three species of for list elements and the corresponding execution of the statement S are given by the following rules:
4.6.4.1. Arithmetic expression. This element gives rise to one value, namely the value of the given arithmetic expression as calculated immediately before the corresponding execution of the statement S.
4.6.4.2. Step-until-element. An element of the form A step B until C, where A, B, and C, are arithmetic expressions, gives rise to an execution which may be described most concisely in terms of additional ALGOL statements as follows:
```
V := A ;
L1: if (V-C) MOD sign(B) > 0 then go to element exhausted;
statement S ;
V := V+B ;
go to L1 ;
```
where V is the controlled variable of the for clause and element exhausted points to the evaluation according to the next element in the for list, or if the step-until-element is the last of the list, to the next statement in the program.
4.6.4.3. While-element. The execution governed by a for list element of the form E while F, where E is an arithmetic and F a Boolean expression, is most concisely described in terms of additional ALGOL statements as follows:
```
L3: V := E ;
if -F then go to element exhausted ;
Statement S ;
go to L3 ;
```
where the notation is the same as in 4.6.4.2 above.
4.6.5. The value of the controlled variable upon exit
Upon exit out of the statement S (supposed to be compound) through a go to statement the value of the controlled variable will be the same as it was immediately preceding the execution of the go to statement.
If the exit is due to exhaustion of the for list, on the other hand, the value of the controlled variable is undefined after the exit.
4.6.6. Go to leading into a for statement
The effect of a go to statement, outside a for statement, which refers to a label within the for statement, is undefined.
4.7. Procedure Statements
4.7.1. Syntax
```
(actual parameter) ::= (string)/(expression) (/array identifier)/
_switch identifier|/procedure identifier/
(letter string) ::= (letter)/(letter string)(letter)
```
the procedure statement and the formal parameters of the procedure heading is established as follows: The actual parameter list of the procedure statement must have the same number of entries as the formal parameter list of the procedure declaration heading. The correspondence is obtained by taking the entries of these two lists in the same order.
4.7.5. Restrictions
For a procedure statement to be defined it is evidently necessary that the operations on the procedure body defined in sections 4.7.3.1 and 4.7.3.2 lead to a correct ALGOL statement.
This imposes the restriction on any procedure statement that the kind and type of each actual parameter be compatible with the kind and type of the corresponding formal parameter. Some important particular cases of this general rule are the following:
4.7.5.1. If a string is supplied as an actual parameter in a procedure statement or function designator, whose defining procedure body is an ALGOL 60 statement (as opposed to non-ALGOL code, cf. section 4.7.8), then this string can only be used within the procedure body as an actual parameter in further procedure calls. Ultimately it can only be used by a procedure body expressed in non-ALGOL code.
4.7.5.2. A formal parameter which occurs as a left part variable in an assignment statement within the procedure body and which is not called by value can only correspond to an actual parameter which is a variable (special case of expression).
4.7.5.3. A formal parameter which is used within the procedure body as an array identifier can only correspond to an actual parameter which is an array identifier of an array of the same dimensions. In addition if the formal parameter is called by value the local array created during the call will have the same subscript bounds as the actual array.
4.7.5.4. A formal parameter which is called by value cannot in general correspond to a switch identifier or a procedure identifier or a string, because these latter do not possess values (the exception is the procedure identifier of a procedure declaration which has an empty formal parameter part (cf. section 5.4.1) and which defines the value of a function designator (cf. section 5.4.4). This procedure identifier is in itself a complete expression.
4.7.5.5. Any formal parameter may have restrictions on the type of the corresponding actual parameter associated with it (these restrictions may, or may not, be given through specifications in the procedure heading). In the procedure statement such restrictions must evidently be observed.
4.7.6. Deleted.
4.7.7. Parameter delimiters
All parameter delimiters are understood to be equivalent. No correspondence between the parameter delimiters used in a procedure statement and those used in the procedure heading is expected beyond their number being the
same. Thus the information conveyed by using the elaborate ones is entirely optional.
4.7.3. Procedure body expressed in code
The restrictions imposed on a procedure statement calling a procedure having its body expressed in non-
\text{ALGOL} code evidently can only be derived from the characteristics of the code used and the intent of the user and thus fall outside the scope of the reference language.
5. Declarations
Declarations serve to define certain properties of the quantities used in the program, and to associate them with identifiers. A declaration of an identifier is valid for one block. Outside this block the particular identifier may be used for other purposes (cf. section 4.1.3).
Dynamically this implies the following: at the time of an entry into a block (through the \text{begin}, since the labels inside are local and therefore inaccessible from outside) all identifiers declared for the block assume the significance implied by the nature of the declarations given. If these identifiers had already been defined by other declarations outside they are for the time being given a new significance. Identifiers which are not declared for the block, on the other hand, retain their old meaning.
At the time of an exit from a block (through \text{end}, or by a go to statement) all identifiers which are declared for the block lose their local significance.
A declaration may be marked with the additional declarator \text{own}. This has the following effect: upon a re-entry into the block, the values of own quantities will be unchanged from their values at the last exit, while the values of declared variables which are not marked as own are undefined. Apart from labels and formal parameters of procedure declarations and with the possible exception of those for standard functions (cf. sections 3.2.4 and 3.2.5), all identifiers of a program must be declared. No identifier may be declared more than once in any one block head.
Syntax.
\[(\text{declaration}) := (\text{type declaration})|(\text{array declaration})|\]
\[(\text{switch declaration})|(\text{procedure declaration})\]
5.1. Type Declarations
5.1.1. Syntax
\[(\text{type list}) := (\text{simple variable})|\]
\[|(\text{type list})|\]
\[(\text{type}) := \text{real} | \text{integer} | \text{Boolean}\]
\[(\text{local or own type}) := (\text{type})|(\text{own type})|\]
\[(\text{type declaration}) := (\text{local or own type})(\text{type list})\]
5.1.2. Examples
\[
\text{integer } p,q,s\]
\[
\text{own Boolean } Acryl,n
\]
5.1.3. Semantics
Type declarations serve to declare certain identifiers to represent simple variables of a given type. Real declared variables may only assume positive or negative values including zero. Integer declared variables may only assume positive and negative integral values including zero. Boolean declared variables may only assume the values \text{true} and \text{false}.
In arithmetic expressions any position which can be occupied by a real declared variable may be occupied by an integer declared variable.
For the semantics of \text{own}, see the fourth paragraph of section 5 above.
5.2. Array Declarations
5.2.1. Syntax
\[(\text{lower bound}) := (\text{arithmetic expression})\]
\[(\text{upper bound}) := (\text{arithmetic expression})\]
\[(\text{bound pair}) := (\text{lower bound})|(\text{upper bound})\]
\[(\text{bound pair list}) := (\text{bound pair})|(\text{bound pair list})|\]
\[(\text{array segment}) := (\text{array identifier})|(\text{bound pair list})|\]
\[(\text{array segment}) := (\text{array identifier})|(\text{array segment})\]
\[(\text{array declaration}) := (\text{array segment})|(\text{array list})|(\text{local or own type})|(\text{array list})\]
5.2.2. Examples
\[
\text{array } a, b, c[7:n;2:m], s[1:-1:10]\]
\[
\text{own integer array } A[(\text{if } c<0 \text{ then } 2 \text{ else } 1:20)]\]
\[
\text{real array } t[1:-1:1]\]
5.2.3. Semantics
An array declaration declares one or several identifiers to represent multidimensional arrays of subscripted variables and gives the dimensions of the arrays, the bounds of the subscripts and the types of the variables.
5.2.3.1. Subscript bounds. The subscript bounds for any array are given in the first subscript bracket following the identifier of this array in the form of a bound pair list. Each item of this list gives the lower and upper bound of a subscript in the form of two arithmetic expressions separated by the delimiter \text{:}. The bound pair list gives the bounds of all subscripts taken in order from left to right.
5.2.3.2. Dimensions. The dimensions are given as the number of entries in the bound pair lists.
5.2.3.3. Types. All arrays declared in one declaration are of the same quoted type. If no type declarator is given the type \text{real} is understood.
5.2.4. Lower upper bound expressions
5.2.4.1. The expressions will be evaluated in the same way as subscript expressions (cf. section 3.1.4.2).
5.2.4.2. The expressions can only depend on variables and procedures which are nonlocal to the block for which the array declaration is valid. Consequently in the outermost block of a program only array declarations with constant bounds may be declared.
5.2.4.3. An array is defined only when the values of all upper subscript bounds are not smaller than those of the corresponding lower bounds.
5.2.4.4. The expressions will be evaluated once at each entrance into the block.
5.2.5. The identity of subscripted variables
The identity of a subscripted variable is not related to the subscript bounds given in the array declaration. How-
ever, even if an array is declared own the values of the corresponding subscripted variables will, at any time, be defined only for those of these variables which have sub-
scripts within the most recently calculated subscript bounds.
5.3. Switch Declarations
5.3.1. Syntax
(switch list) := (designational expression)
(switch list), (designational expression)
(switch declaration) := switch (switch identifier) := (switch list)
5.3.2. Examples
switch S := S1, S2, Q[m], if v > -5 then S3 else S4
switch Q := p1, w
5.3.3. Semantics
A switch declaration defines the set of values of the corresponding switch designators. These values are given
one by one as the values of the designational expressions
entered in the switch list. With each of these designational
expressions there is associated a positive integer, 1, 2, ..., obtained by counting the items in the list from left to
right. The value of the switch designator corresponding to a
given value of the subscript expression (cf. section 3.5).
Designational Expressions) is the value of the designa-
tional expression in the switch list having this given value
as its associated integer.
5.3.4. Evaluation of expressions in the switch list
An expression in the switch list will be evaluated every
time the item of the list in which the expression occurs is
referred to, using the current values of all variables
involved.
5.3.5. Influence of scopes
If a switch designator occurs outside the scope of a
quantity entering into a designational expression in the
switch list, and an evaluation of this switch designator
selects this designational expression, then the conflicts
between the identifiers for the quantities in this expre-
sion and the identifiers whose declarations are valid at
the place of the switch designator will be avoided through
suitable systematic changes of the latter identifiers.
5.4. Procedure Declarations
5.4.1. Syntax
(formal parameter) := (identifier)
(formal parameter list) := (formal parameter)
(formal parameter list), (parameter delimiter)
(formal parameter)
(formal parameter part) := (empty), (formal parameter list)
(identifier list) := (identifier), (identifier list), (identifier)
(value part) := value (identifier list)
(specifier) := string, (type), (array), (array), (array), (array), (label), (switch),
procedure (type), (procedure)
(specification part) := (empty), (specifier), (identifier list)
(procedure heading) := (procedure identifier)
(procedure body) := (statement), (code)
(procedure declaration) :=
procedure (procedure heading) (procedure body)
5.4.2. Examples (see also the examples at the end of the report)
procedure Spur(a) Order:(n) Result:(s) ; value n
array a ; integer n ; real s
begin integer k
s := 0
for k := 1 step 1 until n do s := s + a[k,k]
end
procedure Transpose(a) Order:(n) ; value n
array a ; integer n
begin real w ; integer i, k
for i := 1 step 1 until n do
for k := 1+i step 1 until n do
begin w := a[i,k]
a[i,k] := a[k,i]
a[k,i] := w
end
end Transpose
integer procedure Step (u) ; real u
Step := if 0 <= u \& u <= 1 then 1 else 0
procedure Absmax(a) size:(n,n) Result:(y) Subscripts:(i,k)
comment The absolute greatest element of the matrix a,
of size n by m is transferred to y, and the subscripts of this
element to i and k.
array a ; integer n, m, i, k ; real y
begin integer p, q
y := 0
for p := 1 step 1 until n do for q := 1 step 1 until m do
if abs(a[p,q]) > y then begin y := abs(a[p,q]) ; i := p
k := q
end end Absmax
procedure Innerproduct(a,b) Order:(k,p) Result:(y) ; value k
integer k, p ; real y, a, b
begin real s
s := 0
for p := 1 step 1 until k do s := s + a[p] * b
y := s
end Innerproduct
5.4.3. Semantics
A procedure declaration serves to define the procedure
associated with a procedure identifier. The principal con-
stituent of a procedure declaration is a statement or a
piece of code, the procedure body, which through the use
of procedure statements and/or function designators may
be activated from other parts of the block in the head of
which the procedure declaration appears. Associated
with the body is a heading, which specifies certain identifiers
occurring within the body to represent formal parameters.
Formal parameters in the procedure body will, whenever
the procedure is activated (cf. section 3.2. Function
Designators and section 4.7. Procedure Statements) be
assigned the values of or replaced by actual parameters.
Identifiers in the procedure body which are not formal
will be either local or nonlocal to the body depending on
whether they are declared within the body or not. Those
of them which are nonlocal to the body may well be local
to the block in the head of which the procedure declara-
tion appears. The procedure body always acts like a
block, whether it has the form of one or not. Consequently the scope of any label labelling a statement within the body or the body itself can never extend beyond the procedure body. In addition, if the identifier of a formal parameter is declared anew within the procedure body (including the case of its use as a label as in section 4.1.3), it is thereby given a local significance and actual parameters which correspond to it are inaccessible throughout the scope of this inner local quantity.
5.4.4. Values of function designators
For a procedure declaration to define the value of a function designator there must, within the procedure body, occur one or more explicit assignment statements with the procedure identifier in a left part; at least one of these must be executed, and the type associated with the procedure identifier must be declared through the appearance of a type declarator as the very first symbol of the procedure declaration. The last value so assigned is used to continue the evaluation of the expression in which the function designator occurs. Any occurrence of the procedure identifier within the body of the procedure other than in a left part in an assignment statement denotes activation of the procedure.
5.4.5. Code as procedure body
It is understood that the procedure body may be expressed in non-ALGOL language. Since it is intended that the use of this feature should be entirely a question of hardware representation, no further rules concerning this code language can be given within the reference language.
Examples of Procedure Declarations:
EXAMPLE 1.
procedure euler (fct, sum, eps, tim) ; value eps, tim
integer tim ; real procedure fct ; real sum, eps
comment euler computes the sum of f(i) for i from 0 up to infinity by means of a suitably refined euler transformation. The summation is stopped as soon as tim times in succession the absolute value of the terms of the transformed series are found to be less than eps. Hence, one should provide a function fct with one integer argument, an upper bound eps, and an integer tim. The output is the sum sum. euler is particularly efficient in the case of a slowly convergent or divergent alternating series
begin integer i, k, n, t ; array m[0:15] ; real mn, mp, ds ;
t := n := t := 0 ; m[0] := fct(0) ; sum := m[0]/2 ;
nextterm ; i := t := 0 ; mn := fct(i) ;
for k := 1 step 1 until n do
begin mp := (mn+mp[k])/2 ;
end euler
example 2.4
procedure RK(x,y,n,FKT,eps,eta,EX,y,E,f) ; value x,y
integer n ; Boolean f ; real x,eps,eta,EX
array y,E ; procedure FKT ;
comment: RK integrates the system y_k = f_k(x,y_1,...,y_n) (k=1,2,...,n) of differential equations with the method of Runge-Kutta with automatic search for appropriate length of integration step. Parameters are: The initial values x and y[k] for x and the unknown functions y_k(x). The order n of the system. The procedure FKT(x,y,n,z) which represents the system to be integrated, i.e. the set of functions f_k. The tolerance values eps and eta which govern the accuracy of the numerical integration. The end of the integration interval EX. The output parameter E which represents the solution at x=EX.
begin array y[1:n] ; real x,eps,eta,EX
integer n ; own real t,Hs
procedure RK1ST(x,y,etas,ys) ; real x,etas
comment: RK1ST integrates one single RUNGE-KUTTA with initial values y[k] which yields the output parameters x=EX and y[k], the latter being the solution at x. Important: the parameters n, FKT, x enter RK1ST as nonlocal entities
begin array w[1:n] ; a[1:5] ; integer k,j
x := x := x
for k := 1 step 1 until n do y[k] := w[k] := y[k] := y[k]
for j := 1 step 1 until 4 do begin
FKT(etas,ys,x)
x := x+a[j]
end for k := 1 step 1 until n do
begin w[k] := y[k]+a[j]*x[k] ; y[k] := y[k] + a[j]/4*X/1.3/3
end
1 This RK-program contains some new ideas which are related to ideas of S. Gill, A process for the step-by-step integration of differential equations in an automatic computing machine, [Proc. Comb. Phil. Soc. 47 (1961), 96]; and E. Fröberg, On the solution of ordinary differential equations with digital computing machines, [Fysiotog. Sällsk. Lund, Förh. 20, 11 (1950), 139-152]. It must be clear, however, that with respect to computing time and round-off errors it may not be optimal, nor has it actually been tested on a computer.
end k
end ;
end RKIST ;
Begin of program:
if \(k\) then begin \(H := xE - z\); \(s := 0\) end else \(H := Hs\); \(s := s + 1\); go to \(DD\);
end if ;
AA: if \((z + 2.01 \times H - zE > 0)\) then
begin \(Hs := H\); \(s := s - 1\) ; \(H := (xE - z)/2\)
end ;
RKIST \((x,y,2H,2z,2y)\); BB: RKIST \((x,2y,2H,x3,y3)\);
for \(k := 1\) step 1 until \(n\) do
if \(\text{comp}(y1[k],y3[k],x1)a > \epsilon\) then go to \(CC\);
The ALGOL Family
(factor), def 3.3.1
false, synt 2.2.2
for, synt 2.3, 4.6.1
(for clause), def 4.6.1 text 4.6.3
(for list), def 4.6.1 text 4.6.4
(for list element), def 4.6.1 text 4.6.4.1, 4.6.4.2, 4.6.4.3
(formal parameter), def 5.4.1 text 5.4.3
(formal parameter list), def 5.4.1
(formal parameter part), def 5.4.1
(for statement), def 4.5.1 synt 4.1.1, 4.5.1 text 4.0 (complete section)
(function designator), def 3.2.1 synt 3.3.1, 3.4.1 text 3.2.3, 5.4.4
go to, synt 2.3, 4.3.1
(goto statement), def 4.3.1 synt 4.1.1 text 4.3.3
(identification), def 2.4.1 synt 3.1.1, 3.2.1, 3.5.1, 5.4.1 text 2.4.3
(identification list), def 5.4.1
if, synt 2.3, 3.3.1, 4.5.1
(if clause), def 3.3.1, 4.5.1 synt 3.4.1, 3.5.1 text 3.3.3, 4.5.3.2
(if statement), def 4.5.1 text 4.5.3.1
(implication), def 3.4.1
integer, synt 2.3, 5.1.1 text 5.1.3
(integer), def 2.5.1 text 2.5.4
label, synt 2.3, 5.4.1
(label), def 3.5.1 synt 4.1.1, 4.5.1, 4.6.1 text 1, 4.1.3
(left part), def 4.2.1
(left part list), def 4.2.1
(let), def 2.1 synt 2, 2.4.1, 3.2.1, 4.7.1
(let string), def 3.2.1, 4.7.1
local, text 4.1.3
(local or own type), def 5.1.1 synt 5.2.1
(logical operator), def 2.3 synt 3.4.1 text 3.4.5
(logical value), def 2.2.2 synt 2, 3.4.1
(lower bound), def 5.2.1 text 5.2.4
minus −, synt 2.3, 2.5.1, 3.3.1 text 3.2.3.1
multiply ×, synt 2.3, 3.3.1 text 3.3.4.1
(multiplying operator), def 3.3.1
nonlocal, text 4.1.3
(number), def 2.5.1 text 2.5.3, 2.5.4
(open string), def 2.6.1
(operator), def 2.3
own, synt 2.3, 5.1.1 text 5, 5.2.5
(parameter delimiter), def 3.2.1, 4.7.1 synt 5.4.1 text 4.7.7
(parentheses ( ), synt 2.3, 3.2.1, 3.3.1, 3.4.1, 3.5.1, 4.7.1, 5.4.1 text 3.3.5.2
plus +, synt 2.3, 2.5.1, 3.3.1 text 3.3.4.1
(primary), def 3.3.1
procedure, synt 2.3, 5.4.1
(procedure body), def 5.4.1
(procedure declaration), def 5.4.1 synt 5 text 5.4.3
(procedure heading), def 5.4.1 text 5.4.3
(procedure identifier), def 3.2.1 synt 3.2.1, 4.7.1, 5.4.1 text 4.7.5.4
(procedure statement), def 4.7.1 synt 4.1.1 text 4.7.3
(program), def 4.1.1 text 1
(proper string), def 2.6.1
quantity, text 2.7
real, synt 2.3, 5.1.1 text 5.1.3
(relation), def 3.4.1 text 3.4.5
(relational operator), def 2.3, 3.4.1
scope, text 2.7
semicolon ;, synt 2.3, 4.1.1, 5.4.1
(separator), def 2.3
(sequential operator), def 2.3
(simple arithmetic expression), def 3.3.1 text 3.3.3
(simple Boolean), def 3.4.1
(simple designational expression), def 3.5.1
(simple variable), def 3.1.1 synt 5.1.1 text 2.4.3
space u, synt 2.3 text 2.3, 2.3.3
(specification part), def 5.4.1 text 5.4.5
(specifier), def 2.3
(specifier), def 5.4.1
standard function, text 3.2.4, 3.2.5
(statement), def 4.1.1, synt 4.5.1, 4.6.1, 5.4.1 text 4 (complete section)
statement bracket, see: begin end
step, synt 2.3, 4.6.1 text 4.6.4.2
string, synt 2.3, 5.4.1
(string), def 2.6.1 synt 3.2.1, 4.7.1 text 2.6.3
string quotes ' ', synt 2.3, 2.6.1, text 2.6.3
(subscript, text 3.1.4.1
(subscript bound, text 5.2.3.1
(subscript brackets [ ], synt 2.3, 3.1.1, 3.5.1, 5.2.1
(subscripted variable), def 3.1.1 text 3.1.4.1
(subscript expression), def 3.1.1 synt 3.5.1
(subscript list), def 3.1.1
(sucessor, text 4
switch, synt 2.3, 5.3.1, 5.4.1
(switch declaration), def 5.3.1 synt 5 text 5.3.3
(switch designator), def 3.5.1 text 3.5.3
(switch identifier), def 3.5.1 synt 3.2.1, 4.7.1, 5.3.1
(switch list), def 5.3.1
term, def 3.3.1
ten w, synt 2.3, 2.5.1
then, synt 2.3, 3.3.1, 4.5.1
transfer function, text 3.2.5
true, synt 2.2.2
(type), def 5.1.1 synt 5.4.1 text 2.6
(type declaration), def 5.1.1 synt 5 text 5.1.3
(type list), def 5.1.1
(unconditional statement), def 4.1.1, 4.5.1
(unlabelled basic statement), def 4.1.1
(unlabelled block), def 4.1.1
(unlabelled compound), def 4.1.1
(unsigned integer), def 2.5.1, 3.5.1
(unsigned number), def 2.5.1 synt 3.3.1
until, synt 2.3, 4.6.1 text 4.6.4.2
(upper bound), def 5.2.1 text 5.2.4
value, synt 2.3, 5.4.1
value, text 2.6, 3.3.3
(value part), def 5.4.1 text 4.7.3.1
(variable), def 3.1.1 synt 3.3.1, 3.4.1, 4.2.1, 4.6.1 text 3.1.3
(variable identifier), def 3.1.1
while, synt 2.3, 4.6.1 text 4.6.4.3
END OF THE REPORT
|
{"Source-Url": "http://www.cs.virginia.edu/%7Easb/teaching/cs415-fall05/docs/algol-2.pdf", "len_cl100k_base": 9277, "olmocr-version": "0.1.50", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 9144, "total-output-tokens": 10199, "length": "2e13", "weborganizer": {"__label__adult": 0.00026798248291015625, "__label__art_design": 0.000423431396484375, "__label__crime_law": 0.00024366378784179688, "__label__education_jobs": 0.0010814666748046875, "__label__entertainment": 0.0001074075698852539, "__label__fashion_beauty": 0.00011271238327026369, "__label__finance_business": 0.0002161264419555664, "__label__food_dining": 0.0002865791320800781, "__label__games": 0.0010957717895507812, "__label__hardware": 0.0010786056518554688, "__label__health": 0.0002579689025878906, "__label__history": 0.00023508071899414065, "__label__home_hobbies": 0.00012022256851196288, "__label__industrial": 0.0004780292510986328, "__label__literature": 0.0003857612609863281, "__label__politics": 0.00020313262939453125, "__label__religion": 0.000423431396484375, "__label__science_tech": 0.042083740234375, "__label__social_life": 7.778406143188477e-05, "__label__software": 0.01432037353515625, "__label__software_dev": 0.935546875, "__label__sports_fitness": 0.00020313262939453125, "__label__transportation": 0.0003592967987060547, "__label__travel": 0.00014495849609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32062, 0.06526]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32062, 0.42571]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32062, 0.75807]], "google_gemma-3-12b-it_contains_pii": [[0, 5194, false], [5194, 9752, null], [9752, 12574, null], [12574, 18172, null], [18172, 22963, null], [22963, 27320, null], [27320, 27741, null], [27741, 32062, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5194, true], [5194, 9752, null], [9752, 12574, null], [12574, 18172, null], [18172, 22963, null], [22963, 27320, null], [27320, 27741, null], [27741, 32062, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32062, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 32062, null]], "pdf_page_numbers": [[0, 5194, 1], [5194, 9752, 2], [9752, 12574, 3], [12574, 18172, 4], [18172, 22963, 5], [22963, 27320, 6], [27320, 27741, 7], [27741, 32062, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32062, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
a373696010f7aaa4d3e7c222b093a65b4ef6cf06
|
Optimistic Shared Memory Dependence Tracing
Yanyan Jiang*, Du Li†, Chang Xu*‡, Xiaoxing Ma*‡, Jian Lu*
*State Key Laboratory for Novel Software Technology, Nanjing University
Department of Computer Science and Technology, Nanjing University
†School of Computer Science, Carnegie Mellon University
jiangyy@outlook.com, duli@cs.cmu.edu, {changxu,xxm,lj}@nju.edu.cn
Abstract—Inter-thread shared memory dependences are crucial to understanding the behavior of concurrent systems, as such dependences are the cornerstone of time-travel debugging and further predictive trace analyses. To enable effective and efficient shared memory dependence tracing, we present an optimistic scheme addressing the challenge of capturing exact dependences between unsynchronized events to reduce the probe effect of program instrumentation. Specifically, our approach achieved a wait-free fast path for thread-local reads on x86-TSO relaxed memory systems, and simultaneously achieved precise tracing of exact read-after-write, write-after-write and write-after-read dependences on the fly. We implemented an open-source RWTrace tool, and evaluation results show that our approach not only achieves efficient shared memory dependence tracing, but also scales well on a multi-core computer system.
Keywords—concurrency; shared memory dependence; dynamic analysis
I. INTRODUCTION
Shared memory and locks, though being widely adopted in the ever-increasing concurrent programming paradigm, are notoriously difficult to reason. To understand the behavior of such systems, a key challenge is how to efficiently keep track of shared memory dependences in a concurrent program’s execution. Tracing shared memory dependences enables record and replay of a previous, oftentimes erroneous, execution [1], [2], [3], as well as facilitates trace analyses for data races [4], [5] and atomicity violations [6], [7].
To trace the precise order of shared memory accesses, a straightforward way is to guard every shared memory access with a lock [2], [8]. These lock-based techniques, however, may drastically slow down programs. To make shared memory dependence tracing more efficient, recent research work found that thread-local accesses are predominant for real-world programs, and optimistic approaches are therefore proposed to reduce the overall probe effect [9], [10], [11]. For example, Octet [9] made thread-local memory accesses extremely efficient, at the cost of expensive roundtrip coordination for inter-thread dependences. Stride [10] ingeniously eliminated all read-time synchronization, but requires a post-execution inference whose soundness may suffer from hash collisions. CARE [11] logs even less shared memory dependences, but only provides value-deterministic replay guarantee. Overall, existing approaches attempted to strike a tradeoff between performance and determinism, but they also came with limitations, either requiring offline interference or introducing expensive synchronization operations on certain occasions.
We in this paper present a novel optimistic shared memory dependence tracing technique to overcome the aforementioned challenges in order to make it more practical. We are able to efficiently and precisely trace all three kinds of inter-thread shared memory dependences on the fly: read-after-write, write-after-write and write-after-read dependences.
Aligning with previous work, we propose an optimistic design such that thread-local reads are wait-free [12]. Our approach complements Octet [9] when inter-thread shared memory communications are frequent, as our slow path is a lock-protected critical section and heavy round-trip coordination required by Octet is avoided. To achieve a wait-free fast path, we trace read-after-write dependences by combining insights of wait-free notification in Stride [10] and speculation-retry design in our previous work CARE [11]. We also address the even more challenging task of online tracing exact write-after-thread-local-read dependences by using a carefully designed hash table of which fast-path lookups are wait-free. These algorithms are briefly introduced in Section II, and we expand the comprehensive discussion in Section III.
Our second contribution is extending our technique to systems of relaxed memory model. As mentioned earlier, our thread-local read fast path is wait-free. We further prove that, for the most widely spread commodity x86 multiprocessor systems [13], we achieved precise read-after-write dependence tracing without any memory fence instruction or atomic operation. The proof also draws a positive conclusion to the applicability of previous deterministic record and replay work [10], [11], as their correctness on x86-TSO can be proved by exactly the same technique. Memory fences are carried out to retain fast path wait-freeness in the case that write-after-read dependences are traced, or when the memory model is weaker than total store order. We discuss such relaxed memory model related issues in Section III-E.
Our final contribution is open-source implementation of the shared memory dependence tracing tool RWTrace. We evaluated RWTrace with a series of concurrent benchmarks including desktop, scientific and server programs on a multi-core machine. Evaluation results show that RWTrace outperforms any lock-based approaches, and is tens of times faster for several memory-intensive benchmarks. Evaluation results also show that our RWTrace tool scales well even if the non-uniform memory access multiprocessor architecture is present. The RWTrace implementation is presented in Section IV followed by evaluations on a set of real-world benchmarks in Section V.
Finally, we present qualitative discussion of related work and conclude our paper in Section VI and VII, respectively.
‡ Corresponding authors.
II. OVERVIEW
A. Background
Behavior of concurrent systems consisting of threads and shared memory is difficult to reason, because the shared memory access order largely affects the program outcome. If two shared memory accesses are performed on the same address by two different threads and at least one of them is a write, we say that these two accesses are conflicting. Knowing the exact order of conflicting accesses is crucial to understand the system’s behavior. With such ordering information, one can deterministically replay a problematic execution [1], [2], [3], or conduct further testing and analysis in search of faults and defects [4], [5], [6], [7].
B. Optimistically Tracing Shared Memory Dependences
To efficiently capture inter-thread shared memory dependences, recent research exploits the access pattern of concurrent programs, in which shared memory reads predominate writes [10], and a vast majority of accesses are not involved in an inter-thread dependence [9]. These insights facilitate shared memory dependence tracing approaches that behave differently among shared memory accesses, either in a frequent fast path or in a rare slow path. For example, Stride [10] does not synchronize for read events at all, but requires an offline inference procedure to restore shared memory dependences. Octet [9] achieved extremely efficient fast path for thread-exclusive and read-shared memory accesses, but an inter-thread dependence requires a much more costly roundtrip coordination.
We propose a novel shared memory dependence tracing recipe following an optimistic design that favors thread-local reads\(^1\). To achieve efficient dependence tracing, the major challenge is how to make the thread-local read fast path wait-free [12]. According to the types of two incorporated events, a shared memory dependence can be categorized as a read-after-write, write-after-write or write-after-read dependence. For each category, we highlight its challenge and our solution as follows. Detailed discussions are expanded in Section III.
Write-after-write dependences. We adopt the standard approach of serializing all write events to the same shared address [2], [9], [10], [11]. By maintaining the latest writer thread’s identifier for each shared address, such dependences can be faithfully captured.
Read-after-write dependences. Since the thread-local reads are predominant, the major challenge is how to design an efficient fast path for them. Like [11], we speculatively assume that a read is thread-local and perform the read instantly followed by a posterior test of thread-locality, achieving a fast path when the test is passed. On the other hand, when the thread-locality test fails, we remedy the effect by a slow path, which performs the read again with lock.
However, the thread-locality test in [11] is too optimistic that may miss real dependences. We therefore adopt the memory ordering technique proposed in [10] to design a sound thread-locality test that always fails for non-thread-local reads. Figure 1 demonstrates the discovery of a read-after-write dependence between two threads accessing \(x\) (a solid line denotes a shared memory dependence, while a dashed line indicates a transitively deduced dependence). In short, we associate each address \(x\) with a version identifier \(V(x)\), and perform the update of \(V(x)\) before the write to \(x\) while queries \(V(x)\) after performing the read from \(x\). The designated event ordering guarantees that whenever a read event is reading an inter-thread value, the corresponding update of \(V(x)\) is detected to trigger a thread-locality test failure, and hence an inter-thread dependence is captured.
Write-after-read dependences. Efficiently tracing write-after-read dependences is even more challenging because there is no synchronization between a thread-local read and a write in which a dependence is incorporated (i.e., a write-after-thread-local-read dependence). To the best of our knowledge, none of existing optimistic dependence tracing scheme can obtain the exact read events for a write-after-read dependence without a second inference pass\(^2\).
To trace write-after-read dependences, we also enforce update is performed before read and query is performed after write, as shown in Figure 2. For each shared address, we maintain a hashed mapping to keep track of each thread’s latest read event to the address. By a careful design, we make sure that any structural modification to the hash table will only happen in the slow path, and hash table update can always succeed for thread-local reads, achieving a wait-free fast path that only contains an \(O(1)\) hash table lookup and a shared memory write.
Finally, we offer users two alternatives in different application scenarios for practical concerns. If one collects shared
\(^1\)A read is thread-local if the thread had accessed the same address before, and there is no other thread writing to it in between.
\(^2\)Octet [9], for example, enforces a RdSh \(\rightarrow\) WrEx ordering by a global roundtrip coordination, but the dependence’s precise reader events are lost.
memory dependences for a time-travel debugging or an off-line trace analysis [2], [7], [14], read-after-write and write-after-write dependences are sufficient for restoring all write-after-read dependences by the deterministic replay algorithm described in [11]. Further analysis in Section III-E shows that in this case our read fast path is correct under the x86-TSO memory model (neither memory fence instruction nor atomic operation is needed). On the other hand, we can also trace every shared memory dependence on the fly at the cost of a few additional operations and a memory fence at each shared memory access. Such full set of dependences can be directly used to perform trace analyses [5], [15].
III. TRACING SHARED MEMORY DEPENDENCES
We take a top-down approach in describing our shared memory dependence tracing scheme. After the notations and definitions listed in Section III-A followed by the formalized algorithm in Section III-B, we first expand the discussion on how read-after-write and write-after-write dependences are traced in Section III-C. Then, we present two approaches to tracing write-after-read dependences in Section III-D. Finally, we conduct the justification of extending our scheme to systems of relaxed memory model in Section III-E.
A. Preliminaries
1) Thread and event: We assume that a concurrent system consists of threads accessing a shared memory. Each thread $t$ executes a single in-program-order stream of events
$$E_t = \{e_1, e_2, \ldots, e_n\},$$
as defined in x86-TSO [13]. We use the unique identifier $\langle t: e_i \rangle$ to refer to event $e_i$ performed by $t$. Each event $e_i$ is of one of the following types:
1) $W_t[x] = v$, for a write of value $v$ to address $x$ by thread $t$.
2) $R_t[x] = v$, for a read of value $v$ from address $x$ by thread $t$.
3) $Acq_t[x]$, for an acquisition of lock at address $x$ by thread $t$. $t$ is blocked until the lock is successfully acquired.
4) $Rel_t[x]$, for a release of lock at address $x$ by thread $t$.
These four types of events are sufficient for defining a sequentially consistent execution model. We exclude other synchronization events (e.g., thread fork/join and monitor events) for brevity since they can be easily constructed by proper $Acq$ and $Rel$ events. The x86-TSO memory model also defines other memory-model specific events like memory fence $F_t$, in-processor lock $L_t/U_t$ and store buffer flush $\tau_p$. These notations do not pose any difficulty in understanding our algorithm in a sequentially consistent memory model setting, and hence we omit them for brevity. Precise semantics of these events can be found in [13].
2) Shared memory dependence: Let us first assume that our target system has a sequentially consistent memory model (i.e., shared memory accesses are not reordered and appear to be atomic). We will extend our discussions to relaxed memory model in Section III-E.
Let $E = \bigcup_i E_i$ be the set of all events. For a sequentially consistent system, there exists a total order $\preceq \subseteq E \times E$ such that every read event in $E$ returns the most recent written value in $\preceq$ [16]. To capture the behavior of a concurrent system, one can naively obtain $\preceq$ by serializing all shared memory accesses, precluding any possibility of parallelism. To best recover parallelism, we can also decompose the task of tracing $\preceq$ into detecting inter-thread shared memory dependences, and recover $\preceq$ later by a linear extension [8].
Specifically, to faithfully capture the behavior of a concurrent system, both program order dependences and inter-thread shared memory dependences are required. The program order dependence $\preceq_r \subseteq E \times E$ encodes the happens-before order between events in the same thread, i.e., $\langle t: e_i \rangle \preceq_r \langle t: e_{i+1} \rangle$. On the other hand, an inter-thread shared memory dependence indicates that a thread is reading or writing a value that is previously accessed by another thread. Specifically, for two shared memory access events $\langle t: e_i \rangle$ and $\langle t': e_j \rangle$ performed on the same address, if either $e_i$ or $e_j$ is a write, the relative order $\langle t: e_i \rangle \rightarrow \langle t': e_j \rangle$ is critical for understanding the program’s behavior [9]. According to the type of $e_i$ and $e_j$, such dependences can be categorized into three kinds: read-after-write (RAW), write-after-read (WAR) and write-after-write (WAW), which are represented by $r \xrightarrow{raw} w, w \xrightarrow{war} r$ and $w \xrightarrow{waw} w'$, respectively.
Let $\rightarrow_{hb}$ be the transitive closure of all the aforementioned dependences, i.e.,
$$\rightarrow_{hb} = tr\left( \rightarrow_{po} \cup \rightarrow_{raw} \cup \rightarrow_{war} \cup \rightarrow_{waw} \right).$$
A classical result is that any linear extension of $\rightarrow_{hb}$ is a sequentially consistent total order (i.e., a valid $\preceq$) [8], and hence $\rightarrow_{hb}$ is sufficient for deterministic replay. Since program order is trivially preserved by program execution, we are most interested in the inter-thread shared memory dependences which cannot be transitively deduced by program order in $\rightarrow_{hb}$, $\rightarrow_{po}$ and $\rightarrow_{hb}$, which are sufficient for reproducing and understanding a shared memory system’s concurrent execution.
3) Thread Locality: If thread $t$’s shared memory accesses $\langle t: e_{i_1} \rangle \rightarrow_{hb} \langle t: e_{i_2} \rangle \rightarrow_{hb} \ldots \rightarrow_{hb} \langle t: e_{i_k} \rangle$ are performed on the same address $a$, and there is no other thread writing $a$ in between, we consider all these events thread-local excluding the first event. Formally, events $\langle t: e_{i_1} \rangle, \langle t: e_{i_2} \rangle, \ldots, \langle t: e_{i_k} \rangle$ are thread-local if there is no write event $\langle t': e_j \rangle$ such that $t \neq t'$ and $\langle t: e_{i_1} \rangle \rightarrow_{hb} \langle t': e_j \rangle \rightarrow_{hb} \langle t: e_{i_k} \rangle$. The first event $\langle t: e_{i_1} \rangle$ is excluded because it may be incorporated in an inter-thread dependence. Thread-local events can be combined as a single event in understanding the behavior of a concurrent system, and are thus not have to be logged. We keep this insight in mind in designing our optimistic approach to shared memory dependence tracing.
B. Program Instrumentation
To achieve efficient shared memory dependence tracing, we associate each shared address $a$ with a lock $L(a)$. Different
shared memory addresses are allowed to share a lock. For each lock $L(a)$, we also maintain its version $V(a)$ which denotes the identifier of the latest write event performed when $L(a)$ is acquired. $V(a)$ is in form of $(t : e_i)$ indicating that the most recent writer to $a$ is the $i$-th event $W_t[a] = v$ performed by thread $t$.
In case that WAR dependences are traced, we further associate each shared address $a$ with a key-value pair data structure $M_a$. We use $M_a$ to keep each thread $t$’s latest event reading address $a$, and therefore we require $M_a$ to support the following two operations:
1) update($M_a$, $(t : e_i)$), for updating the latest read event of thread $t$ to be $e_i$. In other words, update sets the key $t$’s corresponding value to $e_i$.
2) query($M_a$), for returning all $(t : e_i)$ pairs, and remove all such pairs in $M_a$.
In Section III-D we show that $M_a$ can be efficiently implemented, preserving wait-freeness for our read fast path.
As briefly discussed in Section II, the key insight of capturing a shared memory dependence between $(t : e_i)$ and $(t' : e_j)$ (either a RAW or WAR dependence) is to instrument the program creating the event ordering of $A^{p_1} \rightarrow (t : e_i) \rightarrow h_b^{p_2} \rightarrow (t' : e_j)$, where $A$ updates a shared state indicating the existence of $(t : e_i)$ and this state change is visible at $B$ such that we can detect a dependence. This insight is realized as our shared memory dependence tracing algorithms. For a read event $R_t[a] = v$ with identifier $(t : e_i)$, our instrumentation is illustrated in Algorithm 1. Similarly, write event $W_t[a] = v$ with identifier $(t : e_i)$’s instrumentation is shown in Algorithm 2. For visual conventions, a box indicates that its contained event is the one being instrumented, and underlined code snippets are only used for tracing WAR dependences. All non-boxed shared memory access events ($R_t$ and $W_t$) are performed by our instrumentation. When we are discussing the rationale of tracing RAW and WAW dependences in Section III-C, these underlined codes can be omitted.
C. Tracing RAW and WAW Dependences
1) Tracing RAW Dependences: Instrumentation for a read event (Algorithm 1) consists of two phases. We design the first phase to be a wait-free speculative read and a thread-locality test. It performs the read event $R_t[a] = v$ as usual (Line 2), followed by a read of $a$’s latest write event identifier $R_t[V(a)]$ (Line 3) and finally a thread-locality test (Line 4).
We expand our discussion of thread-locality test and its correctness in Section III-C3. We design the test to exhibit only single-sided error. In other words, the thread-locality test is guaranteed to fail for any inter-thread read event, assuring that all inter-thread RAW dependences are captured.
Only when the thread locality test cannot confirm a thread-local read, a second phase is carried out to capture the exact inter-thread RAW dependence (Lines 5–13). By acquiring $a$’s corresponding lock $L(a)$, we serialize the read event with any write event to $a$ because all writes to $a$ are also protected by $L(a)$ in Algorithm 2. In this lock-protected region, we once again perform the read event $R_t[a]$ obtaining $v'$ (Line 7) whose writer event’s identifier is $(t'' : e_j)$ (Line 8). We override the read value $v$ in $R_t[a] = v$ by $v'$, essentially “replacing” the read in Line 2 by the one in Line 7, obtaining the exact RAW dependence $(t'' : e_j) \rightarrow (t : e_i)$.
Our two-phase read instrumentation design gains from the fact that thread-local reads are far more frequent than the others in real-world programs [9], [11], [10]. The thread-locality test consists of only thread-local operations, and therefore our read fast path (i.e., passing thread-locality test in the first phase) is wait-free and consumes only a few machine instructions.
2) Tracing WAW Dependences: The write instrumentation (Algorithm 2) protects every write event to address $a$ with lock $L(a)$, to ensure that all writes to the same address are serialized. We also update $V(a)$ in the same lock-protected region to establish atomic update of both the value and its version. By studying the value stored in $V(a)$, Lines 8–9 filters out thread-local writes which can be inferred by the program order and only inter-thread WAW dependences are logged.
3) Detecting Thread Locality: The challenge of effectively and efficiently tracing RAW dependences is the design of a sound and fast thread locality test (Line 4 in Algorithm 1).
The test must be sound so that no real dependence is missed, and should be extremely efficient because it is called very frequently.
To implement such test, we associate each thread $t$ with $V_t(a)$, a thread-local shadow copy of $V(a)$. $V_t(a)$ stores $t$’s knowledge about which write event is the latest one performed on $a$. We allow the thread-locality test to produce false negatives (failing the test for an actually thread-local read). Thus we allow $V_t(a)$ to hold inconsistent (i.e., outdated) writer information. $V_t(a)$ is updated only when an inter-thread RAW dependence is detected through thread locality update (Line 13 in Algorithm 1) or thread itself is performing a write (Line 10 in Algorithm 2). The thread-locality test passes only if the actual writer event’s identifier $\langle a, t', e_j \rangle$ (fetched by Line 3 in Algorithm 1) matches the one stored in the shadow copy, i.e., $V_t(a) = \langle a, t', e_j \rangle$. Note that it is neither practical nor necessary to maintain $V_t(a)$ for every $a$. Memory access locality indicates that the shadow mapping can be efficiently implemented by a cache-like structure of fixed size and any feasible cache replacement strategy [11].
We now explain why this thread-locality test can guarantee to recognize any inter-thread RAW dependence. Note that our write instrumentation (Algorithm 2) updates $V(a)$ before the actual write $\langle a, v \rangle$ is performed (Lines 3–4). Once $V(a)$ is updated, any other thread’s shadow copy $V_t(a)$ (if exists) is immediately outdated, as if we had performed a global invalidate operation before $v$ was written to the shared memory. Combined with our read instrumentation (Algorithm 1) that reads $V(a)$ after the actual read $\langle a, v \rangle$ is performed (Lines 2–3), we ensure that, if $R_t[a]$ is reading a value written by another thread, $V_t(a)$ must be invalidated before $R_t[V(a)]$ is performed, triggering a thread-locality test failure. Specifically, our instrumentation ensures that $R_t[a] \not\rightarrow a \rightarrow V_t(a)$ and $V_t[a] \not\rightarrow a \rightarrow V_t[a]$ if $V_t[a] \not\rightarrow a \rightarrow V_t[a]$ is an inter-thread RAW dependence, the transitive law implies that $V_t[a] \not\rightarrow a \rightarrow V_t[a]$, triggering a thread-locality test failure.
We remind our readers that this argument works only for a sequentially consistent memory model. This careful memory ordering design, however, may suffer from reordering issues in systems of relaxed memory model. We will return to this subject in Section III-E.
From another perspective, the thread-locality test can also be interpreted as a lightweight imprecise instance of the transitive reduction [19] technique for compacting the shared memory dependence log. Transitive reduction states that, for any partial order, say $\rightarrow$, we can safely remove a dependence $a \rightarrow b$ if there is some $t$ such that $a \rightarrow t \land t \rightarrow b$. Repetitively removing redundant dependences yields a unique minimum representation of the partially ordered set. However, state-of-the-art transitive reduction is often performed offline [15]. Exact on-the-fly transitive reduction requires either heavy instrumentation [20], [19] or customized hardware [21]. Thread-locality test, on the other hand, only removes dependences for $a \rightarrow b$ if there is $\rightarrow t \land t \rightarrow b$ or $\rightarrow t \land t \rightarrow b$, achieving a balance of cost and effectiveness.
\begin{algorithm}
\caption{Algorithms for update and query}
\begin{algorithmic}[1]
\Function{update}{$M_a$, \text{t : } e_i}$
\If{$L(a)$ is held then}
\EndIf
\If{We are at Line 9 in Algorithm 1}
\EndIf
\State $\langle a, v \rangle$ = new\()
\State $W_t[addr] = e_i$
\State hash\_insert$(M_a, \langle a, t, addr \rangle)$
\Else
\If{lookup failed}
\EndIf
\If{We are at Line 2 in Algorithm 1}
\EndIf
\State $addr$ = hash\_lookup$(M_a, t)$
\EndIf
\EndIf
\EndIf
\EndIf
\State $W_t[addr] = e_i$
\State \text{MFENCE}
\EndFunction
\Function{query}{$M_a$
\Comment{We are at Line 5 in Algorithm 2}
\State \text{MFENCE}
\ForAll{$\langle t, addr \rangle \in M_a$}
\State \text{R}_t[addr] = e_i$
\State ret $\leftarrow$ ret $\cup$ \langle t : e_i \rangle$
\EndFor
\State hash\_reclaim$(M_a)$; // remove all contents in $M_a$
\State hash\_insert$(M_a, \langle t, new() \rangle)$
\State return ret
\EndFunction
\end{algorithmic}
\end{algorithm}
D. Tracing WAR Dependencies
We provide two independent approaches to tracing WAR dependences. The online tracing algorithm captures WAR dependences on the fly, at the cost of incurring a little more runtime overhead (retaining the wait-freeness for the thread-local read fast path). On the other hand, the offline algorithm uses only RAW and WAW dependences to infer WAR dependences by an extra replay pass.
1) Online Tracing WAR Dependences: The underlined code in Algorithm 1 and Algorithm 2 are used for tracing WAR dependences. Recall that in Section III-B, we use $M_a$ to keep each thread’s latest read event from address $a$. Let us first assume the atomicity of update and query. We update $M_a$ before the read is performed, and query $M_a$ after the write is done. Using the similar argument presented in Section III-C3, we enforce update $(M_a, \langle t : e_i \rangle)$ \text{post} $R_t[a]$ for a read event (Lines 1–2 in Algorithm 1) and $W_t[a] \not\rightarrow$ query$(M_a)$ for a write event (Lines 4–6 in Algorithm 2). Therefore, for any $r = R_t[a]$ happening before $w = W_t[a]$ indicating a WAR dependence, the transitive rule implies that $r$’s update must happen before $w$’s query, establishing the fact that no WAR dependence is missed.
There exists a subtle case when racing read and write events are present. Consider that a WAR dependence $r \rightarrow w$ is detected before $r$ executes Line 2 of Algorithm 1. Later, $r$’s thread-locality test may fail, yielding a logged RAW dependence $w' \rightarrow r$ (w’ is not necessarily equal to $w$).
The cycle formed by \( r \xrightarrow{\text{raw}} w \xrightarrow{hb} w \xrightarrow{\text{raw}} r \) clearly violates our presumption of partial order. Fortunately, this is the only case of generating a false dependence\(^4\) that a cycle is formed. Removal of the false WAR dependence (restoring previously known WAR dependence \( r' \xrightarrow{\text{raw}} w \) where \( r' \xrightarrow{po} r \) if exists) essentially restores the correct dependence.
The next challenge is how to efficiently implement \( M_a \) and its two operations, as a practical wait-free concurrent hash table implementation is not yet available\(^{22}\). To keep the fast path wait-free, we exploit the observation that thread \( t \) only claims itself reading a shared address. In other words, any update of \( M_a \) performed by thread \( t \) operates on key \( t \). Accordingly, we implement \( M_a \) as an ordinary hash table, and design our algorithm to obey the invariant that key \( t \) must exist in \( M_a \) whenever thread \( t \) executes update(\( M_a, \langle t, e_i \rangle \)) at a thread-local read event. This invariant implies that no structural modification is ever needed for a thread-local read, as illustrated in Algorithm 3.
We enforce this invariant by a slight modification to our slow path instrumentation. For any read event \( r \) in thread \( t \) to be thread-local, there must be some event \( u \xrightarrow{po} r \) executing thread locality update in Algorithm 1 or Algorithm 2, and \( u \) itself is either a write event or a non-thread-local read event capturing a RAW dependence \( w \xrightarrow{\text{raw}} u \). In both cases, \( u \) accesses \( a \) and is protected by \( L(a) \). Therefore, at this time, we insert the key \( t \) into \( M_a \) to ensure successful lookups for subsequent thread-local reads (Line 9 in Algorithm 1 and Lines 4–8, 26 in Algorithm 3).
Such modification only changes the internal implementation of \( M_a \), and therefore our previous correctness arguments still hold. Nevertheless, several interesting cases arise. The first case is that update may fail to find the key \( t \) in the hash table (Lines 12–13 in Algorithm 3). Since hash table is only cleared at query in our write-time instrumentation, there must be another thread executed writing a value. In this situation, we have \( W_t[a] \xrightarrow{\text{update}} \text{query}(\langle k, v \rangle) \xrightarrow{\text{update}} [R_t[a]] \) and the read must not pass the thread-locality test. In other words, a hash table lookup failure always indicates that the subsequent thread-locality test will fail. For a similar reason, if query(\( M_a \)) and update(\( M_a, \langle t, e_i \rangle \)) happened in parallel, the read must also not be thread-local. Therefore a RAW dependence is logged, and any incorrect WAR dependence will be discarded.
We demonstrate a possible hash table implementation in Algorithm 4. Since conflicting hash _insert and hash _reclaim are protected by the same lock (Lines 8, 25–26 in Algorithm 3), we thus only need to consider the correctness of racing reads in hash _lookup. Since thread \( t \) only operates on key \( t \), there will be no racing accesses to the same key. Moreover, as long as key \( t \) is in the hash table, lookup will always succeed no matter the old or the resized new hash table is fetched (Lines 22 in Algorithm 4). These justifications are sufficient for ensuring a wait-free fast path.
The final issue of tracing WAR dependences is memory ordering. In a concurrent system of relaxed memory model,
\(^4\) A WAR dependence between a write and a thread-local read is always a true dependence because a thread-local read always happens-before any writer afterwards.
\begin{algorithm}
\caption{An example hash table implementation}
\begin{algorithmic}
\Function{hash _lookup}{\( H, k \)}
\State \( R_t[H] = h \);
\State \( i \leftarrow \text{hash}_\text{probe}(h, k) \);
\If {key not found}
\State \Return{FAIL} ;
\EndIf
\State \( R_t[h(i).value] = v \);
\State \Return{v} ; // read only
\EndFunction
\Function{hash _reclaim}{\( H \)}
\State \( W_t[H] = \text{new}() \);
\EndFunction
\Function{hash _insert}{\( H, \langle k, v \rangle \)}
\State \( R_t[H] = h ; \)
\State \( i \leftarrow \text{hash}_\text{probe}(h, k) ; \) // read only
\State \( W_t[h(i).key] = k ; \)
\State \( W_t[h(i).value] = v ; \)
\If {hash table resize needed}
\State \( h' \leftarrow \text{new}() ; \)
\State \Copy {elements in h to h'} ;
\State \( W_t[H] = h' \);
\EndIf
\EndFunction
\end{algorithmic}
\end{algorithm}
In both cases, no write event \( w' \) can exist such that \( w \xrightarrow{hb} w' \xrightarrow{hb} r \) because all writes are serialized in our instrumentation. Therefore, for any \( w_{\text{pred}} \xrightarrow{raw} w \xrightarrow{raw} w_{\text{succ}} \), we know that \( w_{\text{pred}} \xrightarrow{hb} w \xrightarrow{hb} r \xrightarrow{hb} w_{\text{succ}} \). Therefore, we derive that all writes happening after \( w \) must also happen before \( r \), and all writes happening after \( w \) must also happen after \( r \); we essentially have restored WAR dependences for \( r \). Based on this idea, we can adopt the replay algorithm described in [11] to replay the program execution with only \( raw \) and \( w_{raw} \), and restore any \( w_{\text{sb}} \) if necessary.
E. Dealing with Relaxed Memory Model
1) Tracing WAW Dependences: Obviously, our algorithm can correctly trace WAW dependences because all writes to \( a \) are serialized by \( L(a) \), and correct memory ordering is assured by lock semantics which is independent of memory model.
2) Tracing RAW Dependences: Let us focus on tracing RAW dependences, assuming that the underlined code used for tracing WAR dependences in Algorithm 1 and Algorithm 2 is removed. As discussed in Section III-C3, we carefully design the memory ordering to be \( W_t[V(a)] \xrightarrow{po} W_t[a] \) for a write and \( R_t[a] \xrightarrow{po} R_t[V(a)] \) for a read. Therefore, for any real WAR dependence \( W_t[a] \xrightarrow{hb} R_t[V(a)] \), the transitivity rule implies that \( W_t[V(a)] \xrightarrow{hb} R_t[V(a)] \) and the thread-locality test must fail.
However, in a system of relaxed memory model, the program order is no longer satisfied as memory accesses can be reordered by the underlying hardware. To cope with such non-sequential behaviors, memory access order can be ensured by inserting memory barriers after Line 2 of Algorithm 1 and after Line 3 of Algorithm 2.
One interesting result is that our unmodified RAW dependence tracing algorithm is correct for the most widely spread x86 multiprocessor systems. To derive the correctness, we first show that our instrumentation can capture all RAW dependences for x86-TSO memory model [13] by the following theorem.
**Theorem 1.** In x86-TSO, if \( R_t[a] \) (Line 2 in Algorithm 1) is reading a value that is written by another thread, the thread-locality test at Line 4 must fail.
**Proof:** (sketch) First, a read event \( R_t[a] \) reading value from the store buffer is not the case because such read is considered thread-local and we allow it to pass the test. Therefore, \( R_t[a] = v \) must be reading a value previously written by a write event \( W_v[a] = v \) happened in \( t' \neq t \). According to our instrumentation (Lines 3–4 of Algorithm 2), we know that \( V(a) \) is updated before the actual write is performed, i.e., \( W_{t'}[V(a)] \xrightarrow{po} W_{t'}[a] \), because each thread executes events in respect to the program order in x86-TSO, and both of the writes are inserted into the FIFO store buffer. Moreover, \( R_t[a] \) reading this value from shared memory indicates that \( W_{t'}[a] \) had been dequeued from the store buffer. The FIFO nature of the store buffer ensures that \( W_{t'}[V(a)] \xrightarrow{po} W_{t'}[a] \) must also be dequeued, triggering a failure of our thread-locality test.
Note that this argument is correct even if we use a highly optimized spin-lock implementation that does not flush the store buffer at lock releases (e.g., the implementation described in [13], which is deployed in the pthread library and Linux Kernel). However, in this case, the entire system’s behavior may not be sequentially consistent (SB example in [13] is a possible case). According to our previous work CARE [11], we can always reproduce each thread’s local behavior with our traced RAW and WAW dependences by keeping a per-thread shadow memory at replay, and fetch values from the shadow memory instead of the shared memory for thread-local reads.
This replay scheme works even if non-sequentially-consistent behavior exists because any RAW dependence is captured and a thread-local read’s value is always determined by the shadow memory\(^5\). This is an interesting discovery that with the full set of shared memory dependences, we are able to reproduce non-sequentially-consistent behavior of a concurrent system.
To enforce a sequentially consistent memory model by instrumentation, we further require a store buffer flush each time at write-time lock release (Line 7 of Algorithm 2). With such treatment, the store buffer is always empty when read events at Lines 2–3 of Algorithm 1 are executed, and the values are read from the shared memory. Since all reads from the shared memory appear to be atomic in x86-TSO, a sequentially consistent memory model is guaranteed. This justification not only extends our CARE approach, but also applies for Stride [10] because it also serializes all shared memory writes, and hence a sequentially consistent memory model is enforced.
3) Tracing WAR Dependences: To trace WAR dependences, let us consider underlined code in Algorithm 1 and Algorithm 2. We use the similar memory ordering technique in tracing RAW dependences that places update \( \xrightarrow{po} R_t[a] \) and \( W_{t'}[a] \xrightarrow{po} \) query, to make sure that data in update reaches shared memory before query when a read happened before a write.
This case, however, is more complicated than that in tracing RAW dependences. When RAW and WAW dependences are traced, read instrumentation only contains reads and write instrumentation only contains writes. Since x86-TSO reorders neither a load with other loads nor a store with other stores, no memory barrier is ever needed. On the other hand, when we are tracing WAR dependence, update contains shared memory writes which may be reordered with the actual read \( R_t[a] \), causing a dependence to be missed. This is exactly why we insert MFENCE at Lines 17 and 21 of Algorithm 3.
4) Beyond Total Store Order: As described in Section III-B, the key insight of our dependence tracing scheme is the memory ordering of \( A \xrightarrow{po} \langle t, e_i \rangle \xrightarrow{hb} \langle t', e_j \rangle \xrightarrow{po} B \), and use \( A \xrightarrow{hb} B \) as indicator for an inter-thread dependence. Therefore, we must make sure that the \( \xrightarrow{po} \) is not violated if we extend our algorithms to an even more relaxed memory model, and such memory ordering can be easily achieved by properly inserting memory fence instructions, while the wait-freeness is still retained.
\(^5\)In the SB example, both two shared memory reads are thread-local, and read values are identical to the ones in their shadow memory.
IV. IMPLEMENTATION
We implemented our shared memory dependence tracing tool RWTrace for C/C++ programs compiled by LLVM [23]. Source code of RWTrace is publicly available at http://github.com/jiangyy/rwtrace. The RWTrace tool is implemented as an LLVM optimization pass. The optimization pass is capable of inserting arbitrary instruction sequence before and after any LLVM IR instruction, therefore our RWTrace tool is not limited to shared memory dependence tracing. We expect more dynamic analysis tools to be implemented on the RWTrace framework.
To trace shared memory dependences, we instrument load and store instructions according to the description of Algorithm 1–4. The implementation of required data structures are described as follows.
1) Every shared memory address is mapped to a lock \( L(a) \). We statically allocate a total amount of \( 2^{20} \) lock objects, and map address \( a \) to the lock numbered \((a >> 6) \& 0xffff\). In other words, we divide the memory into 64-byte chunks, and let the address in the same chunk to share one same lock. We expect such address grouping strategy does not significantly impact the performance because this size is equal to the size of L1 cache line in commodity x86 systems, and false sharing of a cache line is expected to be rare.
2) The latest writer’s event identifier \( V(a) \) is stored within \( L(a) \)’s lock object because modifications to \( V(a) \) are always protected by \( L(a) \).
3) \( V(a) \)’s thread-local shadow copy \( V_t(a) \) is kept in thread \( t \)’s local storage, and is implemented by a direct mapping cache containing roughly 10K elements.
4) The latest read event mapping \( M_a(t) \) is designed to support concurrent lookup and update. We implement it by a closed-address hash table and chaining to resolve conflict. As the linked list for each hash table bucket is monotonically increasing, we guarantee the lookups for thread-local reads are always successful. This design enabled us to use ring buffer for memory management, keeping the amortized cost of memory allocation and release to be \( O(1) \) if the buffer is sufficiently large.
Other implementation details can be found in our open source project.
V. EVALUATION
A. Methodology
We demonstrate that our RWTrace tool can efficiently trace shared memory dependences by evaluating RWTrace’s performance on real-world benchmarks. We chose a set of subject programs that are extensively studied by the previous work (a superset of those studied in [3]). Specifically, we selected desktop applications, scientific benchmarks from PARSEC [24] and SPLASH-2 [25] as well as two HTTP Web server programs. Detailed description of these subject programs and their evaluation settings are listed in Table I. For benchmarking the server programs, HTTP requests are generated by the apache’s standard benchmark tool ab [26].
We instrumented all shared memory accesses to the statically allocated data and heap in evaluation, capturing the full set of shared memory dependences (assuming that stack objects are not shared and library code is excluded). We evaluated the running time of our subject programs, as well as the amount of shared memory dependences being captured. All evaluation data were collected via averaging over 10 subject program runs.
We also implemented two lock-based shared memory dependence tracing techniques using the same infrastructure and options. The MutexLock is a C++ implementation of LEAP [2] which protects all shared memory accesses with pthread library’s built-in mutex lock, and traces the dependences between lock acquisitions and releases. The second technique CREWLock enables multiple readers to execute in parallel by protecting shared memory accesses with read/write lock [27]. In this setting, only RAW and WAW dependences can be captured. It is difficult to implement Octet [9] because it requires coordination protocols to be conducted at program safe points, posing non-trivial challenge for an unmanaged runtime. Therefore, we measured Octet protocol’s state transition statistics for a qualitative analysis based on our lock-based implementation.
The evaluation was conducted on a server with four 6-core Intel Xeon X7460 processors (24 cores in total) and 64GB RAM which has an NUMA architecture [28].
B. Evaluation Results
Table II shows our performance evaluation results. We collect the profiling information of the percentage of thread-local reads among all shared memory reads and all shared memory accesses, which are shown in Columns 2 and 3, respectively. Each unmodified subject program’s running time is shown in Column 4 (running time is measured in seconds). Columns 5–6 show the running time and dependences captured by RWTrace that only traces RAW and WAW dependences (described in Sections III-C and III-D2), while Columns 7–8 show the data when WAR dependences are also traced (described in Section III-D). Evaluation results for MutexLock and CREWLock are shown in Columns 9–10 and Columns 11–12, respectively. Columns 13–15 exhibit proportions of state transitions in lock-based Octet simulation: allocation or same state (A/S), upgrading or fence (U/F) and conflicting (Conf.).
1) Study of Efficiency: The evaluation results show that RWTrace has the best running time if only RAW and WAW dependences are traced, which is sufficient for an offline replay. In this setting, RWTrace’s slow path efficiency is comparable to the lightweight lock approach, and hence outperformed CREWLock which captures exactly the same set of dependences. Compared with data reported in Chimera [3], the runtime overhead of RWTrace is smaller than that for scientific benchmarks evaluated in [3] (our average runtime overhead is 44.6% while the reported is 85.8%).
If WAR dependences are also traced, an additional slowdown of 0.3%–142% (median 39%) is paid. In this setting, RWTrace outperformed or has comparable performance with both MutexLock and CREWLock for 11 out of 12 subjects. The only exception is qsort due to large amount of shared memory writes, and our slow path is slightly less efficient than
Table I: List of benchmarks and evaluation settings
<table>
<thead>
<tr>
<th>Subject</th>
<th>Description</th>
<th>LOC</th>
<th>Evaluation Setting</th>
</tr>
</thead>
<tbody>
<tr>
<td>desktop</td>
<td>aget</td>
<td>2.5K</td>
<td>16 threads, 64MB file</td>
</tr>
<tr>
<td></td>
<td>pfscan</td>
<td>1.1K</td>
<td>16 threads, 640MB file</td>
</tr>
<tr>
<td></td>
<td>pbzip2</td>
<td>1.9K</td>
<td>16 threads, 64MB file</td>
</tr>
<tr>
<td>scientific</td>
<td>ocean</td>
<td>4.1K</td>
<td>16 threads, 1024 x 1024 grid</td>
</tr>
<tr>
<td></td>
<td>water</td>
<td>1.8K</td>
<td>16 threads, 1,000 molecules, 10 steps</td>
</tr>
<tr>
<td></td>
<td>ft</td>
<td>2.4K</td>
<td>16 threads, 2** data points</td>
</tr>
<tr>
<td></td>
<td>radix</td>
<td>1.9K</td>
<td>16 threads, 2** elements</td>
</tr>
<tr>
<td></td>
<td>fluid</td>
<td>1.2K</td>
<td>16 threads, 10 frames, 1MB data input</td>
</tr>
<tr>
<td></td>
<td>qsort</td>
<td>0.9K</td>
<td>16 threads, 2** elements</td>
</tr>
<tr>
<td></td>
<td>x264</td>
<td>37K</td>
<td>16 threads, 128 frames, 640 x 360 resolution</td>
</tr>
</tbody>
</table>
| server | knot | 1.2K | 16 threads, 2** requests |
| | apache | 395K | 16 threads, 2** requests |
Table II: Evaluation results
<table>
<thead>
<tr>
<th>Subject</th>
<th>TL/RD</th>
<th>TL/ALL</th>
<th>Time</th>
<th>RWTrace (1)</th>
<th>RWTrace (2)</th>
<th>MutexLock</th>
<th>CREWLock</th>
<th>Octet</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Time</td>
<td>#Dep.</td>
<td>Time</td>
<td>#Dep.</td>
<td>Time</td>
<td>#Dep.</td>
<td>#Dep.</td>
<td>%AS</td>
</tr>
<tr>
<td>aget</td>
<td>53.06%</td>
<td>27.39%</td>
<td>4.53</td>
<td>4.39</td>
<td>4.12K</td>
<td>4.60</td>
<td>4.19K</td>
<td>4.39</td>
</tr>
<tr>
<td>pfscan</td>
<td>99.99%</td>
<td>>99.99%</td>
<td>0.99</td>
<td>7.46</td>
<td>0.15K</td>
<td>18.45</td>
<td>0.21K</td>
<td>30.51</td>
</tr>
<tr>
<td>pbzip2</td>
<td>86.86%</td>
<td>71.55%</td>
<td>1.99</td>
<td>2.01</td>
<td>0.66K</td>
<td>2.34</td>
<td>1.03K</td>
<td>2.07</td>
</tr>
<tr>
<td>ocean</td>
<td>99.99%</td>
<td>99.99%</td>
<td>1.61</td>
<td>1.87</td>
<td>24.7K</td>
<td>2.80</td>
<td>45.7K</td>
<td>34.58</td>
</tr>
<tr>
<td>water</td>
<td>99.89%</td>
<td>95.67%</td>
<td>0.80</td>
<td>1.10</td>
<td>622K</td>
<td>2.67</td>
<td>1.09M</td>
<td>21.86</td>
</tr>
<tr>
<td>fft</td>
<td>>99.99%</td>
<td>99.95%</td>
<td>3.16</td>
<td>4.28</td>
<td>2.34K</td>
<td>5.19</td>
<td>2.56K</td>
<td>5.52</td>
</tr>
<tr>
<td>radix</td>
<td>99.96%</td>
<td>63.62%</td>
<td>0.79</td>
<td>0.91</td>
<td>2.34K</td>
<td>1.17</td>
<td>2.35K</td>
<td>8.46</td>
</tr>
<tr>
<td>fluid</td>
<td>>99.99%</td>
<td>99.97%</td>
<td>0.53</td>
<td>1.46</td>
<td>115K</td>
<td>2.39</td>
<td>20.2K</td>
<td>111.11</td>
</tr>
<tr>
<td>qsort</td>
<td>99.35%</td>
<td>61.49%</td>
<td>1.34</td>
<td>3.30</td>
<td>616K</td>
<td>5.36</td>
<td>1.56M</td>
<td>3.54</td>
</tr>
<tr>
<td>x264</td>
<td>99.98%</td>
<td>99.98%</td>
<td>3.52</td>
<td>29.44</td>
<td>755M</td>
<td>58.29</td>
<td>3.17M</td>
<td>69.25</td>
</tr>
<tr>
<td>knot</td>
<td>83.68%</td>
<td>47.09%</td>
<td>1.80</td>
<td>1.81</td>
<td>38.2K</td>
<td>1.83</td>
<td>79.6K</td>
<td>1.83</td>
</tr>
<tr>
<td>apache</td>
<td>99.93%</td>
<td>67.52%</td>
<td>3.29</td>
<td>3.28</td>
<td>3.50K</td>
<td>3.29</td>
<td>3.61K</td>
<td>3.28</td>
</tr>
</tbody>
</table>
(a) Unmodified (b) RWTrace (without WAR) (c) RWTrace (with WAR)
Figure 3: Evaluation of scalability
a lightweight lock. MutexLock exhibits 30–200× of slowdown for ocean, water and fluid because it prohibits concurrent shared memory reads, and our RWTrace does not suffer from such issue.
For a qualitative comparison with Octet, we refer to [29] which points out that Octet incurs large overhead for memory-intensive programs with even moderate communication (0.1–1% Cord., e.g., water and qsort). Note that this ratio is even higher for aget, pbzip2 and knot, however, these applications are I/O-bound and therefore suffer less from performance penalty of round-trip coordination. Since RWTrace is less optimistic than Octet, it would be less efficient for benchmarks that have numerous non-conflicting writes (e.g., fluid and x264). However, this feature exactly complements Octet’s heavy slow path. As suggested in [29], a hybrid implementation combining Octet and RWTrace is expected to be even more efficient as RWTrace is more efficient than locks.
2) Study of Logged Dependences: CREWLock is only capable of tracing RAW and WAW dependences, and the reported amounts of dependences are consistent with RWTrace (1) (Columns 6 and 12 in Table II). To trace WAR dependences, 0.4–108% (median 39%) more dependences are logged (Column 8). These dependences are sufficient for sound predictive trace analysis (e.g., happens-before race detector). Note that MutexLock does not use shadow memory to hold last writer’s information, and hence redundant read-after-read dependences are also captured, leading to much more dependences being logged for ocean, water, fluid and x264. Also note that RWTrace captures slightly less dependences compared with CREWLock. This is because RWTrace has less probe effect, and less conflicting accesses are interleaved.
3) Study of Scalability: We also evaluated scalability of the scientific subject programs as they extensively use the shared memory. The evaluation results are shown in Figure ??.
expected, all subjects scaled well because our instrumentation does not pose any scalability bottleneck, and has a wait-free fast path to better recover parallelism. A closer inspection shows a counterintuitive observation that instrumented programs scaled slightly better than the unmodified ones. Further profiling information suggests that this is because RWTrace instrumentation does slowdown the program, but inserted code snippets are mostly scalable thread-local workloads (e.g., cache lookup), and their costs are amortized across parallel threads as processor cores increased. On the contrary, unmodified code hits the scalability bottleneck faster due to extensive shared memory accesses and NUMA architecture of the hardware.
VI. RELATED WORK
Shared memory dependence is useful in various ways. First, it serves a basis of deterministically recording and replaying concurrent program’s execution [8]. The logged dependences, after a trace simplification procedure [15], are extremely useful for programmers to debug faulty concurrent programs. Furthermore, these dependences can also be fed to predictive analysis tools for finding potential access anomalies (e.g., by causal race detection [5], [30] or random testing [14]). We are also working on such analysis tools upon the RWTrace framework.
Restoring shared memory dependences from each thread’s local information is computational intractable [31], therefore such solutions are either best-effort [32] or have an exponential worst case [33]. The more straightforward approach tracing shared memory dependence is protecting each shared memory accesses with locks. Obtaining dependences is much easier in this setting as all conflicting accesses are serialized by lock. The lock can be implemented either by JVM’s built-in synchronize primitives [2], hand-tuned spin lock [34], or hardware page protection [1].
Lock implementation can be optimistic towards successive acquisitions in the same thread [35]. Following an optimistic design, Octet [9] made the thread-local fast path extremely efficient, but pays heavy roundtrip coordination cost at slow paths. On the other hand, Chimera [3] uses hybrid program analysis to enforce race-freedom by optimistically grouping fine-grained locks to larger granularity ones.
Recent research work also realized that it is sometimes unnecessary to synchronize a shared memory access even if it is incorporated in an inter-thread shared memory dependence. The seminal work Stride [10] achieved eliminating all read-time synchronizations, and exact dependences can be restored by an offline replay pass. Our previous work CARE [11] is also an optimistic approach to tracing a subset of shared memory dependences for deterministic replay.
The algorithm of RWTrace combines both ideas from Stride and CARE, and extended them with several new designs such that precise dependences are traced on the fly. Compared with traditional lock-based approaches, we achieved a wait-free fast path and does not sacrifice slow path efficiency, thus the dependence tracing procedure is more efficient. Compared with Octet, our slow path (lock protected critical section) is much more efficient than its roundtrip coordination protocol. We also capture more precise write-after-read dependences than Octet because its RdSh → WrEx state transition is handled by a global roundtrip coordination, which enforces happens-before ordering but the exact reader information is lost. Compared with Stride and CARE which deduce shared memory dependences by a replay pass, we capture them in an online fashion. When a faithful replay is infeasible (e.g., missed dependences in the library code or huge amount of I/O operations which cannot be efficiently logged), we are still able to obtain shared memory dependences for further analysis.
Finally, our discussions on relaxed memory model extends the correctness of Stride and CARE to x86-64, as they only considered sequentially consistent memory model.
VII. CONCLUSION
In this paper, we present an optimistic shared memory dependence tracing scheme to effectively and efficiently tracing inter-thread shared memory dependences on the fly. Specifically, we addressed the challenge of capturing the precise write-after-read dependence between a pair of unsynchronized operations, achieving a wait-free fast path for thread-local reads. We implemented our algorithms as RWTrace tool and made it open source to enable more useful analysis tools on this platform.
ACKNOWLEDGMENT
This work was supported in part by National Basic Research 973 Program (Grant No. 2015CB352202), and National Natural Science Foundation (Grant Nos. 61472174, 91318301, 61321491) of China.
REFERENCES
|
{"Source-Url": "https://cs.nju.edu.cn/changxu/1_publications/ASE15.pdf", "len_cl100k_base": 13464, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 46720, "total-output-tokens": 14955, "length": "2e13", "weborganizer": {"__label__adult": 0.00035262107849121094, "__label__art_design": 0.00033020973205566406, "__label__crime_law": 0.00039124488830566406, "__label__education_jobs": 0.0006437301635742188, "__label__entertainment": 7.224082946777344e-05, "__label__fashion_beauty": 0.00015735626220703125, "__label__finance_business": 0.0002071857452392578, "__label__food_dining": 0.000301361083984375, "__label__games": 0.0010166168212890625, "__label__hardware": 0.0020847320556640625, "__label__health": 0.0004253387451171875, "__label__history": 0.00035309791564941406, "__label__home_hobbies": 0.00010889768600463869, "__label__industrial": 0.0004835128784179687, "__label__literature": 0.00024116039276123047, "__label__politics": 0.0003037452697753906, "__label__religion": 0.0004570484161376953, "__label__science_tech": 0.0574951171875, "__label__social_life": 7.903575897216797e-05, "__label__software": 0.008697509765625, "__label__software_dev": 0.92431640625, "__label__sports_fitness": 0.00034880638122558594, "__label__transportation": 0.0006952285766601562, "__label__travel": 0.0002264976501464844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57002, 0.03344]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57002, 0.20543]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57002, 0.8839]], "google_gemma-3-12b-it_contains_pii": [[0, 5819, false], [5819, 10966, null], [10966, 17597, null], [17597, 22171, null], [22171, 28206, null], [28206, 32785, null], [32785, 39568, null], [39568, 45689, null], [45689, 50399, null], [50399, 57002, null], [57002, 57002, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5819, true], [5819, 10966, null], [10966, 17597, null], [17597, 22171, null], [22171, 28206, null], [28206, 32785, null], [32785, 39568, null], [39568, 45689, null], [45689, 50399, null], [50399, 57002, null], [57002, 57002, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57002, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57002, null]], "pdf_page_numbers": [[0, 5819, 1], [5819, 10966, 2], [10966, 17597, 3], [17597, 22171, 4], [22171, 28206, 5], [28206, 32785, 6], [32785, 39568, 7], [39568, 45689, 8], [45689, 50399, 9], [50399, 57002, 10], [57002, 57002, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57002, 0.12236]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
61ae50f5d855bbf017ee14bb4d56bf0497ac4ee3
|
Goals and Vision
Combining Web Services with Semantic Web Technology
Chris Preist
HP Laboratories, Bristol, UK, chris.preist@hp.com
Summary. This chapter introduces the combination of the formerly described Web Services and Semantic Web technologies to Semantic Web Services. It outlines the vision and goals in the Semantic Web Services area and clarifies terminology in this field. It defines an abstract Semantic Web Service architecture and introduces a life cycle of the relationship between a requester and a provider party. This motivates the subsequent chapters for description, discovery, mediation and invocation of semantically annotated services in the web.
6.1 Semantic Web Services Vision
As we have seen from previous chapters, the technologies provided by the Semantic Web are working towards a web which is machine-interpretable; a web where computer algorithms are able to process and reason with information which currently is only available in a human readable form. Web Services technologies, on the other hand, are working towards an environment where organisations can make some of their abilities accessible via the Internet. This is done by ‘wrapping’ some computational capability with a Web Service interface, and allowing other organisations to locate it (via UDDI) and interact with it (via WSDL). Web Service technology provides a standard and widely accepted way of defining these interfaces.
The Semantic Web Services vision is to combine these two technologies, and through this to enable automatic and dynamic interaction between software systems. Web Service technology allows the description of an interface in a standard way, but says nothing (in machine-interpretable form) about what the software system does, or what sequence of messages is used to interact with it. We can overcome this lack using Semantic Web technology. We can annotate software being offered via Web Service interfaces with machine interpretable descriptions describing what the software does (namely the service it provides a potential user) and how it does it. Furthermore, with ontologies able to describe the services that can be provided, we can bring about ‘advertising’ of services in a way which is both rich and machine-interpretable. This allows more sophisticated discovery of services than is currently possible with UDDI.
Combining these technologies enables many new things to be done. ‘Services’ as varied as protein analysis, bookselling, translation and animation rendering could be advertised and discovered automatically on the Internet. A company needing a service could locate a provider they were previously unaware of, set up a short-term business relationship and receive the service in return for a payment. All this could be done automatically and at high speed. Furthermore, several services could be combined into a more complex service, possibly automatically. If one of the component services is unavailable, a replacement could be rapidly found and inserted, so the complex service can still be provided.
Note that we used the word ‘enable’ in the previous paragraph. Semantic Web Services technology is an enabling technology, so it is necessary but not sufficient to bring about the vision we have just described. It provides a means for describing services, and also infrastructural capabilities to discover services and to enable inter-operation. However, it does not provide the reasoning to decide which service you want, which provider is ‘best’, how to negotiate the parameters of a service and what actions to take when using a service. If a service is simple and used in a straightforward way, this reasoning will also be simple. However, in some of the more ambitious scenarios, complex reasoning such as negotiation or dynamic planning will be necessary. Hence, Semantic Web Services alone will not bring about this brave new world – it can do so only in conjunction with other computer science disciplines.
6.2 Example Scenarios
The real value that Semantic Web Services can enable is best illustrated through some example scenarios which this technology, together with appropriate reasoning techniques, can bring about. In this section, we introduce four scenarios. Initially, we present a ‘storyboard’ for each. In subsequent sections, these example scenarios will be used to illustrate different features of Semantic Web Services.
6.2.1 Scenario A: Overdraft Notification Service
A bank provides an ‘overdraft notification service’ to its customers to help them manage their account, and to warn them when they are at risk of going overdrawn. Software at the bank monitors the behaviour of a customer’s account, and keeps track of when regular payments are made into or out of it. Based on the expected future transactions in an account, and the current balance, banking software can predict if the customer is likely to go overdrawn. If this is about to happen, the customer is warned via an email, text or voice message. To send the warning message, the bank’s software component uses some message-sending service. It does not have a pre-selected provider of this service, but instead automatically makes a decision at the time a message must be sent. To do this, it looks in a directory of available service providers and the message services they offer, and selects one based on factors such as cost, reliability and the preferences of the customer receiving the message. It then
sends the message to the provider of that service, which in turn sends a text or voice message to the customer.
This scenario is described in [4] in more detail.
### 6.2.2 Scenario B: Intelligent Procurement
A large manufacturing company makes regular purchases of supplies from a variety of on-line companies. Supplies essential for manufacturing, such as components, are purchased through a fixed supply chain from providers who have been carefully vetted to meet the company's requirements. However, less business-critical supplies, such as stationery, anti-static foot straps or reference books, can be purchased from any reputable supplier. This provides opportunity for shopping around to get the best deal. A software agent acting on behalf of the company is given a list of stationery equipment needed over the next month. It looks in a directory of suppliers the company considers acceptable for those which are able to supply stationery. The suppliers provide purchasing websites which use a 'shopping trolley' model similar to Amazon’s – a customer browses a catalog, places items it wants onto a list and goes to a checkout to get a quote for the total package, including postage. They provide a Web Service front end to these portals, allowing programs to interact with them as well as people. The software agent visits several such sites simultaneously. It interacts with them, discovering if they have the specific items in stock, and builds up a 'shopping trolley' of purchases. On reaching 'checkout', it receives a quote for each as to the total cost of the bundle, including volume discounts. Based on these quotes, it selects the cheapest and completes the transaction with that supplier, cancelling the other requests. The supplier then ships the order.
### 6.2.3 Scenario C: Provision of a Logistics Supply Chain
A company requires the transport of a crate from Bristol to Moscow. It already has long-term contracts in place for land transportation of crates from Bristol to Portsmouth, and from St Petersburg to Moscow. However, its usual supplier of shipping services is for some reason unavailable and it needs to rapidly locate and agree a replacement freight forwarder. A software agent acting on behalf of the company has detailed information about the transportation task which must be carried out. It contacts a discovery agent which has access to descriptions of services various organisations are able to provide, and asks for providers able to ship between Portsmouth and St Petersburg. The discovery agent responds with a list of possible freight forwarders likely to be able to meet these requirements. The software agent then selects one or more of the possible freight forwarders, and sends a more detailed description of the task it requires to be performed, including the date the shipment will arrive at Portsmouth, and the date it must reach St Petersburg. The freight forwarders respond with lists of services they can offer which meet these requirements. For example, one forwarder may say that it has a ship leaving Portsmouth on the required day which will arrive in St Petersburg the day before the deadline. It will also give the cost of placing a crate on that ship. The requesting agent then selects one of the proposed
services (possibly by interacting with a user to make the final decision) and informs
the provider of the decision. Effectively, the two parties enter into an agreement at
this point.
As the shipment takes place, it is coordinated by an exchange of messages
between the two parties. The messages use an industry standard, RosettaNet, which
describes the format and order of the messages. The exchange starts when the crate
is about to arrive in Portsmouth, with a RosettaNet Advanced Shipment Notification
being sent by the requester to the freight forwarder, and ends with the sending of
a Proof of Delivery and Invoice by the freight forwarder when the crate arrives in
St Petersburg.
This scenario is described in [5] in more detail.
6.2.4 Scenario D: Free Stock Quote Web Service
A small-time investor has a software package to keep track of his/her share portfolio.
He/she is able to receive updated share prices via Web Services technology. When
he/she connects to the internet, the software searches for services able to provide
share prices. It locates two possible services, and asks the user to select one. One
service gives prices delayed by 1 minute, and requires a subscription of € 10 /per
month to use. The other gives prices delayed by 30 minutes and is free. The investor
chooses the latter, because he/she does not engage in real-time trading, and the soft-
ware package then updates his/her portfolio information whenever he/she is online.
6.3 Key Concepts in Semantic Web Services
We now introduce some key concepts in Semantic Web Services, and show how
these inter-relate. In each case, we illustrate this with examples from the scenarios
introduced in Sect. 6.2. The work presented in this section follows the Semantic
Web–enabled Web Services conceptual architecture [6].
6.3.1 Notion of Service
First, let us define the key concept of service. Intuitively, one party provides a service
to another when the first party does something for the benefit of the second. A service
may be freely given, but is often done for payment. A window cleaner performs the
service of cleaning windows; a hairdresser performs the service of cutting hair. In
Scenario A above, the bank provides the overdraft warning service to its customer;
in Scenario B, the stationery supplier provides the service of sale and shipment of
stationery to the manufacturing company; in Scenario C, the freight forwarder pro-
vides the service of transferring a crate from one port to another. Formally, we can
summarise this by saying that a service is the performance of some actions by one
party to provide some value to another party. Note that it makes sense to talk about a
service in a certain domain. (In Scenario C, the domain would be transport and logis-
tics.) We refer to this as the domain of value of the service. We call the party which
performs the service the \textit{service provider} and the party which receives the benefit of the service the \textit{service requester}. Services can be considered at different levels of abstraction. A \textit{concrete service} is a specific performance of actions at a given time by one party for another. (In Scenario C, a concrete service would be the shipping of crate 246 on the ship departing from Portsmouth at 9:25 on 11/12/04 and arriving in St Petersburg at 22:00 on 14/12/04.) However, often when we are reasoning about services, we do not want to be so specific. In particular, when discussing a hypothetical service to be performed in the future, we cannot be specific about all of its details. Hence, we use an abstraction. An \textit{abstract service} corresponds to some set or class of concrete services, and allows us to discuss these hypothetical future services without being precise about all aspects of them. (In Scenario C, the service requester may want to talk about a hypothetical service which will carry crate 246, departing from Portsmouth sometime on 11/12/04 and arriving in St Petersburg before 17/12/04.)
6.3.2 Service Representation
One goal of Semantic Web Services is to bring about a computational machine-readable representation of the service, in terms of the value it provides. This is referred to as the \textit{service description}. Usually, a service description will describe an abstract service, in which case it can be referred to as an \textit{abstract service description}. Less often, a concrete service description is used to describe a concrete service.
To describe services, the Semantic Web approach uses techniques based on knowledge representation, a discipline which has developed a set of formal languages and techniques for describing knowledge in a way which permits reasoning with it. When describing a service, there are two key design decisions which must be made initially. First, what formal language is going to be used to describe it? Should it be described using horn clause logic, description logic, non-monotonic logic or some other approach? Different formalisms can be used, and this will be further discussed in Chap. 7. Secondly, what specific concepts and relations are going to be permitted in descriptions, and what is the meaning of these? This involves the creation or selection of an ontology, which provides a structured ontological vocabulary: a set of concepts and relations which can be used to describe things in the domain of interest. It is important that the terms the ontology provides allow a specification of the actions the service consists of, and/or the outcomes it brings about, in the terminology of the domain of value of the service.
When two parties describe services, they make different choices with regard to the language and ontology used. As a result, if one party is to reason with a description produced by the other party, then some additional reasoning will be necessary to translate between the two approaches. This additional reasoning is termed \textit{mediation}, specifically ontology mediation. Other forms of mediation may also be necessary, and we will discuss this further below.
6.3.3 Agents
Having discussed the representation of services, we need to consider the online representation of the service requester and provider. If the providing and receiving of a
service is to be automated, then these two parties must have some online presence. We refer to the software components which represent the parties as agents, with a service provider agent representing a service provider and a service requester agent representing a service requester.
These software components are agents in a very precise sense; they act as representatives online on behalf of some party. (This is the same sense of the word ‘agent’ as in ‘estate agents’, who act on behalf of a house seller.) Hence, the agent property is a role the component takes, rather than some intrinsic property of the component. Hence, these software entities are not necessarily agents in the sense used in Multi Agent Systems research [7]. Often, they will be reactive not proactive, and will be hardwired to follow some pre-determined process. For example, a set of Web Services provided by Amazon make up a service provider agent able to sell books on behalf of Amazon. However, as these entities become more sophisticated, and take on further tasks from the party they represent, they will make use of technology developed by the Multi Agent Systems community. For example, they may use negotiation algorithms [8] to allow them to agree details of services and prices; they may use distributed planning [9] to allow complex service composition and they may use utility theoretic reasoning to decide between possible alternative courses of action [10] as a service is delivered.
Another consequence of ‘agent’ being a role that a software component takes is that it can behave as a requester agent at one time, and a provider agent at another. This can be seen in Scenario A; the bank’s software system acts as a service provider agent to its customer, providing the service of account warnings. However, to get the warning message to its customer, the bank’s system behaves as a service requester and enters into an arrangement with a provider of a message delivery service.
If we are to be precise, we need to make a clear distinction between the service requester (or provider) and the service requester agent (or provider agent) which represents it. However, in practice this is not necessary in our subsequent discussions and we will use ‘service provider/requester’ to refer to the agent also.
6.3.4 Communication
Choreography
When a service is provided online, there must be some interaction between the provider and the requester. This interaction will require some exchange of messages. The exchange of messages within an interaction must follow certain constraints if they are to make sense to both parties. In other words, the message exchange must proceed according to a certain communication protocol known to both parties. In the Semantic Web Services world, a communication protocol, which can be multi-party, is often referred to as a choreography. For consistency with this existing literature, we will adopt this terminology subsequently. When some exchange of messages takes place according to the constraints provided by some choreography, we refer to this as a conversation between two parties which satisfies the choreography.
Interactions about a service may involve more than two parties, playing different roles. In general, many multi-party interactions can be reduced to a set of two-party interactions. However, there are some cases where this is not possible. For the purposes of this book, we focus only on two-party interactions; however, many of the concepts generalise straightforwardly to the multi-party case.
When two parties engage in a conversation, they must each have one or more communication endpoints to send and receive the messages according to some transport protocol. This is referred to as the *grounding* of the choreography. In many cases, service providers will interact via an interface specified in terms of Web Service operations. This is particularly the case for simple service provider agents with no internal state, where their choreography consists simply of a call–response interaction. The free stock quote service in Scenario D is of this type. However, there are other possibilities; the freight forwarder interacts using a complex set of RosettaNet messages with implicit state information in their sequencing, and these messages will be transported between the business partners using the RNIF standard.
**Semantics in Choreography**
As we discussed above, the first technical goal of Semantic Web Services is to provide machine-readable descriptions of service, to allow them to be reasoned with by different parties. The second technical goal of Semantic Web Services is to describe the different choreographies, which parties can use to interact, in a machine-readable form. This form should represent not only the messages which are exchanged, but also provide some model for the underlying intention behind the exchange of messages on the part of both parties. In other words, it should represent the semantics of the message exchange. In Scenario D, messages are exchanged to build up a stationery order; semantic representation of this will show that a certain sequence of messages corresponds to adding an item to the order, another sequence corresponds to getting a quote for the order, and another sequence corresponds to a final agreement that the order will be processed and payment made.
Doing this will allow software entities to reason about choreographies. For example, an entity could use an explicit model of a choreography to dynamically decide which action to take or message to send next.
**6.3.5 Orchestration and Service Composition**
As explained above, choreography determines the constraints on the ordering of messages sent between the service requester and service provider. However, the constraints alone are not enough to determine exactly which message is sent when. This is the role of an *orchestration*. An orchestration is a specification, within an agent, of which message should be sent when. Hence, the choreography specifies what is permitted of both parties, while an orchestration specifies what each party will actually do.
The real power of orchestration becomes evident when we look at multiple simultaneous relationships between agents. So far in this discussion, we have focused
on a single interaction, with one agent taking the role of service requester and the
other the role of service provider. However, it is clear that in many circumstances
an agent will be involved in multiple relationships; in some, it will be acting as a
service provider, while in others it will be acting as a service requester. For example,
in Scenario A, the bank’s overdraft notification service agent acts as a provider to
the bank’s customer. However, it outsources the task of delivering the notification to
other parties. Hence, it acts as a service requester in relationship with these parties.
Often, such an agent will communicate with several service providers and coor-
dinate the services they provide to produce some more complex service – as, e.g.,
the logistics coordinator does in Scenario C. This act of combining and coordinat-
ing a set of services is referred to as service composition. When a requester agent is
interacting simultaneously with many service providers, an orchestration can specify
the sequencing of messages with all of these, including appropriate dependencies.
The orchestration can be specified in several different ways. The most straightforward,
and least flexible, is to make a design time choice of which service providers
to use, and hard-code the integration logic in the service requester agent. A more
flexible way is to use a declarative workflow language to describe the process of
integrating the interactions with the chosen service providers. This is the approach
taken by BPEL [14]. This is more easily maintainable, but suffers from the draw-
back that if one of the chosen service providers is unavailable, then the overall ser-
vice orchestration will fail. A more robust approach, advocated by WSMF [11], is
not to select the service providers in advance within the orchestration, but instead
merely include descriptions of their required functionality. When the orchestration is
executed, appropriate service providers are dynamically discovered and selected at
run-time.
Having an explicit description of a service orchestration in terms of some process
language has a further advantage. It means that the orchestration can exist independ-
ently of a specific requester agent, and be passed between agents as a data structure.
This approach is used to a great extent by the OWL-S virtual machine [12]. Rather
than the service requester being responsible for generating an orchestration, any party
can produce one, showing how several services can be combined to produce a more
complex service. In particular, in the case where a single service provider offers a
variety of services, it is more appropriate for the provider to take responsibility to
show how they can be combined in different ways. If this is done in some agreed
standard process language, such as the OWL-S process model [13], and a service
requester has access to a means to interpret that process language, such as the OWL-S
virtual machine, then any such service requester can make use of the complex
service.
6.3.6 Mediation
When an interaction between two parties takes place, there may be further need
for mediation. There are four forms of mediation which could be necessary: data
mediation, ontology mediation, choreography mediation and process mediation. We
will now briefly introduce each.
**Data Mediation**
A message or fragment of data represents the information it carries in some specific syntactic format. Different service providers may expect different syntactic formats for their messages, even though the information carried is equivalent. Data mediation consists of transforming from one syntactic format to another.
**Ontology Mediation**
When two parties describe services, they make different choices with regard to the vocabulary of terms, and therefore ontology, used to do so. As a result, if one party is to reason with a description produced by the other party, then some additional reasoning will be necessary to translate between the two approaches. This additional reasoning is termed ontology mediation.
**Protocol Mediation**
Two components which are to interact with each other (such as a service requester and service provider) may each have been designed with a particular interaction choreography in mind. Unless agreement was reached between the two designers (either directly or indirectly through the adoption of a standard) then it is unlikely that the two choreographies will be identical. Protocol mediation is mediation which reconciles these two choreographies, by translating a message sequence used by one into a different message sequence used by the other to accomplish the same end.
**Process Mediation**
Behind any interaction, each party has some internal process which manages the reasoning and resources necessary to bring about that interaction. (In many domains of application, this will correspond to a business process.) In some cases, even though the two parties are able to interact via some protocol, there may be some difference between their processes which means this interaction will not succeed. Process mediation is mediation which reconciles the differences in such processes. This is the hardest form of mediation, and may in many cases be impossible without engaging in process re-engineering.
Mediation of these four different kinds is only possible automatically if the messages and choreographies are annotated semantically. It is key to enabling service interaction to take place automatically, and so forms a core part of the Semantic Web Services research programme. Further discussion will be provided in Chap. [10].
Up to now, we have discussed interactions between service provider and service requester in general terms, without considering the underlying goals of the interaction. This is because there are several different goals an interaction can have behind it. As the relationship between service provider and service requester progresses, different goals are required. For that reason, we now turn to this relationship.
6.3.7 Life cycle
The life cycle of the relationship between service requester and service provider goes through four phases: modelling, discovery, service definition and service delivery. During discovery, a requester attempts to locate possible providers able to give it the service it requires. During service definition, the requester and provider interact to define the details of the service which is to be provided. During service delivery, different kinds of interactions can occur which are associated with the provision of the service.
Service Modelling Phase
At the outset of the discovery phase, a service requester prepares a description of the service it is interested in receiving. Because it is unlikely that all details of the service will be known at the outset (e.g., the provider of the service is not known, and the cost of the service may not be known), the description will be of an abstract service. This abstract service description makes up the service requirement description of the service requester. Similarly, service providers create abstract service descriptions representing the service they are able to provide. This is referred to as the service offer description. Note that both the service requirement description and the service offer description are simply descriptions of a service, and hence use the same concepts and relations in the description. However, in each case, the service description plays a different role. In the first case, it describes a service which is being looked for, and in the second case it describes a service which is being provided.
Service Discovery Phase
If the requirement description of a requester and the offer description of a provider are in some sense compatible, then there is a match and the two parties could go on to the service definition phase. There are different ways of deciding whether two descriptions are compatible; these will be discussed in Chap. 8.
To illustrate this, consider Scenario A. The bank is looking for a service provider able to send a message to the customer. Let us say the customer has chosen to receive the message via text. The bank’s requester agent creates a service requirement description stating that it wants to send a text message of length 112 characters to a number on Telefonica Movistar, a Spanish mobile network. A provider advertises a service offer description stating that it is able to send text messages of maximum length 120 characters to Telefonica Movistar numbers at a cost of € 0.1. These two are potentially compatible, so a match should be made during discovery.
There are also different architectures which can be used to carry out discovery. The most common is a centralised discovery ‘service’ which is contacted by the requester using a simple message exchange protocol.
Service Definition Phase
During discovery, a requester may identify several providers which are potentially able to meet their needs. From the set of providers identified, the requester may contact one or more of these and enter into a service definition conversation with them. Selection of which to contact may simply be random, or may involve some analysis of the service providers and choice of which appear in some sense ‘best’. (Recall in Scenario D, the investor chose the cheaper but older service for stock quotes, because low cost was more important than having immediate information.) If service definition fails with those selected, the requester has the option to later contact others which were not initially selected, and try with those.
The service definition phase involves taking an abstract service description of a provider and refining it so that it describes a specific service which meets the requester’s needs. One way of conceptualising this is to think of the abstract service as having attributes which must be instantiated. In Scenario C, the shipment service would have attributes including weight of crate, departure and arrival ports, departure and arrival times, and price. The selection of the values these attributes take is the role of the service definition phase. Sometimes, it is not necessary to specify a specific value, but some constraint on a value is adequate. (In Scenario C, the arrival time might be specified as between 18.00 and 22.00.) This process takes place through a conversation governed by a service definition choreography.
When a requester enters into service definition phase with several possible providers, it will often be in an attempt to explore what options the different parties provide in order to select the best. (Recall in Scenario B, the service requester agent making a stationery purchase goes through the motions of preparing an order and receiving a quote with several providers.) The requester will complete the service definition phase with only one of them, terminating the conversations with those it has not selected.
If the service definition phase is successfully completed between two parties, they have agreed a service to be delivered by the provider to the requester, and can enter into the service delivery phase. Some of the attributes may not be fully defined, merely constrained. (In Scenario C, the freight forwarder may specify that the crate must be lighter than 500 Kg.) In this case, it means that one party (usually the provider) will allow the other to make a selection of attribute value during the delivery phase. (In Scenario C, the requester will inform the freight forwarder of the final crate weight in the advance shipment notification message it sends just before dispatch.) There may be a formal representation of the agreed service description, which can form part of a contract between the two parties [16].
In many cases, a service definition conversation will not be necessary. The description of the service by the provider will define fixed values for all the attributes the provider cares about. The only flexibility in the description will be where a provider is willing to allow a requester to freely choose. Effectively, the provider gives a ‘take it or leave it’ description of the service it provides, and the requester simply selects one. This can be seen in Scenario D. There is no service definition con-
versation between the investment software and the service provider agents. Instead, the investor simply selects which to use based on his/her preferences.
In some cases, the conversation will involve iterative definition of the service, selecting from options to create a complete description piece-by-piece. This can be seen in Scenario B, where the shopping-trolley metaphor is used during service definition. Through an exchange of messages between the two parties, the requester browses the wares, selects some, gets a final quote and agrees (or not) to purchase them.
Less often, the conversation may involve negotiation of certain parameters, such as price. Negotiation involves the iterative relaxing of constraints on values until some agreement is reached. Negotiation is an important area of agent technology research, but detailed discussion is beyond the scope of this chapter.
Service Delivery Phase
When the definition of a service has been agreed, then service delivery can take place. It may be immediate, as in Scenario A where the text message is sent as soon as the bank confirms its selection. Alternatively, it may take place a while after service definition has been completed, as in Scenario C where the agreement to carry a crate in a certain ship may be made days or weeks before the actual voyage. Service delivery may take place entirely off-line, with no communication, as in Scenario A where the text message is sent by the provider without any further exchange of messages. Alternatively, it may involve communication between the two parties. If communication takes place, this is again governed by an interaction choreography.
Several different types of interaction can occur during service delivery, and each is governed by a choreography:
1. The service delivery choreography covers the exchange of messages associated directly with the delivery of the service. In some cases, the service is provided directly by this exchange of messages, as in Scenario D where the stock quote data will be carried within a reply message from the quotation Web Service. In other cases, the exchange of messages is linked with activities occurring in the real world, as in Scenario C where the messages initiate and control (to a limited extent) the movement of a crate from Portsmouth to St Petersburg.
2. A monitoring choreography covers the exchange of messages which allow the service requester to receive information regarding the progress of the service from the provider. In Scenario C, there is a RosettaNet message exchange, ‘Shipment Status Message’, which allows the service requester to get information about the progress of the shipment from the freight forwarder. This is an example of a monitoring choreography.
3. A cancellation/renegotiation choreography allows the service requester, in certain circumstances, to cancel or alter the service which they are receiving from the provider. In Scenario B, we can imagine (as in Amazon) that the purchaser has the option to review, modify or cancel their order through an exchange of messages, provided the order has not entered the dispatching process.
6.4 Architecture for Semantic Web Services
Having introduced the concepts used in Semantic Web Services, we now consider an architecture which can be used to develop and deploy applications. Inevitably, by moving from a conceptual level to an architecture, certain design decisions will be made. We do not claim that this is the only way to make such decisions.
In Multi Agent Systems research, a distinction is made between a micro-architecture and a macro-architecture. A micro-architecture is the internal component-based architecture of an individual entity within a community. A macro-architecture is the structure of the overall community, considering each entity within it as a black box. It is also helpful to consider this distinction in Semantic Web Services. In an open community, it is necessary to standardise the macro-architecture to some extent, but the micro-architecture can be more flexible, with differences in design between various community members.
6.4.1 Macro-Architecture
Initially, we will present the macro-architecture for our community. In our community, there are three possible roles that a software entity can have: service requester agent, service provider agent and discovery provider agent. In general, an entity may have more than one role; however, for clarity we will consider each role separately.
To recap from the previous section, a service requester agent acts on behalf of an individual or organisation to procure a service. It receives a service requirement description from its owner, and interacts with other agents in an attempt to fulfil the requirement it has been given. It has some model, in an ontology, of the domain of the service and also has some model of the kind of actions that can be taken (through message exchange) in this domain.
A service provider agent is able to provide a service on behalf of an organisation. It has a service offer description in some domain ontology (ideally, the same as the requester agent), which describes at an abstract level the kind of services it can provide. It also has a means to generate more concrete descriptions of the precise services it can deliver. Furthermore, it has a formal description of the message protocol used to deliver the service. This includes mappings from the content of messages into concepts within the domain ontology. It also includes mappings from message exchange sequences into actions. In Scenario C, a field in the initial Advance Shipment Notification (ASN) message might map onto the ‘weight’ attribute of the ‘crate’ concept within the domain. The sequence consisting of one party sending the ASN and the other party acknowledging receipt may correspond to a ‘notify shipment’ action in the domain ontology.
A discovery provider agent has access to descriptions of service offers, together with references to provider agents able to provide these services. These service offer descriptions are all in some domain ontology associated with the discovery provider agent. Within this ontology is a ‘service description’ concept which effectively acts as a template for the descriptions of services that the discovery provider can contain.
We illustrate the macro-architecture by specifying the interactions which can take place between the different agents. These interactions are roughly in order of the life cycle progression introduced in the previous section.
1. Provider agent registering a service offer description
A simple message exchange protocol is used between a provider agent and a discovery agent. The provider agent sends a register message to the discovery agent, containing a service offer description in the ontology of the discovery agent and a URI for the provider agent. The discovery agent replies with an accept message if it is able to accept and store the description, reject otherwise. It will only reject a description if the description is not a valid concept in its ontology, or there is some practical reason it can’t accept it, such as lack of memory. Prior to this, if the provider agent is not aware of the ontology used by the discovery agent, it can send a requestOntology message to the discovery agent. The agent replies with an informOntology message containing the section of the ontology relevant to the service description. If this is a different ontology from that used by the service provider agent, then ontology mediation will be necessary. We assume this takes place within the provider agent. However, in general it could take place using a third party or within the discovery agent.
2. Requester agent finding possible providers
Discovery takes place through a simple exchange protocol between a service requester agent and a discovery agent. The requester agent sends a requestProviders message containing a service requirement description in the ontology used by the discovery agent. (As above, it can find out what this is using a requestOntology/informOntology exchange. It may then require ontology mediation, which we assume takes place within the requester agent.) The discovery agent responds with an informProviders message containing a list of URIs of service provider agents. These correspond to those provider agents which have offer descriptions stored within the discovery agent which match (using the discovery agent’s algorithm) with the service requirement description.
3. Requester and provider agents define service
Following discovery, the requester agent exchanges messages with one or more provider agents to define the service it will receive, and to select which provider agent to use. In our architecture, we assume a single simple service definition protocol is used by all requester and provider agents. This protocol is adequate for very many service definition tasks; however, in the general case this assumption is unrealistic and multiple protocols (and possibly protocol mediation) would be necessary. The FIPA standards provide various possible negotiation protocols which could be used at this stage. Our simple protocol consists of two rounds of message exchange. Initially, the service requester agent sends a requestServices message to each provider agent. The message contains
a service requirement description. The provider agent replies with an inform-
Services message, which contain (almost) concrete service descriptions of the
services it is able to provide that meet the needs of the requester. If the requester
wishes to select one of these, it replies with a selectService message containing
the required service, and the provider responds with confirm. The confirm mes-
sage contains a URI referencing where the description of the choreographies
which will be used during service delivery are to be found. If the requester does
not select one within a certain time window, sending no response to the provider,
this is taken as cancelling. Note that this protocol does not allow negotiation—it
simply allows the service provider to list a set of potentially interesting concrete
services to the requester, and allows the requester to select one of these. Note
also that our protocol does not capture Scenario B, intelligent procurement. The
service selection protocol used in this example is a shopping-trolley protocol.
While this is a natural protocol for human users (who are interested in brows-
ing, and looking at one item at a time), it is less essential for software entities
interacting with the service provider. We can imagine an alternative access proto-
col to shopping sites, similar to the one described here, where a requester agent
submits a list of product descriptions it is interested in, receives a list back of
relevant available products, selects a subset and places an order. However, in
practice, many sites will continue to use the shopping-trolley metaphor meaning
that protocol mediation will be important at this stage. For the purposes of the
architecture presented here, we ignore this additional complexity and assume all
parties use the same service specification protocol.
4. Service delivery
Service delivery starts when one party (depending on the choreography used)
sends an initiating message. Unlike previous stages, many different choreogra-
phies can be used depending on the domain of application of the service. In
Scenarios A and D, the choreography is simply a single message exchange cor-
responding to ‘do the service’, with a reply being ‘I have done the service and
here is the result.’ Scenario B is similar, except the response is ‘I will do the
service’ (and it takes place off-line, via mail.) In Scenario C, the choreography
used at this stage will correspond to the sequence of messages specified by the
RosettaNet standard.
Because of the large variety of choreographies which are possible during service
delivery, it is at this stage that protocol mediation will play the largest role. This will
particularly be the case where the choreography can be more complex, as in Scen-
nario C. For the purposes of this architecture, we assume that any protocol mediation
that is required will take place in the service requester agent and use the choreogra-
phy descriptions referenced by the provider agent. However, mediation can equally
well take place within the provider or within a third party.
Given this assumption, then the macro-architecture appears as follows. Each ser-
vice provider has a description of the service delivery choreography associated with
each service it can provide. At the end of the service definition protocol, as a parameter of the confirm message, it informs the requester of a URI which references this description. The requester is then responsible for accessing this description, interpreting it and engaging in a message exchange with the provider which satisfies the requirements of the choreography described.
6.4.2 Micro-Architecture
Having described the macro-architecture, we now turn to the micro-architecture of the system. We look at two of the three roles that software entities can have – requester agent and provider agent – and present a micro-architecture for each. The micro-architecture of the discovery service provider agent will be covered in Chap. 8. Note that, unlike the macro-architecture, a micro-architecture is not normative within a community. The macro-architecture defines the exchange of messages between entities of different roles, and if the community is to function effectively, this must be agreed and adhered to (though the provision of protocol mediation within the macro-architecture allows some flexibility). The micro-architecture of each agent, however, need not follow some pre-agreed structure. The community can function perfectly well with any internal structure, provided the functionality the micro-architecture implements does indeed correspond to the requirements of the macro-architecture.
Figure 6.1 illustrates our architecture for the service requester agent. At the heart of the agent is the application logic, which is responsible for decision-making with
regard to which service to select and how to make use of it. This can include integration with other back-end systems within the organisation which the service requester agent represents. It may also access and assert information in the knowledge base. In other cases, the application logic will be provided by a user interacting through a user interface; the requester agent effectively acts as an online proxy for the user, and relays any important decision-making problems to them, acting on their choice.
The first role of the application logic is to define a service requirement description for the service it needs. When this has been done, it passes the description to the discovery and definition component. This component is responsible for managing the discovery and service definition choreographies, and sends appropriate messages to do this as described in the macro-architecture above. The message format and contents are prepared using the messaging lift/lower component and passed to the transport routines for transmission via an appropriate transportation protocol. Often, but not exclusively, these transportation routines will use WSDL Web Service technology for communicating with the service provider. At points where a decision is required – namely when one or more provider is to be chosen to contact after discovery and when a service is to be chosen during the selection process – the decision is passed for the application logic to be made. The message lift/lower component performs data mediation. When it receives incoming messages, it translates their contents into semantic information according to an ontology and stores these in the Knowledge Base. It generates the content of outgoing messages by using facts in the Knowledge Base to fill fields according to some message schema. When a service has been defined, the application logic initiates the delivery process by passing the URI identifying the delivery choreography to the delivery component. Unlike the discovery and selection component, which contains hard-wired logic for a single protocol, the delivery component is able to carry out protocol mediation. It accesses the description of the choreography given by the service provider. This shows how message contents map onto the domain ontology of the knowledge base, and also shows how sequences of messages correspond to actions within this domain ontology. State machines describe the order in which actions can take place. The application logic can request the execution of an action. This will result in the delivery component initiating an exchange of messages with the service provider. The content of a message will be instantiated by accessing the knowledge base and ‘lowering’ the relevant information into the required message format using the lift/lower component. The message can then be passed to the transport routines for transmission. When a message is received as part of such an exchange, the contents of the message will be ‘lifted’ into the knowledge base using the lift/lower component and the delivery component will note the progress of the message exchange. When an exchange terminates (either through successful completion or through some failure) the application logic is informed of this. The delivery component also handles messages from the provider which are not part of an exchange initiated by the requester. These correspond to actions within the domain which the provider is initiating. The delivery component identifies which action they are initiating, ‘lifts’ the message content to the knowledge base and informs the application logic. It replies (possibly after a decision from the application logic of how to respond) by ‘lowering’ content into a
message, which is then passed to the transport routines. Full details of this process, and the architecture used, are given in Chap. 10.
We now turn our attention to the provider agent (Fig. 6.2). Because, in our architecture, we assume that protocol mediation takes place within the requester, the provider can be simpler. It also has an application logic component at its heart, which is responsible for deciding which services to offer a given requester and also for the provisioning of the service itself. As in the case of the requester, this will often involve integration with a variety of back-end systems belonging to the service provider’s organisation. Initially, the application logic prepares a service offer description and registers this with the discovery service provider. It also prepares a choreography description associated with this service, and publishes it on the web, giving it a URI. From that point on, in our architecture, the provider agent is reactive.
The service definition component has an interface (often, though not exclusively, provided by Web Service WSDL technology) which allows a requester to submit a service requirement description. On receipt of this, the application logic prepares a set of possible services which satisfy the requirement, and this is sent to the requester through the definition component interface. If the definition component receives a selection message from the requester, it responds with a confirm containing the URI of the choreography description which it obtains from the application logic. The service delivery protocol is executed by the service delivery component, again via an interface which may or may not use WSDL Web Service technology. Unlike the requester agent, the provider agent does not need to carry out protocol mediation so the protocol can be hard-wired in the component. Message contents are still lifted into the knowledge base, for access by the application logic. The application logic is informed of the progress of the conversation, requested to initiate internal actions.
---
**Fig. 6.2.** Architecture of service provider agent
to bring about the service, and also consulted if a decision is necessary during the execution of the protocol. In this way, the micro architectures of the two types of actor can animate the conversations required by the macro-architecture. The macro-architecture in turn embodies the concepts introduced in our conceptual model of Semantic Web Services.
### 6.5 Outlook
In this chapter, we have presented a conceptual model for Semantic Web Services which is driven from a requirements analysis of several scenarios. Using this conceptual model, we have developed a technical architecture which could be used to deploy applications of Semantic Web Services. We have introduced the key notions of discovery, service description, mediation and composition, and shown how they form part of a service life cycle within our conceptual model. Subsequent chapters will provide more details of these ideas, and present the techniques available to make them real.
The architecture presented in this chapter is one possible embodiment of the conceptual model, but others are possible. This particular embodiment has been implemented as part of the EU Semantic Web–enabled Web Services program, and has been used to create a demonstrator of Semantic Web Services technology in the domain of logistics supply chain management [5]. If Semantic Web Services are to be deployed effectively on a large scale, it will be necessary for the community to reach agreement about how to do this. A conceptual model and flexible architecture will be a necessary part of this agreement. We believe the ideas presented in this chapter are a step in this direction.
### References
13. [http://www.daml.org/services/owl-s/](http://www.daml.org/services/owl-s/)
Semantic Web Services
Concepts, Technologies, and Applications
Studer, R.; Grimm, S.; Abecker, A. (Eds.)
2007, VI, 406 p., Hardcover
ISBN: 978-3-540-70893-3
|
{"Source-Url": "https://www.springer.com/cda/content/document/cda_downloaddocument/9783540708933-c1.pdf?SGWID=0-0-45-410428-p173722504", "len_cl100k_base": 10579, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 43945, "total-output-tokens": 12471, "length": "2e13", "weborganizer": {"__label__adult": 0.00042724609375, "__label__art_design": 0.0007047653198242188, "__label__crime_law": 0.0005898475646972656, "__label__education_jobs": 0.0021533966064453125, "__label__entertainment": 0.00023567676544189453, "__label__fashion_beauty": 0.0002419948577880859, "__label__finance_business": 0.002254486083984375, "__label__food_dining": 0.0004584789276123047, "__label__games": 0.0010004043579101562, "__label__hardware": 0.0010538101196289062, "__label__health": 0.0007119178771972656, "__label__history": 0.0006194114685058594, "__label__home_hobbies": 0.00012564659118652344, "__label__industrial": 0.0007219314575195312, "__label__literature": 0.0009360313415527344, "__label__politics": 0.0004482269287109375, "__label__religion": 0.0005402565002441406, "__label__science_tech": 0.25439453125, "__label__social_life": 0.00017631053924560547, "__label__software": 0.048187255859375, "__label__software_dev": 0.68115234375, "__label__sports_fitness": 0.0003018379211425781, "__label__transportation": 0.002201080322265625, "__label__travel": 0.0004200935363769531}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58591, 0.01768]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58591, 0.29427]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58591, 0.92567]], "google_gemma-3-12b-it_contains_pii": [[0, 2351, false], [2351, 5452, null], [5452, 8726, null], [8726, 11576, null], [11576, 14963, null], [14963, 18115, null], [18115, 21263, null], [21263, 24597, null], [24597, 27314, null], [27314, 30128, null], [30128, 33559, null], [33559, 36699, null], [36699, 39874, null], [39874, 42905, null], [42905, 46158, null], [46158, 47742, null], [47742, 51475, null], [51475, 53605, null], [53605, 56390, null], [56390, 58435, null], [58435, 58591, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2351, true], [2351, 5452, null], [5452, 8726, null], [8726, 11576, null], [11576, 14963, null], [14963, 18115, null], [18115, 21263, null], [21263, 24597, null], [24597, 27314, null], [27314, 30128, null], [30128, 33559, null], [33559, 36699, null], [36699, 39874, null], [39874, 42905, null], [42905, 46158, null], [46158, 47742, null], [47742, 51475, null], [51475, 53605, null], [53605, 56390, null], [56390, 58435, null], [58435, 58591, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58591, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58591, null]], "pdf_page_numbers": [[0, 2351, 1], [2351, 5452, 2], [5452, 8726, 3], [8726, 11576, 4], [11576, 14963, 5], [14963, 18115, 6], [18115, 21263, 7], [21263, 24597, 8], [24597, 27314, 9], [27314, 30128, 10], [30128, 33559, 11], [33559, 36699, 12], [36699, 39874, 13], [39874, 42905, 14], [42905, 46158, 15], [46158, 47742, 16], [47742, 51475, 17], [51475, 53605, 18], [53605, 56390, 19], [56390, 58435, 20], [58435, 58591, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58591, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
b1540ebb1718dcb773624bbe41e96abcd1f7cd27
|
EDF Schedulability Analysis for an Extended Timing Definition Language
T. Kloda, B. d’Augsbourg, L. Santinelli
To cite this version:
T. Kloda, B. d’Augsbourg, L. Santinelli. EDF Schedulability Analysis for an Extended Timing Definition Language. 9th IEEE International Symposium on Industrial Embedded Systems, Jun 2014, PISA, Italy. hal-01067909
HAL Id: hal-01067909
https://onera.hal.science/hal-01067909
Submitted on 24 Sep 2014
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
EDF Schedulability Analysis for an Extended Timing Definition Language
Tomasz Kloda, Bruno d’Ausbourg, Luca Santinelli
ONERA Toulouse, name.surname@onera.fr
Abstract—In a time-triggered system, activities like task releasing, operational mode switches, sensor readings and actuations are all initiated at predetermined time instants. This paper proposes an extension of the TDL (Timing Definition Language) time-triggered compositional framework, and presents, based on the widely-applied methods, a condition for its schedulability. The schedulability condition developed accounts for multiple concurrently executing modules, multiple operational modes and mode switches. This way the system schedulability can be guaranteed in any execution condition.
I. INTRODUCTION
The development of embedded software is a highly platform dependent process. The main difficulty lies in both formulating the functional specification of the system and correctly determining its temporal behavior. While the former is facilitated by high-level programming languages which abstract from many hardware aspects, getting the expected temporal characteristic of the system involves usually much more efforts due to the implementation of scheduling policies, synchronization, and inter-processes communication protocols.
To efficiently manage these two crucial aspects for system correctness, time-triggered languages are devised for embedded programming. These languages clearly separate the functional part of applications and their timing definition. Applications are specified through two descriptions: their timing definition, expressed in a time-triggered language, and the functional code of tasks, expressed in any programming language. At the final stage, a dedicated compiler generates, based on both descriptions, a ready-to-run executable for a selected target-platform. This allows system designers and developers to focus on the functional aspects instead of the platform (hardware and operating system) without being interested in where, how and when tasks are actually scheduled: on platforms with a single or many CPUs, on platforms with a preemptive priority scheduling or not.
Time-triggered languages provide a programming abstraction which was firstly introduced within the Giotto programming language [13]. Giotto assigns to each task a Logical Execution Time (LET) [14] which defines the precise instants when the task exchanges data with the other tasks and with its environment. A task is invoked and reads its input ports at the beginning of its LET interval, then performs a computation whose results are made available on its output ports exactly at the end of the LET. Figure 1 shows the difference between the logical and physical execution of a task. The observable temporal behavior of a task is independent from the platform related factors such as processing speed, scheduling policy and communication protocols.

Timing Definition Language (TDL) [9], [10], [26], a successor of Giotto, extends these concepts by allowing a decomposition of large real-time systems into concurrently executing tasks sets named modules. Each TDL module runs in one operational mode at a time and can switch the modes independently of other modules.
A. Contributions
While enabling timing and value predictability of programs, Giotto and TDL can be further extended towards a more flexible and more realistic application modeling. In both frameworks, the task LET and period are equal. Introducing a task model with an initial offset and the LET of a task terminating before the end of its period, is what we call Extended Timing Definition Language (E-TDL). This new E-TDL framework is presented in Section II.
With E-TDL it is necessary to guarantee safe execution during multimodal operation inside every module. In section I-B are cited some methods [27], [11] that can be adapted to our case in order to provide a schedulability condition. They address mainly event-triggered systems where the execution of an activity is triggered by the occurrence of an event whose arrival cannot be predefined beforehand. Hence, it can be supposed that in all modules the events which produce the biggest demand may arrive at the same time.
Time-triggered systems observe the state of the controlled object only at specified time instants and initiate appropriate activities only at these instants. Time instants of tasks activations are precisely defined and it is known whether tasks are launched simultaneously or not. Consequently it may be avoided to consider the synchronous case in analysis when it is well known that this case never occurs.
Compositional analysis of such systems should be able to exhibit the relations between the start of the intervals in different modules and compare only these that can actually...
start at the same time. Therefore, the analyses that are well-suited for event-triggered systems can be overestimating in the time-triggered context.
With this work we propose a sufficient condition for the feasibility of an E-TDL system running on a single CPU under the Earliest Deadline First (EDF) scheduling policy. In Section IV we describe an offset analysis to identify feasible execution configurations. In Section V we detail the schedulability analysis which makes use of these configurations and applies to time-triggered E-TDL systems.
B. Related Work
Many different protocols and methodologies attempting to ensure the schedulability of a system across mode switches have been proposed in the literature. Protocols known as synchronous [28], [2], [22] do not release new tasks until all old mode tasks are completed. On the contrary, asynchronous protocols, both for Fixed Priority [29], [19], [22] and EDF [1], [7], define that during transition phase the last activations of old mode tasks and new mode tasks can be executed simultaneously. In TDL and E-TDL, systems can be composed of many modules and each module can undergo mode transitions that are defined only in its local scope. For systems designed in a compositional manner, an approach based on the real-time calculus (RTC) [27] is developed in the work of Stoimenov et al. [25]. Fisher [11] proposed a schedulability test for EDF where the allocation of the processing resources for each subsystem is represented by an explicit-deadline periodic resource model [8] and a sporadic task model [17] is chosen. Servers can also dynamically adapt their parameters of resource reservation. The feasibility under multi-moded resource reservation was studied by Santinelli et al. in [23].
Concerning the schedulability analysis of time-triggered systems the most significant contributions were made notably by Farcaş [9] for TDL and Martinek in the Giotto in Ada [16] framework. The latter extends a Giotto’s task model with the notion of deadline but, since Giotto is not a compositional framework, these results cannot be applied in this instance.
II. EXTENDED TDL MODEL
An E-TDL periodic task \( \tau_i \) \( (\Phi_i, C_i, LET_i, T_i) \) is characterized by an offset \( \Phi_i \), a worst-case execution time \( C_i \), a Logical Execution Time \( LET_i \) (that gives its relative deadline \( D_i \)) and a period \( T_i \).
The offset \( \Phi_i \) is restricted to be smaller than the period \( 0 \leq \Phi_i < T_i \) and \( LET_i \) has to be large enough that task could be executed within it, \( C_i \leq LET_i \leq T_i - \Phi_i \). Moreover, the LET semantics does not allow the \( j \)-th instance \( (j \in \mathbb{N}_+) \) of task \( \tau_i \) started in the time interval \( [(j-1)T_i, jT_i] \) to be finished after time \( jT_i \). Taking into account the above mentioned constraints, an E-TDL task \( \tau_i \) may be implemented by a periodic real-time task whose absolute releases and deadlines are expressed respectively as \( r_{i,j} = \Phi_i + (j-1)T_i \leq jT_i \) and \( d_{i,j} = \Phi_i + LET_i + (j-1)T_i \leq jT_i \).
The LET semantics imposes that a task reads periodically its inputs exactly when it is released and delivers its outputs exactly at the end of its LET interval.
An E-TDL system consists of multiple modules running on the same node. All modules of the system, referred hereafter as Modules, run concurrently sharing common processing resources. Each module \( M_j \) \( \in \text{Modules} \) from a scheduling point of view, is considered independent from the others.
The basic functional units of time-triggered languages are tasks that periodically execute some piece of code. Several concurrent tasks may be grouped into a mode. Tasks are invoked within the mode at declared frequencies and can be removed or added when switching from one mode to another. They communicate between them as well as with sensors and actuators by means of ports. A mode is invoked and performs appropriate actions whenever the environment is in some specific condition that should be handled by this particular operational mode [18]. With a mode \( m_k \), the set of tasks belonging to \( m_k \) is \( \tau[m_k] \).
At a time module \( M_j \) executes one of its modes from the set \( \text{Modes}[M_j] \). One of them is the initial mode \( m_{init} = Init[M_j] \) and is executed at the system beginning. Each mode \( m_k \) executes periodically within its mode period \( T[m_k] \). A mode period is restrained to be a common multiple of the periods of all tasks belonging to that mode, \( T[m_k] \equiv n H[m_k] \) with \( n \in \mathbb{N}_+ \), and \( H[m_k] \equiv \text{lcm}\{T_i \mid \tau_i \in \tau[m_k]\} \).
The relative amount of time spent inside a mode \( m_k \) is named mode time \( \delta_k \) and is set to 0 every time a mode period begins. A module state can be described by the tuple \( (m_k, \delta_k) \). As mode time \( \delta_k \) evolves within the mode period \( T[m_k] \), 0 \( \leq \delta_k \leq T[m_k] \), appropriate actions like releasing or terminating tasks, are triggered.
Whenever a condition change is detected in the environment or inside the system, the current operating mode stops its activities and a new mode starts instantaneously with a mode set to zero. These transitions are described in E-TDL by mode switches. During execution of mode \( m_k \) the conditions to switch from mode \( m_k \) to mode \( m_{k+1} \) are checked periodically every mode switch period \( T_{sw}\{m_k,m_{k+1}\} \). The instants at which this check occurs are named mode switch instants, \( \delta_{ms} \).
If the conditions are satisfied, the mode switch can take place. Every mode switch period \( T_{sw}\{m_k,m_{k+1}\} \) is restricted to be a common multiple of all the task periods of \( m_k \):
\[
T_{sw}(m_k, m_{k+1}) \mod H[m_k] = 0 \land \\
\exists n \in \mathbb{N}_+, n T_{sw}(m_k, m_{k+1}) = T[m_k].
\] (1)
Such a choice of mode switch instants entails that a mode switch may occur only when no current mode task is running. This way the new mode can be safely activated without any
delay. In future works we will enhance the mode switch within E-TDL to let it safely happen before $T_{sw}(m_k, m_{k+1})$.
Within an actual mode $m_k$, the modes that may be started at $\delta_k$ belong to the set $\text{starting\_modes}(m_k, \delta_k)$ where
$$\text{starting\_modes}(m_k, \delta_k) = \{m_{k+1} | \exists T_{sw}(m_k, m_{k+1}) : \delta_k \mod T_{sw}(m_k, m_{k+1}) = 0\} \cup \{m_k | \delta_k = T[m_k]\}. \quad (2)$$
III. COMPOSITIONAL SCHEDULABILITY ANALYSIS FOR E-TDL
The presented E-TDL multi-mode model imposes on each module of the system a set of possible execution patterns that can be observed during the system temporal evolution. In what follows, the behavior of every module is characterized in time and the processing resources the module demands over time are quantified. This permits to provide a sufficient condition for the schedulability of the whole system under mode switches.
A. Execution Trace of an E-TDL Module
In [9] Farcas proposed a mode-switch graph which allows to exhibit all the modes of a given module and the transitions it can undergo. Modes are represented by vertices and mode switches by directed edges in the graph. The mode switch period labels the edge. More formally, the mode switch graph of a module $M_j \in Modules$ describes the set of switches that this module can undergo. Each mode switch is defined as a tuple $(m_k, m_{k+1}, T_{sw}(m_k, m_{k+1}))$ where $m_k, m_{k+1} \in Modes[M_j]$ and $T_{sw}(m_k, m_{k+1})$ is the period of the $(m_k, m_{k+1})$ mode switch. Restarting the same mode after the end of its period can be also considered as a mode switch $(m_k, m_k, T[m_k])$ and is so depicted on the graph.
The mode switch graph can be defined as the set:
$$\{(m_k, m_{k+1}, T_{sw}(m_k, m_{k+1})) | m_k, m_{k+1} \in Modes[M_j], \exists \delta_k : m_{k+1} \in \text{starting\_modes}(m_k, \delta_k)\} \quad (3)$$

During its execution, a module can remain in the current mode or switch to one of its possible successive modes. The behavior of a module can be described by a walk that travels through its mode-switch graph, visiting modes at multiples of mode switch periods, jumping to another modes whenever there is a need for changing mode.
**Definition 1 (Walk in a Mode-Switch Graph).** A walk $w = (m_1, \mu_1), \ldots, (m_n, \mu_n)$ of an E-TDL mode-switch graph is a sequence of $n$ pairs where $m_1, \ldots, m_n$ are the subsequent modes in the mode-switch graph, and $\mu_1, \ldots, \mu_n$ are the numbers of:
- times the mode switch condition to $m_{k+1}$ has been checked in $m_k$ (number of $T_{sw}(m_k, m_{k+1})$ spent in $m_k$), for $k < n$; $\mu_k \in \mathbb{N}_+$,
- full periods $T[m_k]$ spent in $m_k$, for $k = n$; $\mu_k \in \mathbb{N}_0$.
The first mode $m_1$ in the walk $w$ is designated as $\text{head}(w)$ and the last mode $m_n$ as $\text{tail}(w)$. The length of a walk $w = (m_1, \mu_1), \ldots, (m_n, \mu_n)$ can be expressed as:
$$|w| = \sum_{k=1}^{n} \mu_k T_{sw}(m_k, m_{k+1}) \quad (4)$$
We use $T_{sw}(m_k, m_{k+1})$ interchangeably with $T[m_k]$ for $k = n$ as there is no next mode in the walk $w$.
Figure 4 illustrates how an execution trace in the interval $[t_s, t_f]$ can be decomposed. This trace encapsulates a walk $w$ between two time intervals. Both of these time intervals cover an execution pattern within a single mode run. The interval that precedes $w$ starts at time $t_s$ and ends when the module enters mode $\text{head}(w)$. The interval at the tail of $w$ starts in mode $\text{tail}(w)$ at mode time 0 and ends at $t_f$.
**Definition 2 (Module Execution Trace).** An execution trace of an E-TDL module $M_j \in Modules$ over a time interval $[t_s, t_f]$ is denoted by $\sigma_{M_j} = (m_s, \delta_s, \delta'_s, w, m_f, \delta_f)$ where
- $m_s \in Modes[M_j]$ is the module executing before walk $w$,
- $\delta_s : 0 < \delta_s \leq T[m_s]$ is the mode time related to $t_s$,
- $\delta'_s : \delta_s \leq \delta'_s \leq T[m_s]$ is the mode time of mode $m_s$,
- $w$ is a walk in the mode-switch graph of module $M_j$,
- $m_f \in Modes[M_j]$ is the module executing after walk $w$,
- $\delta_f : 0 \leq \delta_f < T[m_f]$ is the mode time related to $t_f$.
It has to be fulfilled that:
- $\text{head}(w) \in \text{starting\_modes}(m_s, \delta'_s)$,
- if $\text{tail}(w) \neq m_f$,
then $m_f \in \text{starting\_modes}(\text{tail}(w), T[\text{tail}(w)])$ and $\text{tail}(w)$ is executed at least one time at the end of $w$,
- $t_f - t_s = \delta'_s - \delta_s + |w| + \delta_f$.
Short intervals, within which no more than one mode period is executed, can be represented as $\sigma_{M_j} = (m_s, \delta_s, \delta'_s, 0, 0, 0)$.

When a module $M_j$ runs a walk, it crosses modes. $M_j$ can stay in any mode $m_k$ before starting $m_{k+1}$ for any time that is a multiple of the mode switch period $T_{sw}(m_k, m_{k+1})$. The length of a walk can be expressed as a linear combination of the modes switch periods it spends in each of its modes.
**Definition 3 (Path in a Mode-Switch Graph).** A path $p$ in an E-TDL mode-switch graph is the set of mode switch periods that can be traversed by some walk $w$ that executes tail($w$) at least once. Walk $w = ((m_1, \mu_1), \ldots, (m_k, \mu_k), (m_{k+1}, \mu_{k+1}), \ldots, (m_n, \mu_n))$ where $\mu_n \geq 1$, follows a path $p$ if:
$$ p = \{ T_{sw}(m_k, m_{k+1}) | k < n \} \cup \{ T[m_k] | k = n \}. $$
**B. Resource demand of an E-TDL Module**
To determine the schedulability of an E-TDL system, the resource demand in each module should be precisely quantified.
An E-TDL execution trace is the combination of two types of intervals. Before and after its walk no more than one mode period is executed. The walk itself constitutes a sequence of intervals that span over some number of mode switch evaluation periods. Based on the concept of demand function and demand bound function [4], what follows evaluates the resource demands in such intervals with respect to the E-TDL model we are considering. Let $\delta_k$ and $\delta_k'$ be the mode times of the mode $m_k$ such that $0 \leq \delta_k < \delta_k' \leq T[m_k]$. The demand function $df(m_k, \delta_k, \delta_k')$ within a mode $m_k$ is the cumulative execution time required by all the task instances in $m_k$ having its releases and deadlines between $\delta_k$ and $\delta_k'$.
$$ df(m_k, \delta_k, \delta_k') \overset{\text{def}}{=} \sum_{\tau_i \in [\delta_k, \delta_k')} \left( \left\lfloor \frac{\delta_k - \Phi_i - LET_i}{T_i} \right\rfloor \right) C_i + \left\lfloor \frac{\delta_k' - \Phi_i}{T_i} \right\rfloor C_i \tag{5} $$
For a walk $w$, its demand function can be calculated as:
$$ df(w) \overset{\text{def}}{=} \sum_{(m_k, \mu_k) \in w} \mu_k T_{sw}(m_k, m_{k+1}) U(m_k) \tag{6} $$
where $U(m_k)$ is the processor utilization factor of mode $m_k$:
$$ U(m_k) \overset{\text{def}}{=} \sum_{\tau_i \in [\delta_k, \delta_k')} C_i \tag{7} $$
The foregoing definitions can be applied to express the resource demanded by an E-TDL module execution trace $\sigma_{M_j}$.
**Definition 4 (Demand Function).** For a given E-TDL execution trace $\sigma_{M_j} = (m_s, \delta_s, \delta_s', w, m_f, \delta_f)$, its demand function $df(\sigma_{M_j})$ is the cumulative processing time required by $M_j$ to execute $\sigma_{M_j}$.
$$ df(\sigma_{M_j}) \overset{\text{def}}{=} df(m_s, \delta_s, \delta_s') + df(w) + df(m_f, 0, \delta_f) \tag{8} $$
Execution traces depend on the system evolution. During an interval $\Delta$ that starts when module $M_j$ is running mode $m_s$ at mode time $\delta_s$, different execution traces may be observed: each of them is depending on the performed mode switches. Each of these execution traces is characterized by some value of demand function. Only the highest demand function value of these traces can be considered in the further analysis.
**Definition 5 (Maximal Demand Function).** For module $M_j \in \text{Modules}$ maximal demand function $\maxdf_{M_j}(m_s, \delta_s, \Delta)$ denotes the largest value of demand function that characterizes some E-TDL execution trace of length $\Delta$ that starts from mode time $\delta_s$ in mode $m_s \in \text{Modes}[M_j]$.
$$ \maxdf_{M_j}(m_s, \delta_s, \Delta) \overset{\text{def}}{=} \max_{\sigma_{M'_j}} \left\{ \left\{ df(\sigma_{M'_j}) \right\} \right\} \tag{9} $$
The following definition estimates the highest demand function value for an E-TDL execution trace which can start at an arbitrary mode time in any one of the declared modes. We call it maximal demand bound function to recall the notion of demand bound function from [4] and differentiate with respect to it due to the different task model from E-TDL.
**Definition 6 (Maximal Demand Bound Function).** The maximal demand bound function $\maxdbdf_{M_j}(\Delta)$ denotes the maximal cumulative requirement of computation for module $M_j \in \text{Modules}$ during any time interval $\Delta$ over E-TDL execution traces.
$$ \maxdbdf_{M_j}(\Delta) \overset{\text{def}}{=} \max_{(m_s, \delta_s)} \{ \maxdf_{M_j}(m_s, \delta_s, \Delta) \} \tag{10} $$
**C. Schedulability of an E-TDL System**
We are now able to formulate our first schedulability condition for an E-TDL system under EDF. This condition is derived from the processor demand criterion [4], [6]. The schedulability of a task set where deadlines are less than periods is guaranteed whenever the cumulative demand of the computation made by its tasks in any interval is never larger than the length of this interval. The following theorem adapts this reasoning to the E-TDL framework by cumulating the processor demands over modules. It checks for any time interval if the total amount of processing time requested by all the individual modules to complete their execution traces does not exceed the interval length. Multi-mode E-TDL with mode switches at $T_{sw}$ are included into the following schedulability theorem.
**Theorem 1 (Schedulability of an E-TDL System).** Let be an E-TDL system defined by a set of modules $\text{Modules}$ such that:
$$ \sum_{M_j \in \text{Modules}} \max_{m \in \text{Modes}[M_j]} \left\{ U(m) \right\} \leq 1 \tag{11} $$
If for every time interval $\Delta > 0$:
$$ \sum_{M_j \in \text{Modules}} \maxdbdf_{M_j}(\Delta) \leq \Delta \tag{12} $$
then the E-TDL system is schedulable under EDF on one processor.
Proof: The proof of this theorem can be derived from Lemma 3.4 in [4]. The authors show that a complete task
The cumulative demand is functions over an interval of this length for the individual
Theorem 1, Equation (12), is not satisfied. The demand bound
follows:
\[ \tau \]
It can be seen from the above figure that the system is
overestimation for time-triggered systems.
Example 1. Given an E-TDL system composed of modules
modes, and modules relationships. The schedulability analysis
of multi-module multi-mode E-TDL systems will benefit from
these conditions. The statements of these conditions are based
on paths.
Definition 7 (Greatest Common Divisor of Path). The
greatest common divisor \( \gcd(p) \) of a path \( p \) is the greatest
common divisor of all mode switch periods making this path
and of the period of its last mode.
Defining \( T'_{sw}(m_k, m_{k+1}) = T_{sw}(m_k, m_{k+1}) / \gcd(p) \), the length of a
walk in Equation (4) can be rewritten as:
\[ |w| = \gcd(p) \sum_{j=1}^{n} k T'_{sw}(m_k, m_{k+1}). \]
All the pairs \( T_{sw}(m_k, m_{k+1}) \) within a path \( p \) are mutually
prime, and a walk \( w \) of \( p \) is a linear combination of these
coprime integers. From the Frobenius problem statement [21],
[24] it follows that, given a set of relatively prime positive
integers \( a_1, \ldots, a_n \), any natural number larger than some
bound noted as \( F(a_1, \ldots, a_n) \) can be expressed as a linear
combination of \( a_1, \ldots, a_n \). Then, for a given path \( p \) the lengths
of its potential walks, and so the start instants of the last mode
in these walks, fall in the set of all natural multiples of \( \gcd(p) \).
A generic destination mode \( m_{dst} \) can begin at the time instants
in \( \text{start}(m_{dst}) \), and it is
\[ \text{start}(m_{dst}) \subset \bigcup_{p \in P_{dst}} \{ n \gcd(p) \mid n \in \mathbb{N} \} \]
where $P_{\text{dst}}$ is the set of all the paths leading from the initial mode to the destination mode $m_{\text{dst}}$. Then $(m_{\text{dst}}, \delta_{\text{dst}})$ can be observed at time $t = t_{\text{start}}(m_{\text{dst}}) + \delta_{\text{dst}}$ where $t_{\text{start}}(m_{\text{dst}}) \in \text{start}(m_{\text{dst}})$.
B. Time distance between mode starts in distinct modules
We now evaluate the time distances that can separate start instants of the modes running in distinct modules. The proposed approach is derived from the work of Pellizzoni and Lipari [20] that is applied to the analysis of the real-time periodic tasks with offsets.
The following lemma characterizes the time distances between activations of two modes in two distinct modules.
**Lemma 1 (Interval between two modes).** The time distance between start instants of mode $m_a \in \text{Modes}[M_a]$ and mode $m_b \in \text{Modes}[M_b]$ with $M_a, M_b \in \text{Modules}$ and $M_a \neq M_b$ lies within the set
$$\bigcup_{p_a \in P_a, p_b \in P_b} \{ \alpha \gcd(p_a \cup p_b) \mid \alpha \in \mathbb{Z} \}. \quad (15)$$
$P_a$ is a set of paths leading from $\text{Init}[M_a]$ to $m_a$ and $P_b$ is a set of paths leading from $\text{Init}[M_b]$ to $m_b$.
Proof: The difference $\Delta_{\text{start}}(m_a, m_b)$ between start instants of mode $m_a$ and mode $m_b$ which were reached by traversing respectively path $p_a$ and path $p_b$ may be expressed using Equation (14):
$$\Delta_{\text{start}}(m_a, m_b) = t_{\text{start}}(m_a) - t_{\text{start}}(m_b) = n_1 \gcd(p_a) - n_2 \gcd(p_b)$$
According to the Bézout's identity [3], for any non zero integers $c$ and $d$ there exist integers $x, y \in \mathbb{Z}$ such that $cx + dy = \gcd(c, d)$ and every integer of the form $cx + dy$ is a multiple of $\gcd(c, d)$. This implies that the values of $\Delta_{\text{start}}(m_a, m_b)$ are multiples of $\gcd(\gcd(p_a), \gcd(p_b))$. Because the greatest common divisor operation satisfies the property of associativity [12], the last term can be rewritten as $\gcd(p_a \cup p_b)$.
The following Lemma refines Lemma 1 by evaluating precisely the time intervals that can separate the start instants of two concurrent modes instances.
**Lemma 2 (Interval between two concurrent modes).** Given mode $m_a \in \text{Modes}[M_a]$ and mode $m_b \in \text{Modes}[M_b]$ where $M_a, M_b \in \text{Modules}$ such that $M_a \neq M_b$. If the current instance of mode $m_b$ started no later than the current instance of mode $m_a$, then the time distances between starts of these two instances lie inside the following set:
$$\bigcup_{p_a \in P_a, p_b \in P_b} \{ \alpha \gcd(p_a \cup p_b) \}, \quad (16)$$
where $\alpha \in \mathbb{N} : 0 \leq \alpha \gcd(p_a \cup p_b) < T[m_b]$.\n
Proof: For $\alpha = 0$ the most recent instances of $m_a$ and $m_b$ start exactly at the same time. The previous possible mode’s $m_b$ activation points are moved back by multiples of $\gcd(p_a \cup p_b)$ as explained in Lemma 1. From some $\alpha$ value, start instants of mode $m_b$ belong to the previous $m_b$ instances (terminated before the activation of the current one). Since the only considered instances of mode $m_b$ should be these which run concurrently with $m_a$, the value of $\alpha \gcd(p_a \cup p_b)$ cannot exceed the length of the period $T[m_b]$. \hfill $\blacksquare$
The above relation holds for a pair of modes. We generalize this result to the case of a compound system of more than two modes.
**Lemma 3 (Intervals between n modes).** Let $\text{Modules}' \subseteq \text{Modules}$ be a set of $n - 1$ E-TDL modules $M_1, \ldots, M_{n-1}$ such that $n : 3 \leq n \leq |\text{Modules}|$ and $m_1, \ldots, m_{n-1}$ be the $n - 1$ modes each belonging to a different module in $\text{Modules}'$. Let $M_n \in \{ \text{Modules} - \text{Modules}' \}$ and $m_n \in \text{Modes}[M_n]$. Suppose that the current instances of modes $m_1, \ldots, m_{n-1}$ and $m_n$ are running at the same time and every mode $m_k$ ($k \in \mathbb{N} : 1 \leq k \leq n$) has been reached by taking a path $p_k$. Suppose also that mode $m_1$ started its most recent activation no sooner than all the other modes ($1 \leq k \leq n$).
If each mode $m_k \in \text{Modules}' (1 < k < n)$ started $\alpha_k \gcd(p_1 \cup p_k)$ time units before mode $m_1$, then the possible offsets that separate the start of $m_n$ and the start of $m_1$ are given by $\alpha_n \gcd(p_1 \cup p_n), \alpha_n \in \mathbb{N}$ and must satisfy the following conditions:
1. $0 \leq \alpha_n \gcd(p_1 \cup p_n) < T[m_n]$
2. $\forall k \in \mathbb{N} : 1 < k < n, \exists \alpha \in \mathbb{Z} : \alpha_n \gcd(p_1 \cup p_n) = \alpha_k \gcd(p_1 \cup p_k) + r \gcd(p_k \cup p_n)$.
Proof: The first condition results from Lemma 2. The second condition anchors the start instant of $m_n$ with respect to the start instants of the other modes. Each mode $m_k : 1 < k < n$ starts $\alpha_k \gcd(p_1 \cup p_k)$ time units before the start of $m_1$ and is not finished by this time. From Lemma 1 it follows that the start instant of $m_n$ can occur only at time points that lie in the distance $r \gcd(p_k \cup p_n)$ from the start of $m_k$. This relation is expressed by the second condition. \hfill $\blacksquare$
For an E-TDL system defined by a set $\text{Modules}$, the point of interest is to identify all the relations between concurrently running modes $m_1, \ldots, m_{|\text{Modules}|}$ in distinct modules of the system. These modes are reached by walking along paths $p_1, \ldots, p_{|\text{Modules}|}$.
**Algorithm 1 VerifyStartInstants($p_1, \ldots, p_n, \alpha_2, \ldots, \alpha_n$)**
Require: $\forall 1 \leq k \leq n : p_k$ is a path to mode $m_k$
Require: Lemma 3 holds for $p_1, \ldots, p_{n-1}$ and $\alpha_2, \ldots, \alpha_{n-1}$
Ensure: Lemma 3 holds for $p_1, \ldots, p_n$ and $\alpha_2, \ldots, \alpha_n$
1: if not $0 \leq \alpha_n \gcd(p_1 \cup p_n) < T[m_n]$ or $k_n \notin \mathbb{N}$ then
2: return false
3: end if
4: for $k \leftarrow 2, n - 1$ do
5: $\text{diff} := \alpha_n \gcd(p_1 \cup p_k) - \alpha_k \gcd(p_1 \cup p_k)$
6: $\text{rem} := \text{diff} \mod \gcd(p_k \cup p_n)$
7: if $\text{rem} \neq 0$ then
8: return false
9: end if
10: end for
11: return true
Algorithm 1 makes use of Lemma 3. Given \( \alpha_2, \ldots, \alpha_{n-1} \) that realizes mode starts setup according to Lemma 3 for \( n - 1 \) modes, it checks if introduction of \( \alpha_n \) for a \( n \)-th mode characterizes a realizable mode starts setup for these \( n \) modes. We look for a set \( \alpha(\text{Modules}) \{p_1, \ldots, p_{|\text{Modules}|}\} \) of all the tuples \( (\alpha_2, \alpha_3, \ldots, \alpha_{|\text{Modules}|}) \) meeting conditions of Lemma 3. These tuples represent all the valid modes offsets. The set \( \alpha(\text{Modules}) \{p_1, \ldots, p_{|\text{Modules}|}\} \) can be obtained by applying Algorithm 2, where initially the set \( \alpha(n-2) \) of all \( \alpha_2 \) fulfilling Lemma 2 for modes \( m_1 \) and \( m_2 \) is computed. Then, by incrementing \( n \) from \( n = 3 \), the tuples \( (\alpha_2, \ldots, \alpha_n) \) are estimated according to Lemma 3, till \( n = |\text{Modules}| \).
Algorithm 2 FindStartInstants \( p_1, \ldots, p_{|\text{Modules}|} \)
Require: \( \forall M_j \in \text{Modules}: \exists \alpha_k \in \text{Modes}[M_j] \)
Ensure: \( \forall (\alpha_2, \ldots, \alpha_{n-1}) \in \alpha(\text{Modules}) \text{ Lemma 3 holds} \)
\begin{align*}
1: & \quad \alpha(2) = \{ \alpha_2 \mid \text{Lemma 2 holds for } \alpha_2 \text{ and paths } p_1 \text{ and } p_2 \} \\
2: & \quad \text{for } n \leftarrow 3, |\text{Modes}| \text{ do} \\
3: & \quad \alpha(n) \leftarrow 0 \\
4: & \quad \text{for all } (\alpha_2, \ldots, \alpha_{n-1}) \in \alpha(n-1) \text{ do} \\
5: & \quad \text{for all } \alpha_n : 0 \leq \alpha_n \text{ gcd}(p_1 \cup p_n) < T[m_n] \text{ do} \\
6: & \quad \text{if Lemma 3 holds for } (\alpha_2, \ldots, \alpha_{n-1}, \alpha_n) \text{ then} \\
7: & \quad \alpha(n) := \alpha(n) \cup (\alpha_2, \ldots, \alpha_{n-1}, \alpha_n) \\
8: & \quad \text{end if} \\
9: & \quad \text{end for} \\
10: & \quad \text{end for} \\
11: & \quad \text{end for} \\
12: & \quad \text{return } \alpha(|\text{Modules}|) \\
\end{align*}
C. Observable Parallel Configurations
An external observer of an E-TDL system can describe its state at a particular time instant of the run as a snapshot. This snapshot describes the modes and mode times in each concurrent module at that moment. We name this snapshot a parallel configuration of the system denoted as \( \zeta = (\{m_1, \delta_1\}, \ldots, \{m_n, \delta_n\}) \) where \( n = |\text{Modules}| \) \( \forall M_j \in \text{Modules} \), \( m_k \in \text{Modes}[M_j] \) and \( \delta_k \) is the current mode time in \( m_k \).
A parallel configuration is observable if its modes offsets are in accordance with conditions of Lemma 3 (mode offsets can be found by applying Algorithm 2).
Definition 8 (Observable Parallel Configuration). Given an E-TDL system composed of \( n \) Modules \( n = |\text{Modules}| \) a parallel configuration \( \zeta = (\{m_1, \delta_1\}, \ldots, \{m_n, \delta_n\}) \) is observable if there exists \( (\alpha_2, \ldots, \alpha_N) \in \alpha(n)(p_1, \ldots, p_N) \) such that:
\begin{equation}
\forall k, 1 < k \leq n : \quad (\delta_k - \delta_1 + T[m_1]) \mod T[m_k] = \alpha_k \text{ gcd}(p_1 \cup p_k) \tag{17}
\end{equation}
Each of these observable parallel configurations will be analyzed and checked for feasibility.
It may happen that the start instant of some mode can occur at any mode time of any other concurrent mode. Given modes \( m_1, \ldots, m_n \) running in parallel such that each mode \( m_k \) \( (1 \leq k \leq n) \) has been reached by path \( p_k \), then a mode \( m_x \) \( (1 \leq x \leq n) \) can start its execution at whatever mode time of any other mode \( m_k \) if \( \forall k \neq x : \text{gcd}(p_x \cup p_k) = 1 \). Furthermore, if the above condition is met not only for some of concurrent modes but for all of them, it can be deduced that any combination of mode times in different modes defines an observable parallel configuration. Given modes \( m_1, \ldots, m_n \) running in parallel such that each mode \( m_k \) can be reached by path \( p_k \in P_k \) where \( P_k \) is the set of all the paths leading from the initial mode to mode \( m_k \). Any mode \( m_k \) can start its execution at any time instant of concurrent modes if \( \exists P \in \prod_{k=1}^{n} P_k : \forall p_k, p_{k'} \in P, \text{gcd}(p_k \cup p_{k'}) = 1 \).
In that case all the possible parallel configurations are observable. Consequently, the execution traces with the largest processor demand can be simultaneous. Then Theorem 1 can be used without any overestimation. Otherwise, the following exact analysis can be performed.
V. E-TDL Exact EDF Schedulability
The feasibility condition we derive for an E-TDL system running under EDF on one processor makes use of offsets and task relationships. In order to be schedulable, for any observable parallel configuration, the maximal processing demands of execution traces that begin at that particular configuration cannot exceed the processing resources in any time interval. The following theorem guarantees schedulability of an E-TDL system.
Theorem 2 (Exact Schedulability of an E-TDL System). Let be an E-TDL system defined by a set of \( n \) modules Modules \( (M_k \in \text{Modules}, 1 \leq k \leq n) \) such that:
\begin{equation}
\sum_{k=1}^{n} \max_{m \in \text{Modes}[M_k]} \{U(m)\} \leq 1 \tag{18}
\end{equation}
If for every observable parallel configuration \( \zeta = (\{m_1, \delta_1\}, \ldots, \{m_n, \delta_n\}) \) and every time interval \( \Delta > 0 \):
\begin{equation}
\sum_{k=1}^{n} \text{maxdf}_{M_k}(m_k, \delta_k, \Delta) \leq \Delta \tag{19}
\end{equation}
where \( (m_k, \delta_k) \) is the state of module \( M_k \) in the observable parallel configuration \( \zeta \), then the E-TDL system is schedulable under EDF on one processor.
Proof: The proof of this theorem is similar to the proof of Theorem 1 and can be also derived from Lemma 3.4 in [4]. We designate by \( t_1 \) a time instant at which a parallel configuration \( \zeta \) was observed. For \( \Delta > 0 \), the maximal demand function \( \text{maxdf}_{M_k}(m_k, \delta_k, \Delta) \) quantifies the greatest possible resources that can be requested by module \( M_k \in \text{Modules} \) in the interval \( [t_1, t_2] \) such that \( \Delta = t_2 - t_1 \) and \( M_k \) is running in \( (m_k, \delta_k) \) at the time instant \( t_1 \). The total amount of processing time available in the interval \( [t_1, t_2] \) is equal to \( \Delta \). By summing up the maximal demands from the particular modules we obtain the resources that must be granted for E-TDL system in the time interval \( [t_1, t_2] \). If these resources do not exceed \( \Delta \), E-TDL system is schedulable.
A. Feasibility Bound
In this section we derive an upper bound for the time interval \( \Delta \) in Theorem 2 so that condition 19 becomes fully computationally tractable. If an E-TDL system is not schedulable, then some of its tasks will miss its deadline in the time interval that is no longer than this bound.
Every interval \( \Delta \) can be seen as a composition of three adjacent intervals: \( \Delta_1, \Delta_2 \) and \( \Delta_3 \). Interval \( \Delta_2 \) spans over the time from the first to the last hyperperiod point in \( \Delta \), whereas \( \Delta_1 \) and \( \Delta_3 \) cover the pieces of execution occurring respectively before and after \( \Delta_2 \). Figure 6 illustrates the above described \( \Delta \) decomposition.

The maximum value of demand function in any interval \( \Delta_1 \) for a module \( M_j \), denoted by \( df_{M_j}(\Delta_1) \), is given by:
\[
\max df_{M_j}(\Delta_1) = \max df_{M_j}(m_k, r_{\min}(m_k), H[m_k]) \\
\leq \max_{m_k}(U(m_k)H[m_k])
\]
where \( r_{\min}(m_k) \) is the earliest release of some task from mode \( m_k \in Modes[M_j] \) occurring after the beginning of this mode. In like manner, the maximum value of demand function for any interval \( \Delta_3 \), denoted by \( df_{M_j}(\Delta_3) \), can be found:
\[
\max df_{M_j}(\Delta_3) = \max df_{M_j}(m_k, 0, d_{\max}(m_k)) \\
\leq \max_{m_k}(U(m_k)H[m_k])
\]
where \( d_{\max}(m_k) \) is the latest deadline of some task from mode \( m_k \in Modes[M_j] \) before its hyperperiod \( H[m_k] \). The maximum value of demand function for any interval \( \Delta_2 \), covering full executions of the hyperperiods of subsequent modes from the first hyperperiod in the first mode to the start of the last hyperperiod in the last mode inside interval \( \Delta \), is denoted by \( df_{M_j}(\Delta_2) \) such that:
\[
\max df_{M_j}(\Delta_2) \leq \Delta \max_{m_k}(U(m_k)) \quad (20)
\]
where \( m_k \in Modes[M_j] \).
As there is no tasks that can be started in one of these intervals and having deadline in another, for any \( \Delta \) and any valid mode time \( \delta_k \) in mode \( m_k \) from module \( M_j \) the following relation is derived:
\[
\Delta \max_{m_k}(U(m_k)) + 2 \max_{m_k}(U(m_k)H[m_k]) \geq \\
\max df_{M_j}(\Delta_1) + \max df_{M_j}(\Delta_2) + \max df_{M_j}(\Delta_3) \\
\geq \max df_{M_j}(m_k, \delta_k, \Delta)
\]
where \( m_k \in Modes[M_j] \).
Similarly to the reasoning proposed by Baruah [4], [5], if the system is not schedulable, there exists some \( \Delta \) for which the second condition of Theorem 2 is violated:
\[
\sum_{M_j \in Modules} \max df_{M_j}(m_k, \delta_k, \Delta) > \Delta
\]
Taking into account beforehand obtained properties bounding function \( \max df_{M_j}(m_k, \delta_k, \Delta) \), an overflow observed in \( \Delta \) implies that:
\[
\sum_{M_j \in Modules} \left( \Delta \max_{m_k}(U(m_k)) + 2 \max_{m_k}(U(m_k)H[m_k]) \right) > \Delta
\]
Thus, it is sufficient to check the feasibility for the intervals that are no longer that:
\[
\Delta < \frac{2 \times \sum_{M_j \in Modules} \max_{m_k}(U(m_k))}{1 - \sum_{M_j \in Modules} \max_{m_k}(U(m_k))} \quad (21)
\]
where \( m_k \in Modes[M_j] \).
VI. Test Case
A sample E-TDL system is studied to gain insight into the key aspects of the proposed EDF schedulability analysis.
The test case is a 3-modules E-TDL system, where the modules \( M_1, M_2, M_3 \in Modules \) execute on the same node. Each module defines its modes together with modes switches as it is indicated on Figure 7 (the topmost mode in each module is considered to be the initial mode). Periods, mode switch periods as well as all the task parameters making up the particular modes are presented in Table 1.

<table>
<thead>
<tr>
<th>Module</th>
<th>mode</th>
<th>( T )</th>
<th>( T_{sw} )</th>
<th>tasks</th>
</tr>
</thead>
<tbody>
<tr>
<td>M1</td>
<td>( m_{11} )</td>
<td>10</td>
<td>10</td>
<td>( T_{111}(0, 2, 6, 10), T_{112}(0, 1, 5, 5) )</td>
</tr>
<tr>
<td>M1</td>
<td>( m_{12} )</td>
<td>8</td>
<td>-</td>
<td>( T_{121}(2, 1, 2, 8) )</td>
</tr>
<tr>
<td>M2</td>
<td>( m_{21} )</td>
<td>4</td>
<td>4</td>
<td>( T_{211}(0, 1, 4, 4) )</td>
</tr>
<tr>
<td>M2</td>
<td>( m_{22} )</td>
<td>8</td>
<td>4</td>
<td>( T_{221}(1, 1, 1, 8) )</td>
</tr>
<tr>
<td>M3</td>
<td>( m_{31} )</td>
<td>8</td>
<td>-</td>
<td>( T_{311}(2, 1, 1, 8) )</td>
</tr>
</tbody>
</table>
Tab. 1: Modes and tasks properties
On the first attempt, we apply Theorem 1 to verify system schedulability. Since the sum of the maximal utilization factors for the modes in distinct modules is not greater than 1, we verify condition given by Equation (12). In Figure 8, a series of plots illustrates maximal demand bound functions \(mdbf_{M_1}, \)
The greatest common divisors $\gcd(p_a \cup p_b)$ for pairs of paths leading to modes in different modules are calculated in Table 3. According to Lemma 1, for $p_{22} = 4$ and $p_{31} = 8$, every time distance separating starts of these two modes is a multiple of $\gcd(p_{22} \cup p_{31}) = 4$. From Lemma 2 we obtain $\alpha(p_{22}, p_{31}) = \{0, 1\}$. Mode $m_{31}$ can start either at the same time as $m_{22}$ (0 × $\gcd(p_{22} \cup p_{31})$) either 4 time units before (1 × $\gcd(p_{22} \cup p_{31})$). Equation (18) is not satisfied by any coefficient $\alpha(p_{22}, p_{31})$ for module $M_2$ state $(m_{22}, 1)$ and module $M_3$ state $(m_{31}, 2)$, since $(2 - 1 + 8) \mod 8 \notin \{0, 4\}$. A parallel configuration where these two module states coincide is not observable and therefore the execution traces $\sigma_{M_2}$ and $\sigma_{M_3}$ cannot start at the same time instant. It can be concluded that the system is schedulable in the interval $\Delta = 1$.
For interval $\Delta = 2$, the parallel configurations for which the schedulability of the system cannot be guaranteed by Theorem 1 are as follows:
$$\{((m_{12}, 2), (m_{22}, \delta_{22}), (m_{31}, \delta_{31})) \mid \delta_{22} \in \{0, 1\}, \delta_{31} \in \{1, 2\}\}$$
Since all these configurations occur during concurrent execution of modes $m_{12}$, $m_{22}$ and $m_{31}$, the relationship between their starts should be established.
We apply Lemma 2 to paths leading to modes $m_{12}$ and $m_{22}$ (see Table 2) under the assumption that the current instance of mode $m_{12}$ is invoked no earlier than the current instance of $m_{22}$. It results in values of $\alpha_2 \in \alpha^2(p_{12}, p_{22})$ which correspond to the distances $(\alpha_2 \times \gcd(p_{12} \cup p_{22}))$ between starts of $m_{12}$ and $m_{22}$ concurrent instances. By considering path leading to mode $m_{31}$, from Lemma 3, we have $\alpha^3(p_{12}, p_{22}, p_{31})$ of tuples $(\alpha_2, \alpha_3)$. Each tuple $(\alpha_2, \alpha_3)$ describes a mode activation pattern in which $m_{22}$ and $m_{31}$ started respectively $\alpha_2 \times \gcd(p_{12} \cup p_{22})$ and $\alpha_3 \times \gcd(p_{12} \cup p_{31})$ instants before $m_{12}$. Table 4 shows all valid tuples $(\alpha_2, \alpha_3)$ together with possible walks starting at the initialization of every module and resulting in the activation pattern reflected by this tuple.
Having values of $\alpha^3(p_{12}, p_{22}, p_{31})$ at our disposal, we define all the observable parallel configurations for concurrent execution of modes $m_{12}$, $m_{22}$ and $m_{31}$. Table 5 represents,
for module’s $M_1$ state $(m_{12}, 2)$, the possible module $M_2$ and $M_3$ states that satisfy Equation (18).
\[
\begin{array}{cccccccc}
\delta_{22} & (0,0) & (0,2) & (1,1) & (1,5) & (2,0) & (2,2) & (5,1) & (5,5) \\
\delta_{31} & 2 & 2 & 4 & 4 & 6 & 6 & 0 & 0 \\
\end{array}
\]
Tab. 5: Parallel configurations $(m_{12}, 2), (m_{22}, \delta_{22}), (m_{12}, \delta_{31})$
It can be seen from Table 5 that the parallel configurations at which the execution traces requesting 1 unit of computation over interval $\Delta = 2$ start are never activated simultaneously. Therefore, the sum of maximal demand functions in $\Delta = 2$ for any observable parallel configuration, is never larger than 2. The system is schedulable according to Theorem 2.
VII. CONCLUSION AND FUTURE WORK
In this paper we extended the TDL task model into E-TDL, and proposed the condition for the feasibility of an E-TDL system scheduled by EDF on one processor. A methodology to exhibit all the possible timing configurations of the system in presence of mode switches has been introduced. Based on the well-founded concept of processor demand we provided techniques to describe resource requirement of such a system.
One of the issues to be addressed in the future is the reduction of the complexity of our solution. This can be achieved by optimizing computation of demand functions and investigating if there exist some point from which they can be periodic. The feasibility bound, in certain cases, could be also estimated more tightly. If in the tested interval the existence of the point where all the modes from distinct modules terminate synchronously can be stated, it would not be necessary to continue the analysis beyond this point.
Another interesting proposal may be running all the modules in temporal isolation. The question that should be answered then would be the choice of the most suitable resource reservation pattern.
Concerning the reactivity of the system, we suggest that mode switches may operate not only at instants that are hyperperiods but also at some possible other idle instants in the mode. Some tasks whose completion is not vital for the consistency of the system, might be aborted across the mode switches.
REFERENCES
|
{"Source-Url": "https://onera.hal.science/hal-01067909/file/DTIM14042.1405599757.pdf", "len_cl100k_base": 13549, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 49044, "total-output-tokens": 15914, "length": "2e13", "weborganizer": {"__label__adult": 0.0003578662872314453, "__label__art_design": 0.00067901611328125, "__label__crime_law": 0.0003535747528076172, "__label__education_jobs": 0.0012350082397460938, "__label__entertainment": 0.00011330842971801758, "__label__fashion_beauty": 0.00019788742065429688, "__label__finance_business": 0.0006489753723144531, "__label__food_dining": 0.0004112720489501953, "__label__games": 0.0008826255798339844, "__label__hardware": 0.00432586669921875, "__label__health": 0.0006785392761230469, "__label__history": 0.00044417381286621094, "__label__home_hobbies": 0.0002009868621826172, "__label__industrial": 0.0013322830200195312, "__label__literature": 0.00030112266540527344, "__label__politics": 0.0003783702850341797, "__label__religion": 0.0006384849548339844, "__label__science_tech": 0.239501953125, "__label__social_life": 8.082389831542969e-05, "__label__software": 0.01074981689453125, "__label__software_dev": 0.73486328125, "__label__sports_fitness": 0.00031185150146484375, "__label__transportation": 0.00115966796875, "__label__travel": 0.0002503395080566406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50701, 0.02751]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50701, 0.39552]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50701, 0.81193]], "google_gemma-3-12b-it_contains_pii": [[0, 978, false], [978, 5875, null], [5875, 12005, null], [12005, 16780, null], [16780, 22546, null], [22546, 24320, null], [24320, 30551, null], [30551, 37271, null], [37271, 41930, null], [41930, 44539, null], [44539, 50701, null]], "google_gemma-3-12b-it_is_public_document": [[0, 978, true], [978, 5875, null], [5875, 12005, null], [12005, 16780, null], [16780, 22546, null], [22546, 24320, null], [24320, 30551, null], [30551, 37271, null], [37271, 41930, null], [41930, 44539, null], [44539, 50701, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50701, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50701, null]], "pdf_page_numbers": [[0, 978, 1], [978, 5875, 2], [5875, 12005, 3], [12005, 16780, 4], [16780, 22546, 5], [22546, 24320, 6], [24320, 30551, 7], [30551, 37271, 8], [37271, 41930, 9], [41930, 44539, 10], [44539, 50701, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50701, 0.02258]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
56ada2d0b8dfd5f77798bc9dd865b54da37ee408
|
Change Impact Identification in Object Oriented Software Maintenance
D. Kung, J. Gao, P. Hsia, F. Wen
Computer Science Engineering
Univ. of Texas at Arlington
P. O. Box 19015
Arlington, TX 76019-0015
Tel: (817) 273-3627
Fax: (817) 273-3784
Email: kung@cse.uta.edu
Y. Toyoshima, and C. Chen
Fujitsu Network Transmission Systems, Inc.
Abstract
Types of code changes in an object oriented library are described. A formal model for capturing and inferencing on the changes to identify affected classes is described. The model consists of three types of diagrams: the object relation diagram (ORD), the block branch diagram (BBD), and the object state diagram (OSD). An ORD describes the inheritance, aggregation, and association relationships between the classes of a C++ library. A BBD describes the control structure and interfaces of a member function. And an OSD describes the state behavior of a class. Unlike in modeling, these diagrams are automatically generated from code and facilitate understanding and changing a C++ library. An OO software maintenance environment that implements the research result is described. Our experience with the environment prototype shows promising results.
Key words and phrases: software maintenance, object oriented programming, change analysis, impact identification, regression testing, environment, tool
1 Introduction
One important activity of software maintenance is regression testing, which ensures that the modified software still satisfies its intended requirements. To save effort, regression testing should retest only those parts that are affected by the modifications.
In traditional function-oriented programming, only control dependencies exist between the modules; and hence, it is relatively easy to identify the affected modules. In the object-oriented (OO) paradigm, a number of new features is supported, such as encapsulation, information hiding, inheritance, aggregation, polymorphism, and dynamic binding. These new features introduce new problems in the maintenance phase, including difficulty of identifying the affected components when changes are made.
Encapsulation and information hiding imply the so-called “delocalized plan” [solo88a], in which several member functions from possibly several object classes are invoked to achieve an intended functionality. This phenomenon means that changes to a member function of a class may affect many classes. Inheritance and aggregation imply structure and state dependent behavior reuse, i.e., the data members, function members, and state dependent behavior of a class are re-used by another class. Thus, there are data dependencies, control dependencies, and state behavior dependencies between the two classes. Moreover, since the inheritance and aggregation relations are transitive relations, the above dependencies also are transitive dependencies. Polymorphism and dynamic binding imply that objects may take more than one form, and which form an object assumes is unknown until run time. This makes the identification of the affected components much more difficult.
The maintenance complications introduced by the OO features can be summarized as follows: 1) although it is relative easy to understand most of the data structures and member functions of the object classes, understanding of the combined effect or combined functionality of the member functions is extremely difficult; 2) the complex relationships between the object classes make it difficult to anticipate and identify the ripple effect\(^1\) [gane82a] of changes; 3) the data dependencies, control dependencies, and state behavior dependencies make it difficult to prepare test cases and generate test data to “adequately” retest\(^2\) the affected components; 4) the complex relations also make it difficult to define a cost-effective test strategy to retest the affected components.
In an attempt to solve above problems, the Software Engineering Center for Telecommunications at UTA and Fujitsu Network Transmission Systems, Inc. have undertaken a major effort in the last two years to develop a methodology for OO software testing and maintenance. The results obtained so far include: 1) a reverse engineering approach for design recovery of C++ programs [kung93b]; 2) a three level schema and algorithms for data flow testing of OO programs [chan93a]; 3) definition and identification of class firewalls and a test strategy for regression testing of C++ programs [kung94a]; 4) a specification-based method for object state testing [kung94b]; and 5) a program-based method for object state testing [kung94c]. Part of these results and other results have been implemented in an integrated testing and maintenance environment [kung93g] [song93a].
This paper discusses types of changes that can be made to an OO library. It also describes a method for identifying the affected classes due to structure changes to an object class library. The method is based on a reverse engineering approach to extract the classes and their interrelationships. This information is represented in a multigraph, which is used to automatically identify the changes and the effects of changes. The method has been implemented in the integrated testing and maintenance environment. The architecture and functionality of the relevant part will be presented.
The organization of this paper is as follows. Section 2 gives a brief review of related work on maintenance of conventional as well as OO software. In section 3, we discuss types of changes, and change identification. A formal model is presented to facilitate change identification and impact identification, which is described in section 4. In section 5, we describe a support system for OO testing and maintenance. In section 6, we report our experience on OO software maintenance and in section 7 we present the conclusions and future work.
\(^1\)The ripple effect refers to the phenomenon that changes made to one part of a software system ripple throughout the system.
\(^2\)We use this to loosely mean retesting the software with certain degree of confidence. We choose not to give a formal definition of adequacy in this paper.
2 Related Work
Hartmann and Robson examined several regression testing strategies, including methods for capturing the program portion which may be affected by maintenance modifications to a conventional program [hart89a]. A similar study was conducted by Leung and White [leun91a] using a formally defined cost model. Laski and Szumer described an algorithm for identifying the affected parts in conventional program maintenance [lask92a]. The algorithm is based on differentials between the control flow graphs for the original program and the modified program. In [leun90a] impact of data and function changes is addressed using a dynamic approach.
Some conventional program maintenance systems have been reported in the literature. The $R^n$ environment [hood84a] and the VIFOR (Visual Interactive FORtran) [raj90a] were developed for FORTRAN programs, the MasterScope [teit81a] for Interlisp, and the CIA (C Information Abstractors) [chen90a] for C. These systems provide editing, browsing, and database supports to a maintainer. In particular, the VIFOR system also provides graphical display and transformations between the textual representation and the graphical representation.
Wilde and Huit [wild92a] analyzed problems of dynamic binding, object dependencies, dispersed program structure, control of polymorphism, high level understanding and detailed code understanding. The authors then provided a general list of recommendations, including the use of dependency analysis [wild89a] and clustering methods [choi90a] [lius90a] [schw89a] [selb88a], for possible tool support.
Crocker and Mayrauser addressed problems relating to class hierarchy changes, class signature changes, and polymorphism [croc93a]. The authors then proposed a list of tools to help solve some of the problems. The tools provide information collection, storage, analysis, inference, and display capabilities.
An early system for maintaining C++ programs was reported by Samehncerg in [same90a]. The system utilizes the inheritance relation and containment relations (e.g., a class is contained in a file, or a method belongs to a class, etc.) to provide text based browsing facilities to an OO software maintainer.
The C++ Information Abstractors [gras90a] use program analyzers to extract cross reference information and store the information in a database. A maintainer can query the data base to obtain the desired knowledge to maintain a C++ program.
Lejteker, Meyers and Reiss discussed the difficulty of maintaining an OO software system due to the presence of inheritance and dynamic binding [lejt92a]. The authors then described the XREF/XREFDB prototype system that provides text editing and relational data base querying support to facilitate OO software maintenance. A similar system is described in [obri87a].
Our system is similar in many aspects to the above systems. It uses program analyzers to collect information and stores the information in a data base. It provides both graphical and textual display and browsing, whereas most of the existing systems provide only textual display and browsing (with VIFOR as an exception). It is capable of automatically identifying the changes to an OO program and deriving the affected parts from the changes. Another difference is that our system is integrated with testing capabilities to facilitate regression test case and test data reuse and generation, result analysis, and report generation.
3 Change Identification
One of the major difficulties in software maintenance is to identify changes and their impact automatically since it is very difficult to keep track of the changes when a software system is modified extensively by several persons. This capability becomes even more crucial when the modifications are performed by one group of persons and regression testing is performed by another group of persons.
In this section, we first discuss the different types of code changes in section 3.1. We then present, in section 3.2, a formal model for capturing such changes Finally, we describe in the remaining sections how to identify the various types of code changes.
3.1 Types Of Code Changes
Figure 1 provides a classification of code changes in an OO class library. These change types are explained as follows:
- **Data change.** Any datum (i.e., a global variable, a local variable, or a class data member) can be changed by updating its definition, declaration, access scope, access mode and initialization. In addition, adding new data and/or deleting existing data are also considered as data changes.
- **Method change.** A member function can be changed in various ways. Here we classify them into three types: component changes, interface changes, and control structure changes.
Component changes include: 1) adding, deleting, or changing a predicate, 2) adding, deleting a local data variable, and 3) changing a sequential segment.
Structure changes include: 1) adding, deleting, or modifying a branch or a loop structure, and 2) adding, or deleting a sequential segment.
The interface of a member function consists of its signature, access scope and mode, its interactions with other member functions (for example, a function call). Any change on the interface is called an interface change of a member function.
- **Class change.** Direct modifications of a class can be classified into three types: component changes, interface changes and relation changes. Any change on a defined/redefined member function or a defined data attribute is known as a component change. A change is said to be an interface change if it adds, or deletes a defined/redefined attribute, or changes its access mode or scope. A change is said to be a relation change if it adds, or deletes an inheritance, aggregation or association relationship between the class and another class.
- **Class library change.** These include: 1) changing the defined members of a class, 2) adding, or deleting a class and its relationships with other classes, 3) adding, or deleting a relationship between two existing classes\(^3\), 4) adding, or deleting an independent class.
\(^3\)Changing a relationship R1 (between two classes) into a relationship R2 is considered as deleting R1 and adding R2.
<table>
<thead>
<tr>
<th>Components</th>
<th>Changes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>2</td>
</tr>
<tr>
<td></td>
<td>3</td>
</tr>
<tr>
<td>Method</td>
<td>interface changes</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>structure changes</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>component change</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Class</td>
<td>component change</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>relationship change</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Class</td>
<td>component change</td>
</tr>
<tr>
<td>Library</td>
<td>relationship change</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Figure 1: Different Types Of Code Changes
3.2 A Formal Model
Our formal model was originally developed for capturing and representing the complex relationships and interdependencies between the various parts of a C++ program. The model consists of three types of diagrams, i.e., Object Relation Diagrams (ORD), Block Branch Diagrams (BBD), and Object State Diagrams (OSD). An ORD facilitates the understanding of the inheritance, aggregation, and association relationships\(^4\) between the classes. These relationships are extracted from code and displayed graphically. Figure 2 shows a screen dump of an ORD for a subset of the InterViews library. We postpone the formal definition of ORD and explanation of the screen dump til section 3.6.
A BBD facilitates the understanding of the member functions and their relationships to the global data, class data, and other member functions. Figure 3 shows a BBD for a member function of the InterViews library. The various components of a BBD is explained as follows:
- the large window displays the BBD body, denoted B; it encapsulates the program graph for the member function\(^5\).
- the upper left window displays the global and class data that are used by the member function; this is denoted by Du;
- the upper right window displays the input/output parameters, denoted P, of the member function;
- the bottom left window displays the global and class data that are defined (i.e., updated) by this member function; this is denoted by Dd;
- the bottom right window displays functions that are called by this member function; this is denoted by Fe;
Formally, the block branch diagram for a member function \(f\) is a quintuple
\[
BBD_f = (D_u, D_d, P, F_e, B)
\]
where the components are as defined above. When no confusion can arise, we will omit the subscript \(f\) from \(BBD_f\).
A BBD body is formally defined by a directed graph \(B = (V, E)\), where \(V\) denotes the set of program graph vertices and \(E \subset V \times V\) the directed edges representing the control flows. As usual, \(B\) satisfies the following conditions: 1) there is exactly one starting vertex (which has indegree zero) and one final vertex (which has outdegree zero); 2) all the other vertices have indegree one and outdegree either one or two; 3) except the starting and final vertices, each vertex also satisfies the following conditions: a) if it has outdegree one, then it represents either a function call or a sequence of simple statements; b) if it has outdegree two, then it represents a decision vertex for a simple condition; 3) every vertex of \(B\) occurs on some path from the starting vertex to the final vertex. For more details the reader is referred to \([\text{kung93b}]\).
\(^4\)The meanings of these relationships are similar to those used in OO modeling, but there are subtle differences, as we have addressed in \([\text{kung94a}]\).
\(^5\)The program graph can be used, among others, to generate basis path test cases and test data \([\text{beiz90a}]\). However, it is beyond the scope of this paper to explore this issue.
Figure 2: An ORD for a part of the InterViews Library
Figure 3: A BBD for a member function in the InterViews Library
The OSD is not closely related to the work in this paper; and hence, it is omitted. The interested reader is referred to [kung93b] [kung94b] [kung94c].
3.3 Data Change Identification
Data change identification is easy since the needed information is captured by the BBD’s (and the internal representation) for the member functions\(^6\). In particular, information about each data item’s access scope, type, access mode, update set (i.e., functions that define the data item), and use set (i.e., functions that use the data item). To identify data change, this information is compared with the information for the original software. If any of the above information is different, the corresponding type of change is identified.
3.4 Method Change Identification
We will use method and member function interchangeably. Let BBD = \((D_u, D_d, P, F_c, B)\), and BBD’ = \((D_u’, D_d’, P’, F_c’, B’)\) be the BBDs for a member function C::f(...) and its modified version C::f’(...) respectively. Recall that \(B = (V, E)\) (or \(B’ = (V’, E’))\) is a directed graph which represents the control structure of C::f(...) (or C::f’(...)). Method structure and/or component changes are identified as follows:
1. if \((V – V’) \neq \emptyset\) then any \(v \in (V – V’)\) is a deleted block node.
2. if \((V’ – V) \neq \emptyset\) then any \(v \in (V’ – V)\) is an added block node.
3. if \((E – E’) \neq \emptyset\) then any \(e \in (E – E’)\) is a deleted control edge.
4. if \((E’ – E) \neq \emptyset\) then any \(e \in (E’ – E)\) is an added control edge.
A member function interface change is identified as follows:
1. if \((D_u – D_u’) \neq \emptyset\), then some data uses are removed.
2. if \((D_u’ – D_u) \neq \emptyset\), then some data uses are added.
3. if \((D_d – D_d’) \neq \emptyset\), then some data definitions are removed.
4. if \((D_d’ – D_d) \neq \emptyset\), then some data definitions are added.
5. if \((F_c – F_c’) \neq \emptyset\), then some function calls are removed\(^7\).
6. if \((F_c’ – F_c) \neq \emptyset\), then some function calls are added.
\(^6\)Functions not belong to any class are treated as member functions of a dummy system class in our approach.
\(^7\)Signature change is treated as deleting and then adding a function.
3.5 Class Change Identification
A class is a pair $C = (D_{def}, F_{def})$, where $D_{def}$ is a set of defined/redefined data attributes, $F_{def}$ is a set of defined/redefined member functions.
Let $C' = (D'_{def}, F'_{def})$ be a modified version of a class $C$. Then class code change is identified as follows:
- if $(D_{def} - D'_{def}) \neq \emptyset$, then any $d \in (D_{def} - D'_{def})$ is a deleted data attribute.
- if $(D'_{def} - D_{def}) \neq \emptyset$, then any $d \in (D'_{def} - D_{def})$ is an added data attribute.
- if any $d \in D'_{def} \cap D_{def}$ is changed, then a residual data attribute is changed.
- if $(F_{def} - F'_{def}) \neq \emptyset$, then any $f$ in $(F_{def} - F'_{def})$ is a deleted member function.
- if $(F'_{def} - F_{def}) \neq \emptyset$, then any $f$ in $(F'_{def} - F_{def})$ is an added member function.
- if any $f \in F'_{def} \cap F_{def}$ is changed, then a residual defined/redefined member function is changed.
3.6 Class Library Change Identification
A class library $L$ is a collection of ORDs. An ORD is an edge labeled directed graph $ORD = (V, L, E)$, where $V$ is the set of nodes representing the object classes, $L = \{I, Ag, As\}$ is the set of edge labels (for inheritance, aggregation, and association), and $E = E_I \cup E_{AG} \cup E_{AS}$ is the set of edges. For a detailed definition and how to reverse code to yield an ORD, the reader is referred to [kung93b]. As mentioned earlier, Figure 2 shows the screen dump of an ORD for part of the InterViews library. In the figure, the inheritance and aggregation relationships are shown using Rumbaugh et al’s notation, while association is shown using directed arcs. The figure says that Canvas is associated with CanvasRep, and hence dependent on CanvasRep. ControlState and Scene are parts of Canvas, and hence Canvas is dependent on ControlState and Scene. The figure also shows that World is a derived class of Canvas, and hence, dependent on Canvas.
Figure 2 also shows a window containing the header file information for the Scene class. This information is obtained by clicking on the rectangle labeled by “Scene”. From the header file information, a maintainer can request the system to display the details of a member by clicking on that member. But this latter capability is not shown in Figure 2.
Modifications to a library can be classified into three basic cases, i.e., adding an ORD, deleting an ORD, and changing an ORD\(^8\). In the first two cases, there is no impact to the other ORD’s, therefore, we will consider only the last case. An ORD can be changed in several ways: changing the defined members of a class, adding/deleting a relation between two existing classes, and adding/deleting a class and its relations. Change identification for a single class has been discussed in the previous subsection. Here, we focus on structure change of a class library.
Let $ORD = (V, L, E)$ and $ORD' = (V', L', E')$ be the ORD’s for two versions of the same software. A structure change in an ORD is identified as follows:
- if $(V' - V) \neq \emptyset$ then any $v \in (V' - V)$ is an added class node.
---
\(^8\)Note an isolated class is an ORD.
Figure 4: Different Structural Changes In An ORD
- if \((V - V') \neq \emptyset\) then any \(v \in (V - V')\) is a deleted node.
- if \((E' - E) \neq \emptyset\) then any \(e \in (E' - E)\) is an added new edge.
- if \((E - E') \neq \emptyset\) then any \(e \in (E - E')\) is a deleted edge.
- if any \(v\) in \(V \cap V'\) is changed, then a residual class is changed.
To facilitate understanding, Figure 4 shows the different types of structure changes for an ORD. Figures 4(a) and (b) show the two cases in which a new class node is added into the original ORD by inserting a new relation with an residual class. Two cases of a class deletion are given in Figures 4(c) and (d). Notice that if a class node is removed from an ORD, then all relation edges between the class node and other classes must be deleted. In Figure 4(e), an existing relation edge is removed from two residual classes. In Figure 4(f), a new relation edge between two residual classes is added.
\(^9\text{An independent single class in a class library is considered as an ORD. Thus, adding (or deleting) an independent single class adds (or deletes) an ORD.}\)
4 Change Impact Identification
After change identification, it is very important to detect the ripple effects of the changes. Because these changes may affect a software in different aspects, including functions, structures, behaviors and performance. Clearly understanding these effects not only reduce the cost of software maintenance, but also save the regression test effort. For example, if we can find all the affected components in the give software, the testers only need to retest these components instead of all of the components in the software. Thus, it is very important to identify and enclose all the affected components after changing a software.
Change impact identification includes data change impact identification, method change impact identification, class change impact identification, and class library change (i.e., class relation change) impact identification. Existing results, e.g., [leun90a], can be used to identify data and method change impacts. Class change impact has been addressed in [kung94a]. Therefore, we focus on class library change impact identification in this paper.
4.1 Class Library Change Impact Identification
The major task of class library change impact identification is to find all the affected classes due to changes of interclass relationships. We use a class firewall concept introduced in [kung94] to enclose all affected classes. The computation of a class firewall is based on the ORDs for the class library.
As shown in Figure 4, there are six types of structure changes in an ORD. Taking into consideration the differences in treating the inheritance, aggregation and association relationships, the impact on a residual class is identified as follows:
(a) Adding a new “superclass”:
i. If the new edge is an inheritance edge, then it expands A’s members. According to Weyuko’s antidecomposition axiom\(^{10}\), we should retest these new inherited members in the context of class A [pbry70]. In addition, integration testing of class A’s new inherited members and its other members is needed to make sure that they work well together.
ii. If the edge is an inheritance or aggregation edge, then it expands A’s state space in terms of state behavior (see Figure 4.1a). That is, its states and transitions are extended by its inherited members from class B. According to Weyukos’s anticomposition axiom\(^{11}\), we should retest the state behaviors of class A.
iii. If the edge is an association edge, then at least one method of class A must be changed, and hence, A is affected in this sense.
(b) Adding a new dependent class.
Class A is not affected and hence does not need to be retested.
(c) Deleting a “superclass”.\(^{10}\)
\(^{10}\) There exists a program P and component Q such that T is adequate for P, T' is the set of vectors of values that variables can assume on entrance to Q for some t of T, and T' is not adequate for Q. [weyu88a]
\(^{11}\) There exist programs P and Q, and test set T, such that T is adequate for P, and the set of vectors of values that variables can assume on entrance to Q for inputs in T is adequate for Q, but T is not adequate for P; Q[P;Q is the composition of P and Q. [weyu88a]
This changes class A by removing class B from class A’s superclass or component class list:
i. If the edge is an inheritance edge, then it reduces the inherited members. This only affects class A’s test cases which related to those removed members.
ii. If the edge is an inheritance or aggregation edge, then it reduces the states and transitions of class A (see Figure 4.1b). According to Weyko’s antidecomposition axiom, we should retest the state behaviors of the modified class A.
iii. If the edge is an association edge, then at least one method of class A must be changed, and hence, A is affected in this sense.
(d) Deleting a dependent class.
Class A is not affected.
(e) Deleting a relationship between existing classes.
This is similar to (c) above.
(f) Adding a relationship between existing classes.
This is similar to (a) above.
We have discussed the different types of structure changes of an OO library. We showed some of the changes affect a residual class A even though its defined attributes are not changed at all. Thus, class A should be retested. A residual class like class A is called an addition affected class if it is directly affected by any edge addition (or class addition) in an ORG (cases (a) and (f) above). Similarly, a residual class is called a deletion affected class if it is directly affected by any edge deletion (or class deletion) in an ORG (cases (c) and (e) above).
4.2 Class Firewall Generation
The basic idea of computing a class firewall is described in [kung94]. A binary relation R, derived from an ORG = (V, L, E), is introduced to compute the class firewall.
\[ R = \{ < C_j, C_i > | C_i, C_j \in V \land < C_i, C_j, l > \in E \} \]
where R is the dependence relation which defines the dependence between classes, according to the inheritance, aggregation, and association relations.
In [kung94], we have proved that for an ORG, if the modification a class library changes a class C without altering the structure of the ORG, then a class firewall for C, denoted \( \text{CCFW}(C) \), can be computed as follows:
\[ \text{CCFW}(C) = \{ C_j | < C, C_j > \in R^* \} \]
where \( R^* \) is the transitive closure of R. That is, if \( < C_i, C_j > \in R \) and \( < C_j, C_k > \in R^* \), then \( < C_i, C_k > \in R^* \). The transitive closure of R can be computed by the famous Warshall algorithm [aho83].
Let \( L \) be a class library, and \( L' \) its modified version. Assume that ORD = \( (V, L, E) \) be an ORG in \( L \), and ORD' = \( (V', L', E') \) its modified version. We define a binary relation \( R_r \) as
\[ R_r = R \cap (V \times V) \cap (V' \times V') \]
where \( \times \) is the Cartesian product operation. In other words, \( R_r \) is the relation which defines the dependencies between the residual classes.
The class firewalls are generated as follows:
- The class firewall for a changed class C is computed as follows:
\[ \text{CCFW}(C) = \{ C_j | < C, C_j > \in R^*_r \} \]
- The class firewall for addition affected classes is computed as follows:
\[ \text{CCFW} = \{ C_j | (\exists C) (\exists k) ((< C_j, C, k > \in E' - E) \land < C, C_j > \in R^*_r) \} \]
where \( R' \) is the dependence relation for the modified ORD.
- The class firewall for deletion affected classes is computed as follows:
\[ \text{CCFW} = \{ C_j | (\exists C) (\exists k) ((< C_j, C, k > \in E - E') \land < C, C_j > \in R^*_r) \} \]
5 Support System
The objective of a software maintenance system is to help a software maintainer in: understanding a given software, identifying code changes, supporting software updates and enhancement, detecting change effects. Therefore, any software maintenance system has to fulfill four important requirements: 1) it has to be able to provide the various information about the software, including its structures, and the interfaces and relationships between different components at the different levels; 2) it has to provide an efficient and user-friendly interface to present the various information about software and support maintenance activities; 3) it has to be able to identify code changes between different software versions and their effects.
Figure 5: The Architecture Of OOTME
Figure 5 depicts the architecture of an OO testing and maintenance environment we are currently developing.
The components of the environment are described as follows:
- **GUI**: The GUI is constructed based on Motif and X window software, it is user-friendly and easy to use.
- **Parser**: There are three different parsers: the ORD parser, the BBD parser, and the OSD parser. The user can use them to extract information from a class library.
- **Displayer**: There are three Displayers: the ORD Displayer, the BBD Displayer, and the OSD Displayer. The user can use them to display the ORDs, BBDs, and OSD’s, respectively.
- **Change identifier**: The change identifier can be used to find the code changes between two different versions of the same class library. It can also be used to automatically identify the impact of a planned code change to help a maintainer to determine whether the change shall be carried out.
- **Firewall generator**: The firewall generator can be used to identify a class firewall to enclose all the possible affected classes in a class library when it is modified.
- **Regression test tool**: The regression test tool consists of: test strategy generator, test case generator. The test strategy generator produces a cost-effective test order for each class in the library [kung94]. This test order will be used as a re-test sequence in class unit testing, and re-integration testing. The test case generator is used to generate new test cases.
We have applied this tool to many applications, including the Interviews library. Figure 6 shows an example listing of the firewall information for a subset of the InterViews library. We have also compared the two versions (3.0 and 3.1) of the Interviews library using the OOTME. It lists all of the differences between these two versions, including 68 added classes, 76 deleted classes, and
Figure 6: Change impact identification
46 residual classes (reused classes). In addition, it also identified 26 changed residual classes, 16 affected classes and 4 unaffected classes. The detailed result is given in tables 1 – 3.
<table>
<thead>
<tr>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
</tr>
</thead>
<tbody>
<tr>
<td>ActiveHandler</td>
<td>Adjustable</td>
<td>AllocationInfo</td>
<td>AllocationTable</td>
<td>AllocationTableImpl</td>
</tr>
<tr>
<td>BoxImpl</td>
<td>CoordinateSpace</td>
<td>DebugGlyph</td>
<td>Dialog</td>
<td>DialogHandler</td>
</tr>
<tr>
<td>DialogKitImpl</td>
<td>Drag</td>
<td>DragZone</td>
<td>DragZoneSink</td>
<td>FieldButton</td>
</tr>
<tr>
<td>FieldEditorImpl</td>
<td>FieldStringEditor</td>
<td>FileBrowserImpl</td>
<td>FileChooserImpl</td>
<td>FontBoundingBox</td>
</tr>
<tr>
<td>GLContext</td>
<td>Input Handler</td>
<td>InputHandlerImpl</td>
<td>LayoutKit</td>
<td>LayoutKitImpl</td>
</tr>
<tr>
<td>LayoutLayer</td>
<td>MFDialogKitImpl</td>
<td>MFKitForeground</td>
<td>MFKitFrame</td>
<td>MFKitImpl</td>
</tr>
<tr>
<td>MKKitInfo</td>
<td>MKFKitMenuItem</td>
<td>MKItem</td>
<td>MKItem</td>
<td>MKItem</td>
</tr>
<tr>
<td>OL_Anchor</td>
<td>OL_Button</td>
<td>OL_Cable</td>
<td>OL_Channel</td>
<td>OL_CheckBox</td>
</tr>
<tr>
<td>OL_CheckMark</td>
<td>OL_DragBox</td>
<td>OL_Elevator</td>
<td>OL_ElevatorGlyph</td>
<td>OL_FieldEditor</td>
</tr>
<tr>
<td>OL_Frame</td>
<td>OL_Gauge</td>
<td>OL_Indicator</td>
<td>OL_MenuMark</td>
<td>OL_Mover</td>
</tr>
<tr>
<td>OL_Pushpin</td>
<td>OL_PushpinLook</td>
<td>OL_Scrollbar</td>
<td>OL_Setting</td>
<td>OL_Slider</td>
</tr>
<tr>
<td>OL_Specs</td>
<td>OL_Stepper</td>
<td>OL_Tick</td>
<td>OL_ToLimit</td>
<td>Observable</td>
</tr>
<tr>
<td>Observer</td>
<td>WidgetKitImpl</td>
<td>WidgetKitOverlay</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Table 1: New added classes in InterViews3.1
<table>
<thead>
<tr>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
</tr>
</thead>
<tbody>
<tr>
<td>ApplicationWindow</td>
<td>BMargin</td>
<td>BoxAllocation</td>
<td>BoxComponent</td>
<td>BreakSet</td>
</tr>
<tr>
<td>Center</td>
<td>DeckInfo</td>
<td>FixedSpan</td>
<td>HCenter</td>
<td>HGlue</td>
</tr>
<tr>
<td>HMargin</td>
<td>HRule</td>
<td>Hit Target</td>
<td>HitTargetList</td>
<td>IconWindow</td>
</tr>
<tr>
<td>LMargin</td>
<td>LRBox</td>
<td>Listener</td>
<td>ManagedWindow</td>
<td>Margin</td>
</tr>
<tr>
<td>OptionDesc</td>
<td>Overlay</td>
<td>PSFont</td>
<td>PFontImpl</td>
<td>Page</td>
</tr>
<tr>
<td>FagelInfo</td>
<td>Patch</td>
<td>Pattern</td>
<td>PointerHandler</td>
<td>PopupWindow</td>
</tr>
<tr>
<td>PossibleHitTarget</td>
<td>Printer</td>
<td>PrinterInfo</td>
<td>PrinterRep</td>
<td>PropertyData</td>
</tr>
<tr>
<td>RMargin</td>
<td>Raster</td>
<td>Regexp</td>
<td>ReqErr</td>
<td>Resource</td>
</tr>
<tr>
<td>ResoncElmImpl</td>
<td>Rule</td>
<td>Sensor</td>
<td>Session</td>
<td>SessionIOHandler</td>
</tr>
<tr>
<td>SessionRep</td>
<td>Shadow</td>
<td>SimpleComposer</td>
<td>Stencil</td>
<td>Style</td>
</tr>
<tr>
<td>StyleAttribute</td>
<td>StyleRep</td>
<td>StyleWildcard</td>
<td>StyleWildcardInfo</td>
<td>StyleWildcardMatchQuality</td>
</tr>
<tr>
<td>Superpose</td>
<td>TBBbox</td>
<td>TIFFRaster</td>
<td>TIFFRasterImpl</td>
<td>TMargin</td>
</tr>
<tr>
<td>Target</td>
<td>ToXCompositor</td>
<td>Tile</td>
<td>TileReversed</td>
<td>TopLevelWindow</td>
</tr>
<tr>
<td>TransformSetter</td>
<td>Transformer</td>
<td>TransientWindow</td>
<td>VCenter</td>
<td>VGlue</td>
</tr>
<tr>
<td>VMargin</td>
<td>VRule</td>
<td>ValueString</td>
<td>Window</td>
<td>World</td>
</tr>
<tr>
<td>XYMarker</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Table 2: Deleted classes from InterViews3.0
<table>
<thead>
<tr>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
<th>class name</th>
</tr>
</thead>
<tbody>
<tr>
<td>(C)Aggregate</td>
<td>(C)Allocation</td>
<td>(C)Background</td>
<td>(C)Bitmap</td>
<td>(C)Border</td>
</tr>
<tr>
<td>(C)Box</td>
<td>(C)Break</td>
<td>(C)Brush</td>
<td>(C)Canvas</td>
<td>(C)Color</td>
</tr>
<tr>
<td>(C)Composition</td>
<td>(C)Deck</td>
<td>(C)Display</td>
<td>(C)Event</td>
<td>(C)Extension</td>
</tr>
<tr>
<td>(C)Font</td>
<td>(C)FontFamily</td>
<td>(C)Glyph</td>
<td>(C)Handler</td>
<td>(C)Hit</td>
</tr>
<tr>
<td>(C)HitImpl</td>
<td>(C)Image</td>
<td>(C)LRComposition</td>
<td>(C)Monoglyph</td>
<td>(C)Requisition</td>
</tr>
<tr>
<td>(C)TBComposition</td>
<td>(A)AggregateInfo</td>
<td>(A)Align</td>
<td>(A)Character</td>
<td>(A)CompositionComponent</td>
</tr>
<tr>
<td>(A)Control</td>
<td>(A)Discretionary</td>
<td>(A)Glue</td>
<td>(A)Group</td>
<td>(A)HStur</td>
</tr>
<tr>
<td>(A)LRRMarker</td>
<td>(A)Label</td>
<td>(A)Layout</td>
<td>(A)ShapeOf</td>
<td>(A)Space</td>
</tr>
<tr>
<td>(A)Strut</td>
<td>(A)YStrut</td>
<td>(U)Allocation</td>
<td>(U)ArrayCompositor</td>
<td>(U)Compositor</td>
</tr>
<tr>
<td>(U)Requirement</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Table 3: Reused classes in InterView3.1
17
6 Experience
Aids in understanding an OO software system, anticipating and identifying the effect of change, and facilitating regression testing are desirable capabilities of an OO software maintenance environment.
Our experience indicates that it is extremely time consuming and tedious to test and maintain an OO software system. This problem becomes even acute when documentation is either missing or inadequate. Consider for example the InterViews library originally developed by Stanford University. An early version of the library consisted of 146 files, more than 140 classes, more than 400 relationships, and more than 1,000 member functions. We felt difficult to obtain a high level understanding of the classes, member functions, and their relationships. Our initial experiment showed that it takes in average two hours for a C++ programmer to understand a small member function (ranging from a few lines to less than 20 lines) that invokes other member functions. Without tool support, it is almost impossible to anticipate and identify the effect of change because a class can be instantiated by another class which can then use the capabilities of the former. To ensure quality of our products, we often had to retest the entire library when major changes were made.
Software engineers in the industry consider the system useful for testing, maintenance, and reengineering. The application of the system to the InterViews library, an elevator library, and a PBX program shows that it facilitates understanding, test ordering [kung94a], test case generation (for which automatic support will be available in the future), and effort estimation (in terms of extended cyclomatic complexity and COCOMO model [boeh84a]).
The application of the automatic change and change effect identification capabilities to the InterViews library has produced promising results. However, our experience is too limited to draw any conclusions. We anticipate that these capabilities will be particularly useful in the maintenance phase. Without tool support, one has to document what have been changed and identify the impact of the changes according to one’s knowledge of the system. This is both time consuming and inaccurate. The tool will reduce costs and improve productivity in documentation and regression testing by automatically identifying the changes and their impact.
Although the system is still in its prototyping stage, several companies have expressed interests in experimenting with the system and we are porting it to more companies. Since we did not emphasize portability during prototyping, porting to other platform and operating system is not easy.
7 Conclusion and Future Work
We have described the various types of code changes of an OO system and a formal model for capturing and inferencing on the changes to identify affected components.
The model and the inference capabilities have been implemented in a tool prototype. Experience with an earlier version of the tool shows promising results.
As reported elsewhere [kung94a], the changed and affected classes can be tested in a cost-effective order to avoid extensive construction of test stubs.
Identification of changes and their impact is only one aspect of software maintenance. We are currently extending the capabilities to include various metrics, such as complexity, object-orientedness, and effort, to facilitate the maintenance work. The system is being expanded with these new fea-
tures and integrated with a test environment to provide retesting support.
8 Acknowledgment
The material presented in this paper is based on work supported by the Texas Advanced Technology Program (Grant No. 003656-097), Fujitsu Network Transmission Systems, Inc., Hewlett-Packard Company, and the Software Engineering Center for Telecommunications at UTA.
9 References
Specification-Based Approach,” submitted for publication.
|
{"Source-Url": "http://www.engr.sjsu.edu:80/gaojerry/course/287/Change-Impact.pdf", "len_cl100k_base": 10270, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 115625, "total-output-tokens": 12409, "length": "2e13", "weborganizer": {"__label__adult": 0.00026917457580566406, "__label__art_design": 0.00025963783264160156, "__label__crime_law": 0.00024509429931640625, "__label__education_jobs": 0.0006928443908691406, "__label__entertainment": 3.784894943237305e-05, "__label__fashion_beauty": 0.00011259317398071288, "__label__finance_business": 0.00013709068298339844, "__label__food_dining": 0.00021982192993164065, "__label__games": 0.0004014968872070313, "__label__hardware": 0.0005269050598144531, "__label__health": 0.0002675056457519531, "__label__history": 0.00013136863708496094, "__label__home_hobbies": 6.41942024230957e-05, "__label__industrial": 0.00019538402557373047, "__label__literature": 0.00015974044799804688, "__label__politics": 0.00012046098709106444, "__label__religion": 0.00028586387634277344, "__label__science_tech": 0.0036773681640625, "__label__social_life": 6.002187728881836e-05, "__label__software": 0.00502777099609375, "__label__software_dev": 0.986328125, "__label__sports_fitness": 0.00020062923431396484, "__label__transportation": 0.00027680397033691406, "__label__travel": 0.00013566017150878906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47211, 0.02726]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47211, 0.62338]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47211, 0.8757]], "google_gemma-3-12b-it_contains_pii": [[0, 2126, false], [2126, 6172, null], [6172, 9620, null], [9620, 12423, null], [12423, 14401, null], [14401, 17449, null], [17449, 17503, null], [17503, 17567, null], [17567, 19826, null], [19826, 23016, null], [23016, 24155, null], [24155, 27359, null], [27359, 28775, null], [28775, 31535, null], [31535, 33445, null], [33445, 33484, null], [33484, 38209, null], [38209, 41681, null], [41681, 44159, null], [44159, 47211, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2126, true], [2126, 6172, null], [6172, 9620, null], [9620, 12423, null], [12423, 14401, null], [14401, 17449, null], [17449, 17503, null], [17503, 17567, null], [17567, 19826, null], [19826, 23016, null], [23016, 24155, null], [24155, 27359, null], [27359, 28775, null], [28775, 31535, null], [31535, 33445, null], [33445, 33484, null], [33484, 38209, null], [38209, 41681, null], [41681, 44159, null], [44159, 47211, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47211, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47211, null]], "pdf_page_numbers": [[0, 2126, 1], [2126, 6172, 2], [6172, 9620, 3], [9620, 12423, 4], [12423, 14401, 5], [14401, 17449, 6], [17449, 17503, 7], [17503, 17567, 8], [17567, 19826, 9], [19826, 23016, 10], [23016, 24155, 11], [24155, 27359, 12], [27359, 28775, 13], [28775, 31535, 14], [31535, 33445, 15], [33445, 33484, 16], [33484, 38209, 17], [38209, 41681, 18], [41681, 44159, 19], [44159, 47211, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47211, 0.2526]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
6f43214ec17b697c29708fe88c2cd13a99b8e573
|
[REMOVED]
|
{"Source-Url": "https://iris.unito.it/retrieve/handle/2318/1522392/42139/2015_ff_pool_ijpp.pdf", "len_cl100k_base": 11414, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 62098, "total-output-tokens": 13988, "length": "2e13", "weborganizer": {"__label__adult": 0.0003962516784667969, "__label__art_design": 0.00041794776916503906, "__label__crime_law": 0.0003707408905029297, "__label__education_jobs": 0.0005764961242675781, "__label__entertainment": 0.00010019540786743164, "__label__fashion_beauty": 0.0001832246780395508, "__label__finance_business": 0.00026345252990722656, "__label__food_dining": 0.0003800392150878906, "__label__games": 0.0007696151733398438, "__label__hardware": 0.001415252685546875, "__label__health": 0.0005307197570800781, "__label__history": 0.0004148483276367187, "__label__home_hobbies": 0.00011903047561645508, "__label__industrial": 0.0005717277526855469, "__label__literature": 0.0003323554992675781, "__label__politics": 0.000347137451171875, "__label__religion": 0.0007023811340332031, "__label__science_tech": 0.06939697265625, "__label__social_life": 0.0001016855239868164, "__label__software": 0.007213592529296875, "__label__software_dev": 0.9140625, "__label__sports_fitness": 0.0003893375396728515, "__label__transportation": 0.0008459091186523438, "__label__travel": 0.00025963783264160156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59375, 0.02614]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59375, 0.48944]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59375, 0.86435]], "google_gemma-3-12b-it_contains_pii": [[0, 688, false], [688, 1974, null], [1974, 5362, null], [5362, 8355, null], [8355, 13251, null], [13251, 15430, null], [15430, 18235, null], [18235, 22829, null], [22829, 25490, null], [25490, 28291, null], [28291, 31229, null], [31229, 31455, null], [31455, 33911, null], [33911, 36717, null], [36717, 38768, null], [38768, 40645, null], [40645, 42905, null], [42905, 46137, null], [46137, 48493, null], [48493, 49867, null], [49867, 52587, null], [52587, 55431, null], [55431, 59375, null]], "google_gemma-3-12b-it_is_public_document": [[0, 688, true], [688, 1974, null], [1974, 5362, null], [5362, 8355, null], [8355, 13251, null], [13251, 15430, null], [15430, 18235, null], [18235, 22829, null], [22829, 25490, null], [25490, 28291, null], [28291, 31229, null], [31229, 31455, null], [31455, 33911, null], [33911, 36717, null], [36717, 38768, null], [38768, 40645, null], [40645, 42905, null], [42905, 46137, null], [46137, 48493, null], [48493, 49867, null], [49867, 52587, null], [52587, 55431, null], [55431, 59375, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59375, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59375, null]], "pdf_page_numbers": [[0, 688, 1], [688, 1974, 2], [1974, 5362, 3], [5362, 8355, 4], [8355, 13251, 5], [13251, 15430, 6], [15430, 18235, 7], [18235, 22829, 8], [22829, 25490, 9], [25490, 28291, 10], [28291, 31229, 11], [31229, 31455, 12], [31455, 33911, 13], [33911, 36717, 14], [36717, 38768, 15], [38768, 40645, 16], [40645, 42905, 17], [42905, 46137, 18], [46137, 48493, 19], [48493, 49867, 20], [49867, 52587, 21], [52587, 55431, 22], [55431, 59375, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59375, 0.06792]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
b525dc146aaa1ff1a4c01ba59965b0e67f018cbe
|
Graph-based Signatures for Kernel Data Structures
Zhiqiang Lin†, Junghwan Rhee†, Xiangyu Zhang†, Dongyan Xu†, Xuxian Jiang‡
†Purdue University, ‡NCSU
{zlin, rhee, xyzhang, dxu}@cs.purdue.edu jiang@cs.ncsu.edu
ABSTRACT
The signature of a data structure reflects some unique properties of the data structure and therefore can be used to identify instances of the data structure in a memory image. Such signatures are important to many computer forensics applications. Existing approaches propose the use of value invariants of certain fields as data structure signatures. However, they do not fully exploit pointer fields as pointers are more dynamic in their value range. In this paper, we show that pointers and the topological properties induced by the points-to relations between data structures can be used as signatures. To demonstrate the idea, we develop SigGraph, a system that automatically extracts points-to relations from kernel data structure definitions and generates unique graph-based signatures for the data structures. These signatures are further refined by dynamic profiling to improve efficiency and robustness. Our experimental results show that the graph-based signatures achieve high accuracy in kernel data structure recognition, with zero false negative and close-to-zero false positives. We further show that SigGraph achieves strong robustness in the presence of malicious pointer manipulations.
1. INTRODUCTION
Given a kernel data structure definition, identifying instances of that data structure in a kernel memory image is a highly desirable capability in computer forensics, especially memory forensics where investigators try to recover semantic information from a memory image obtained from a suspect/victim machine [23, 10, 18, 32, 30]. Analogous to the pattern recognition problem in image processing, the problem of data structure – especially kernel data structure – instance recognition has received increasing attention. For example, the state-of-the-art solutions often rely on the field value invariance exhibited by a data structure as its signature [33, 31, 12, 8, 7]. The value of such a field is either constant or in a fixed range and the effectiveness and robustness of the value-invariant approach has been well demonstrated. However, there exist many kernel data structures that are not covered by the value-invariant approach. For example, some data structures do not have fields with invariant values or value ranges. It is also possible that an invariant-value field is corrupted (e.g., by kernel bugs or attacks), making the corresponding data structure instance un-recognizable. Furthermore, some value invariant-based signatures may not be unique enough to distinguish themselves from others. For example, a signature that demands the first field to have value 0 may generate a lot of false positives.
In this paper, we present a complementary model for kernel data structure signatures. Different from the value-invariant-based signatures, our approach, called SigGraph, uses a graph structure rooted at a data structure as the data structure’s signature. More specifically, for a data structure with pointer field(s), each pointer field – identified by its offset from the start of the data structure – points to another data structure. Transitive, such points-to relations entail a graph structure rooted at the original data structure. We observe that data structures with pointer fields widely exist in operating system (OS) kernels. For example, when compiling the whole package of Linux kernel 2.6.18-1, we found that over 40% of all data structures have pointer field(s).
Compared with the field values of a data structure, the “topology” of such a “points-to” graph (which is across data structures) is much more stable. Moreover, in an OS kernel, it is unlikely that two different data structures have exactly the same graph-based signature, which is confirmed by our experiments with a number of Linux kernels. As such, SigGraph is deemed a natural scheme to uniquely identify kernel data structures with pointers.
SigGraph has the following key features: (1) It models the topological invariants between a subject data structure and those directly or transitively reachable via points-to relations. Furthermore, SigGraph recognizes and formulates the challenge that different data structures may share isomorphic structural patterns such that false positives are induced if the invariants are not properly chosen. SigGraph proposes a theoretically sound solution identifying signatures that are guaranteed not to cause false positives in ideal scenarios (e.g. pointers are always not null) and develops a number of practical extensions to adapt the algorithm to real-world scenarios (e.g. some pointers may be null). (2) SigGraph exploits the wealth of points-to relations between kernel data structures, and is able to generate multiple signatures for the same data structure. This is particularly powerful when operating under malicious pointer mutation attacks. (3) SigGraph avoids complex, expensive points-to analysis for void pointer handling (e.g., in [9]) as it can generate distinct signatures without involving those pointers. (4) The graph-based signatures can often be described by context-free-grammars such that parsers/scanners can be automatically generated to recognize data structure instances. More specifically, to determine if address x holds an instance of data structure T, we only need to perform pattern matching starting at x using the parser for T. This avoids the construction of (and dependence on) a global memory graph starting from the global variables and stack variables of a program/OS [17, 9].
We have performed extensive evaluation on SigGraph-generated signatures with several Linux kernels and verified the uniqueness of
2. OVERVIEW
2.1 Problem Statement and Challenges
The goal of SigGraph is to use the inter-data structure topology induced by points-to relations as a data structure’s signature. Consider 7 simplified Linux kernel data structures, 4 of which are shown in Figure 1(a)-(d). In particular, task_struct (TS) contains 4 pointers to thread_info (TI), mm_struct (MS), linux_binfmt (LB), and TS, respectively. TI has a pointer to TS, and MS has two pointers: one to vm_area_struct (VA) (not shown in the figure) and the other is a function pointer. LB has one pointer to module (MD).
At runtime, if a pointer is not null, its target object should have the type of the pointer. Let $S_T(x)$ denote a boolean function that decides if the memory region starting at $x$ is an instance of type $T$ and let $*$ denote the value stored at $x$. Take task_struct as an example, we have the following rule, assuming all pointers are not null.
$$S_{TS}(x) \rightarrow S_{TI}(x) \land S_{MS}(x) \land S_{LB}(x)$$ \hspace{1cm} (1)
It means that if $S_{TS}(x)$ is true, then the four pointer fields must point to regions with the corresponding types and hence the boolean functions regarding these fields must be true. Similarly, we have the following
$$S_{TI}(x) \rightarrow S_{TS}(x+0)$$ \hspace{1cm} (2)
$$S_{MS}(x) \rightarrow S_{TS}(x+4) \land S_{LB}(x+4)$$ \hspace{1cm} (3)
$$S_{LB}(x) \rightarrow S_{TS}(x+0)$$ \hspace{1cm} (4)
for thread_info, mm_struct, and linux_binfmt, respectively. Substituting symbols in rule (1) using rules (2), (3) and (4), we further have
$$S_{TS}(x) \rightarrow S_{MS}(x+0) \land S_{MB}(x+4) \land S_{LB}(x+0) \land S_{LB}(x+8) \land S_{TS}(x+12)$$ \hspace{1cm} (5)
The rule corresponds to the graph shown in Figure 1 (e), where the nodes represent pointer fields with their shapes denoting pointer types; the edges represent the points-to relations with their weights indicating the pointers’ offsets; and the triangles represent recursive occurrences of the same pattern. It means that if the memory region starting at $x$ is an instance of task_struct, the layout of the region must follow the graph’s definition. Note that the inference of rule 5 is from left to right. However, we observe that the graph is so unique that the reverse inference tends to be true. In other words, we can use the graph as the signature of task_struct and achieve the reverse inference as follows.
$$S_{TS}(x) \leftarrow S_{TS}(x+0) \land S_{TS}(x+4) \land S_{TS}(x+8) \land S_{TS}(x+12)$$ \hspace{1cm} (6)
To realize the SigGraph signature scheme we need to address a number of challenges:
- **Capturing uniqueness of signatures.** Given a static data structure definition, we aim to construct its points-to graph as shown in the task_struct example. However, it is possible that two distinct data structures may lead to isomorphic graphs which cannot be used to distinguish instances of the two data structures. Hence our first challenge is to identify the sufficient and necessary conditions for signature uniqueness between data structures.
- **Generating signatures.** It is possible that a data structure may have multiple unique signatures, depending on how (especially, how deep) the points-to edges are traversed when generating a signature. In particular, among the valid signatures of a data structure, finding the minimal signature that has the smallest size while retaining uniqueness (relative to other data structures) is a combinatorial optimization problem. Finally, it is desirable to automatically generate a parser for each signature that will perform the corresponding data structure instance recognition on a memory image.
- **Improving recognition accuracy.** Although statically a data structure may have a unique signature graph, at runtime, pointers may be null whereas non-pointer fields may have pointer-like values. As a result the data structure instances in a memory image may not fully match the signature. We need to handle such issues to improve recognition accuracy.
2.2 System Overview
The overview of the SigGraph system is shown in Figure 2. It consists of four key components: (1) data structure definition extractor, (2) dynamic profiler, (3) signature generator, and (4) parser generator. The starting point of our system is to extract data structure definitions of the target OS. In this paper, we use the source code of Linux kernels as subject programs. SigGraph extracts all kernel data structure definitions automatically through a compiler pass. Since our signatures rely on pointer fields whose values may be null or some special values, the dynamic profiler identifies such problematic pointer fields and handle them accordingly. The signature generator is responsible for checking if unique signatures exist for a data structure. If so, the generator will generate them. The generated signatures are passed to the parser generator component that can automatically generate parsers for individual data structures from their signatures.
3. DATA STRUCTURE DEFINITION EXTRACTION
A naive method to extract data structure definitions is to directly process source code. This method is error-prone because definitions may be present in multiple source files; they may have various scopes (i.e., the declaration contexts) and type aliases can be introduced by typedef. SigGraph’s data structure definition extractor adopts a compiler-based approach, where the compiler is instrumented to walk through the source code and extract data structure definitions. It is robust as it is based on a full-fledged language frontend. In particular, we introduce a compiler pass in gcc-4.2.4. The pass takes abstract syntax trees (ASTs) as input as they retain substantial symbolic information [1]. The compiler-based approach also allows us to handle data structure in-lining, which occurs when a data structure has a field that is of the type of another structure; after compilation, the fields in the inner structure become fields in the outer structure. Furthermore, we can easily see through type aliases introduced by typedef via ASTs.
The net outcome of the compiler pass is the data structure definitions extracted in a canonical form. The pass is inserted into the compilation workflow right after data structure layout is finished (in stor-layout.c). During the pass, the AST of each data structure is traversed. If the data structure type is struct or union, its field type, offset, and size information is dumped to a file. To precisely reflect the field layout after in-lining, we flatten the nested definitions and adjust offsets.
We note that source code availability is not a fundamental requirement of SigGraph. For a close-source OS (e.g., Windows), if debug information is provided with the binary, SigGraph can simply use the debug information.
4. SIGNATURE GENERATION
Assume a data structure T has n pointer fields with offsets f1, f2, ..., fn and types t1, t2, ..., tn. A predicate St(x) determines if the region starts at address x is an instance of t. The following production rule can be generated for T.
\[
S_T(x) \rightarrow S_{t_1}(\ast(x + f_1)) \land S_{t_2}(\ast(x + f_2)) \land \ldots \land S_{t_n}(\ast(x + f_n))
\]
(7)
The problem of data structure signature generation is along the reverse direction of the above rule. Given a memory snapshot, we hope to identify instances of a data structure by trying to match the right-hand side of the rule (as a signature) with memory content starting at a certain location. Although it is generally difficult to infer the types of memory at individual locations based on the memory content, it is more feasible to infer if a memory location contains a pointer and hence to identify the layout of pointers with high confidence. This can be done recursively by following the pointers to the destination data structures. As such, the core challenge in signature generation is to find a finite graph induced by points-to relations (including pointers, pointer field offsets, and pointer types) that uniquely identifies a target data structure, which is the root of the graph. For convenience of discussion, we assume that pointers are not null and they each have an explicit type (i.e. not a void * pointer). We will describe how to handle those real-world issues in Section 6.
As mentioned earlier, two distinct data structures may have isomorphic structural patterns. For example, if two data structures have the same pointer field layout, we need to further look into the “next-hop” data structures (we call them lower layer data structures) via the points-to edges. Moreover, we observe that even though the pointer field layout of a data structure may be unique (different from any other data structure), an instance of such layout in memory is not necessary an instance of the data structure. Consider Figure 3, struct A and X have different layouts for their pointer fields. If the program has only these two data structures, it appears that we can use their one level pointer structure as the signature. However, this is not true. Consider the memory segment at the bottom of Figure 3, in which we detect three pointers (the boxed bytes). It appears that S1(0x80020f0) is true because it fits the one level structure of struct A. But it is possible that the three pointers are instead the instances of fields x2, x3, and x4 in struct X and hence the region is part of an instance of struct X. In other words, a pattern scanner based on struct A will generate many false positives on struct X. The reason is that the structure of A coincides with the sub-structure of X. As we will show later in Section 7, such coincidences are very common.
To better model the issue, we introduce the concept of immediate pointer pattern (IPP) that describes the one level pointer structure as a string such that the aforementioned problem can be detected by deciding if an IPP is the substring of another IPP.
**Definition 1.** Given a data structure T, let its pointer field offsets be f1, f2, ..., fn, pointing to types t1, t2, ..., tn, resp. Its immediate pointer pattern, denoted as IPP(T), is defined as follows.
\[\text{IPP}(T) = f_1 \cdot t_1 \cdot (f_2 - f_1) \cdot t_2 \cdot (f_3 - f_2) \cdot \ldots \cdot (f_n - f_{n-1}) \cdot t_n.\]
We say an IPP(R) is a sub-pattern of IPP(T) if \(g_1 \cdot r_1 \cdot (f_2 - f_1) \cdot r_2 \cdot (f_3 - f_2) \cdot \ldots \cdot (f_n - f_{n-1}) \cdot r_n\) is a substring of IPP(R), with \(g_1 \geq f_1\) and \(r_1, ..., r_n\) any pointer types.
Intuitively, an IPP describes the types of the pointer fields and their intervals. An IPP(T) is a sub-pattern of IPP(R) if the pattern of pointer field intervals of T is a sub-pattern of R’s, disregard the types of the pointers. It also means that we cannot distinguish an instance of T from an instance of R in memory if we do not look into the lower layer structures. For instance in Figure 3, IPP(A) = 0· B · 12 · C · 6 · D and IPP(X) = 8· Y · 28 · BB · 12 · CC · 6 · DD. IPP(A) is a sub-pattern of IPP(X).
**Definition 2.** Replacing a type t in a pointer pattern with “(IPP(t))” is called one pointer expansion, denoted as \(\rightarrow_t\).
A pointer pattern of a data structure T is a string generated by a sequence of pointer expansions from IPP(T).
For example, assume the definitions of B and D can be found in Figure 4.
Figure 4: Data structure isomorphism.
\[
IPP(A) = \begin{cases}
0 \cdot B \cdot 12 \cdot C \cdot 6 \cdot D & \text{if } A \cong R; \\
B \cdot \left(0 \cdot (0 \cdot E \cdot 4 \cdot B) \cdot 12 \cdot C \cdot 6 \cdot D\right) & \text{if } A \ncong R.
\end{cases}
\]
(8)
The strings [1] and [2] are both pointer patterns of \( A \). The pointer patterns of a data structure are candidates for its signature. As one data structure may have many pointer patterns, the challenge becomes to algorithmically identify the unique pointer patterns of a given data structure so that instances of the data structure can be identified from memory by looking for satisfactions of the pattern without causing false positives. If efficiency is a concern, the minimal pattern should also be identified.
Existence of Signature. The first question we need to answer is whether a unique pointer pattern exists for a given data structure. According to the previous discussion, given a data structure \( T \), if its \( IPP \) is a sub-pattern of another data structure’s \( IPP \) (including the case in which they are identical). We cannot use the one layer structure as the signature of \( T \). We have to further use the lower-layer data structures to distinguish it from the other data structure. However, it is possible that \( T \) is not distinguishable from another data structure \( R \) if their structures are isomorphic.
Definition 3. Given two data structure \( T \) and \( R \), let the pointer field offsets of \( T \) be \( f_1, f_2, \ldots, \) and \( f_m \), pointing to types \( t_1, t_2, \ldots, \) and \( t_m \), resp.; the pointer field offsets of \( R \) be \( g_1, g_2, \ldots, \) and \( g_m \), pointing to types \( r_1, r_2, \ldots, \) and \( r_m \), resp.
\( T \) and \( R \) are isomorphic, denoted as \( T \cong R \), if and only if
\[ \begin{align*}
\text{[1]} & \quad n \equiv m; \\
\text{[2]} & \quad \forall 1 \leq i \leq n \left( f_i \equiv g_i \left( f_i \ncong r_i \right) \right); \\
\text{[3]} & \quad \forall a \text{ cycle is formed when deciding } t_i \cong r_i.
\end{align*} \]
Intuitively, two data structures are isomorphic, if they have the same number of pointer fields (Condition [1]) at the same offsets ([2.1]) and the types of the corresponding pointer fields are also isomorphic ([2.2]) or the recursive definition runs into cycles ([2.3]), e.g., when \( t_i \equiv T \cap r_i \equiv R \).
Figure 4 (a) presents the definitions of some data structures in Figure 3. The data structures whose definitions are missing from the two figures do not have pointer fields. According to Definition 3, \( B \cong BB \) because they both have two pointers at the same offsets; and the types of the pointer fields are isomorphic either by the substructures \((E \cong EE)\) or by the cycles \((B \cong BB)\).
Given a data structure, we can now decide if it has a unique signature. As mentioned earlier, we assume that pointers are not \texttt{null} and are not of the \texttt{void*} type.
Figure 5: If the offset of field \texttt{el} in struct \texttt{G} changes to 16, struct \texttt{A} has two possible signatures.
Theorem 1. Given a data structure \( T \), if there does not exist a data structure \( R \) such that
\[ \begin{align*}
\text{[1]} & \quad IPP(T) \text{ is a sub-pattern of } IPP(R), \\
\text{[2]} & \quad \text{assume the sub-pattern in } IPP(R) \text{ is } g_1 \cdot r_1 \cdot (f_2 - f_1) \cdot r_2 \cdot (f_3 - f_2) \cdot \ldots \cdot (f_m - f_{m-1}) \cdot r_m \cdot t_1 \cong t_2 \cong t_2 \cong \ldots \text{ and } t_m \cong t_m. \\
\end{align*} \]
\( T \) must have a unique pointer pattern, that is, the pattern can not be generated from any other individual data structure through expansions.
The proof of Theorem 1 is presented in Appendix I. Intuitively, the theorem specifies that \( T \) must have a unique pointer pattern (i.e., a signature) as long as there is not an \( R \) such that \( IPP(T) \) is a sub-pattern of \( IPP(R) \) and the corresponding types are isomorphic.
If there is an \( R \) satisfying [1] and [2] in the theorem, no matter how many layers we inspect, the structure of \( T \) remains identical to part of the structure of \( R \), which makes them indistinguishable. In Linux kernels, we have found a few hundred such cases (about 12% of overall data structures). But most of them are data structures that are rarely used or not important according to the kernel security and forensics literature.
Note that two isomorphic data structures may have different concrete pointer field types. But given a memory snapshot, it is unlikely for us to know the concrete types of memory cells. Hence, such information cannot be used to distinguish the two data structures. In fact, concrete type information is not part of a pointer pattern. Their presence is rather for readability.
Consider the data structures in Figure 3 and Figure 4. Note all the data structures whose definitions are not shown do not have pointer fields. \( IPP(A) \) is a sub-pattern of \( IPP(X) \), \( B \cong BB \) and \( CC \cong CC \). But \( D \) is not isomorphic to \( DD \) due to their different immediate pointer patterns. According to the theorem, there must be a unique signature for \( A \). In this example, the pointer pattern [2] in Equation (8) is a unique signature and if we find pointers that have such structure in memory, they must indicate an instance of \( A \).
Finding the Minimal Signature. Even though we can decide if a data structure \( T \) has a unique signature with the theorem, there may be multiple pointer patterns of \( T \) that can distinguish it from other data structures. Ideally, we want to find the minimal pattern as it requires the minimal parsing efforts during scanning. For example, if field \texttt{el}’s offset in struct \texttt{G} is 16, struct \texttt{A} has two possible structures as shown in Figure 5. They correspond to the pointer patterns
\[ \begin{align*}
0 \cdot (0 \cdot (16 \cdot G \cdot 8 \cdot H) \cdot 4 \cdot B) \cdot 12 \cdot C \cdot 6 \cdot D \\
0 \cdot B \cdot 12 \cdot C \cdot 6 \cdot (4 \cdot I)
\end{align*} \]
One is generated by expanding \( B \) and then \( E \), and the other is generated by expanding \( D \). Either one can serve as a unique signature of \( A \).
Algorithm 1 An approximate algorithm for signature generation
Input: Data structure $T$.
Output: The pointer pattern that serves as the signature.
1: $s = IPP(T)$
2: let $IPP(T)$ be $f_1 \cdot t_1 \cdot (f_2 - f_1) \cdot t_2 \cdot ... \cdot (f_n - f_{n-1}) \cdot t_n$
3: for each sub-pattern $p_{a_1} \cdot r_1 \cdot (f_2 - f_1) \cdot r_2 \cdot (f_3 - f_2) \cdot ... \cdot (f_n - f_{n-1}) \cdot r_n$
4:
5:
6: expand($s$)
7: for each $p \in distinct$ do
8:
9:
10: if $p$ is different from $s$ disregard type symbols then
11:
12:
13:
14:
15: return $s$
In general, finding the minimal unique signature is a combinatorial optimization problem: given a data structure $T$, find the minimal pointer pattern of $T$ that can not be a sub-pattern of any other data structure $R$, that is, cannot be generated by pointer expansions from a sub-pattern of $IPP(R)$. The complexity of a general solution is likely in the NP category. In this paper, we propose an approximate algorithm that guarantees to find a unique signature if one exists, though the generated signature may not be the minimal one. It is a breadth-first algorithm that performs expansions for all pointer symbols on the same layer at one step until the pattern becomes unique.
The algorithm first identifies the set of data structures that may have $IPP(T)$ as their sub-patterns (lines 3-5). Such sub-patterns are stored in $distinct$. Next, it performs breadth-first expansions on the pointer pattern of $T$, stored in $s$, and the patterns in $distinct$, until all patterns can be distinguished. It is easy to infer that the algorithm will eventually find a unique pattern if one exists.
For the data structures in Figures 3 and 4, the pattern generated for $A$ by the algorithm is
$$0 \cdot (0 \cdot E \cdot 4 \cdot B) \cdot 12 \cdot C \cdot 6 \cdot (4 \cdot I)$$
It is produced by expanding $B$ and $D$ in $IPP(A)$.
Generating Multiple Signatures. In some scenarios, it is highly desirable to generate multiple signatures for the same data structure. A common scenario is that some pointer fields in a signature may not be dependable. For example, certain kernel malware may corrupt the values of some pointer fields and, as a result, the corresponding data structure instance will not be recognized by a signature that involves those pointers.
SigGraph mitigates such a problem by generating multiple unique signatures. In particular, if certain pointer fields in a data structure are potential targets of corruption, SigGraph will avoid using such fields during signature generation in Algorithm 1. For example, if field $e1$'s offset in struct $G$ is 16 and field $a3$ in struct $A$ is not dependable. Algorithm 1 generates a signature for struct $A$ by pruning the sub-graph rooted at field $a3$ in Figure 5(a). The detailed algorithm is elided.
5. PARSER GENERATION
Given a data structure signature, i.e., a pointer pattern, our technique can automatically generate a parser. The parser will be used to scan memory images during forensic investigations and identify instances of the data structure. To automatically generate parsers, we describe all signatures using a context free grammar (CFG). Then we leverage yacc to generate parsers. The CFG is described as follows.
$$\text{Signature} \ ::= \text{number} \cdot \text{Pointer} \cdot \text{Signature} | \epsilon$$
$$\text{Pointer} \ ::= \text{type} | (\text{Signature})$$
In the above grammar, number and type are terminals that represent numbers and type symbols, respectively. A Signature is a sequence of number, Pointer, in which Pointer describes either the type or the Signature of the data structure being pointed-to. It is easy to tell that the grammar describes all the pointer patterns in Section 4, including the signature of $A$ generated by our technique (Equation 9).
Parsers can be generated based on the grammar rules. Intuitively, when a number symbol is encountered, the field offset should be incremented by number. If a type is encountered, the parser asserts that the corresponding memory contain a pointer. If a '(' symbol is encountered, a pointer dereference is performed and the parser starts to parse the next level memory region until the matching ')’ is encountered. A sample parser generated for the signature in Equation (9) can be found in Figure 6.
Function isInstanceOf_A decides if a given address is an instance of $A$; assertPointer asserts the given address must contain a pointer value, otherwise an exception is thrown and the function isInstanceOf_A returns 0. The yacc rules to generate parsers are elided for brevity.
Considering non-pointer fields. So far a parser considers only the positive information from the signature, which is the fields that are supposed to be pointers, but does not consider the implicit negative information, which is the fields that are supposed to be non-pointers. In many cases, negative information is needed to construct robust parsers.
For example, assume a data structure $T$ has a unique signature $0 \cdot A \cdot 8 \cdot B \cdot 4 \cdot C$. If there is a pointer array that stores a consecutive sequence of pointers, even though the signature is unique and has no structural conflict with any other data structures, the generated parser will mistakenly identify part of the array as an instance of $T$.
In order to handle such issues, the parser should also assert that the non-pointer fields must not contain pointers. Hence the parser for the above signature becomes the following. Method assertNotPointer asserts that the given address does not contain a pointer.
6. HANDLING PRACTICAL ISSUES
So far we have assumed an ideal environment for SigGraph. However, when applied to large system software such as the Linux kernel, SigGraph faces a number of practical challenges. In this section, we present our techniques to handle the following key issues.
1. **Null Pointers** – It is possible that pointer fields have a null value, which are not distinguishable from other non-pointer fields, such as integer or floating point fields with value 0. If 0s are considered as a pointer value, a memory region with all 0 values would satisfy any immediate pointer patterns, which is clearly undesirable.
2. **Void Pointers** – Some of the pointer fields may have a void* type and they will be resolved to different types at runtime. Obviously, our signature generation algorithm cannot handle such cases.
3. **User Level Pointers** – It is also possible that a kernel pointer field has a value that actually points to user space. For example, the set_child_tid and clear_child_tid fields in task_struct, and the vdsos field in mm_struct point to user space. The difficulty is that user space pointers have a very dynamic value range due to the very large user space, which makes it hard to distinguish them from non-pointer fields.
4. **Special Pointers** – A pointer field may have non-traditional pointer value. For example, for the widely used list_head data structure, Linux kernel uses LIST_POISON1 with value 0x00100100 and LIST_POISON2 with value 0x00200200 as two special pointer to verify that nobody uses non-initialized list entries. Another special value SPINLOCK_MAGIC with value 0xdead4ead also widely spreads in some pointer fields such as in data structure radix_tree.
5. **Pointer Like Values** – Some of the non-pointer fields may have values that resemble pointers. For example, it is not a very uncommon coding style to cast a pointer to an integer field and later cast it back to a pointer.
6. **Undecided Pointers** – Union types allow multiple fields with different types to share the same memory location. This creates problems for us too when pointer fields are involved.
7. **Rarely Accessed Data Structures** – Our algorithm presented in Section 4 treats all data structures equally important and tries to find signatures that are unique regarding all data structures. However, some of the data structures are rarely used and hence the conflicts caused by them may not be so important.
We find that most of the above problems boil down to the difficulty in deciding if a field is pointer or non-pointer. Fortunately, the following observation leads to a simple solution: Pruning a few noisy pointer fields does not degenerate the uniqueness of the graph-based signatures. Even though a signature after pruning may conflict with some other data structure signatures, we can often perform a few more refinement steps to redeem the uniqueness. As such, we devise a dynamic profiling phase to eliminate the dependable pointer/non-pointer fields.
Our profiler relies on a virtual machine monitor QEMU [3] to keep track of kernel memory allocation and deallocation for kernel data structures. More specifically, since most kernel objects are managed by slab allocators, we hook the allocation and deallocation of kmem_cache objects through functions such as kmem_cache_alloc and kmem_cache_zalloc, retrieving function arguments and return values to track these objects. Their types are acquired by looking at their slab name tags. Then we track the life time of these objects, and monitor their values. More details on how to track the allocation/deallocation of kernel objects at the VMM level can be found in our technical report [28].
We monitor the values of a kernel data structure’s fields to collect the following information: (1) How often a pointer field takes on a value different from a regular non-null pointer value; (2) How often a non-pointer field takes on a non-null pointer-like value; (3) How often a pointer has a value that points to the user space. In our experiment, we profile a number of kernel executions for long periods of time (hours to tens of hours).
With the above profiles, we revise our signature generation algorithm with the following refinements: (1) excluding all the data structures that have never been allocated in our profiling runs so that structural conflicts caused by these data structures can be ignored; (2) excluding all the pointer fields that have the void* type or fields of union types that involve pointers – in other words, these fields are considered dependable (Section 4), which is done by annotating with a special symbol.
### Table 1: Experimental results of signature uniqueness test
<table>
<thead>
<tr>
<th>Kernel version</th>
<th>#Total structs</th>
<th>#Pointer structs</th>
<th>#Unique signature</th>
<th>Percent</th>
<th>Average depth</th>
<th>#No signature</th>
</tr>
</thead>
<tbody>
<tr>
<td>2.6.15-1</td>
<td>8850</td>
<td>3397</td>
<td>3229</td>
<td>89.76%</td>
<td>2.31</td>
<td>368</td>
</tr>
<tr>
<td>2.6.18-1</td>
<td>11800</td>
<td>4882</td>
<td>4050</td>
<td>88.18%</td>
<td>2.45</td>
<td>572</td>
</tr>
<tr>
<td>2.6.20-15</td>
<td>14992</td>
<td>6096</td>
<td>5395</td>
<td>88.50%</td>
<td>2.54</td>
<td>701</td>
</tr>
<tr>
<td>2.6.24-26</td>
<td>15901</td>
<td>6427</td>
<td>5645</td>
<td>87.83%</td>
<td>2.47</td>
<td>782</td>
</tr>
<tr>
<td>2.6.31-1</td>
<td>26799</td>
<td>9957</td>
<td>8683</td>
<td>87.20%</td>
<td>2.73</td>
<td>1274</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Number of Signatures in Different Steps</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>1555</td>
</tr>
<tr>
<td>1820</td>
</tr>
<tr>
<td>2337</td>
</tr>
<tr>
<td>2172</td>
</tr>
<tr>
<td>3364</td>
</tr>
</tbody>
</table>
7. **EVALUATION**
We have implemented a prototype of SigGraph, with C and Python code. Specifically, we instrument gcc-4.2.4 to traverse ASTs and collect data structure definitions. Our parser generator is lex/yacc based, and the generated parsers are in C. The total implementation is around 9.5K lines of C code and 6.8K LOC Python code.
7.1 **Signature Uniqueness**
We first test if unique signatures exist for kernel data structures. We take 5 popular Linux distributions (from Fedora Core 5 and 6; and Ubuntu 7.04, 8.04 and 9.10), and the corresponding kernel version are shown in the first column of Table 1. Then we compile these kernels using our instrumented gcc. Observe that there are quite a large number of data structures in different kernels, ranged from 8850 to 26799. Overall, we find nearly 40% of the data structures have pointer fields, and nearly 88% (shown in the 5th column) of the data structures with pointer fields have unique signatures. We show the
7.2 Effectiveness Compared with Value-invariant
To test the effectiveness of SigGraph, we take Linux kernel 2.6.18-1 as a working system, and show how the generated signatures can detect data structure instances. We list 23 widely used kernel data structures which are shown in the 7th column of Table 2. We choose these data structures because: (1) they are the most commonly examined data structures in existing literature [23, 10, 18, 32, 30, 33, 31, 8]; (2) they are very important data structures that can show the status of the system (the primary focus of memory forensics) in the aspects of process, memory, network and file system; from these data structures, other data structures are also traversed, as our signatures often contain lower level data structures.
To ease our presentation, we assign an ID to each data structure, which is shown in the 3rd column of Table 2, with
Table 2: Summary of data structure signatures from Linux kernel 2.6.18-1
| Category | Data Structure Name | ID | Size | \(|F|\) | \(|P|\) | Statically-Derived Depth | Dynamically-Refined Depth | Static Properties of the Data Structure | SigGraph Signature | Value Invariant Signature |
|------------|---------------------|------|------|--------|--------|--------------------------|--------------------------|------------------------------------------|-------------------|--------------------------|
| Processes | task_struct | 1 | 1408 | 354 | 81 | 1 | 2 | \(\sum P_{i}\) | 2233 | \(\sum |P|\) |
| | thread_info | 2 | 58 | 15 | 4 | 2 | 4 | \(\sum P_{i}\) | 344 | \(\sum |P|\) |
| | key | 3 | 100 | 27 | 9 | 4 | 6 | \(\sum P_{i}\) | 69 | \(\sum |P|\) |
| Memory | mm_struct | 4 | 488 | 123 | 23 | 1 | 2 | \(\sum P_{i}\) | 26 | \(\sum |P|\) |
| | vm_area_struct | 5 | 84 | 21 | 10 | 4 | 4 | \(\sum P_{i}\) | 60 | \(\sum |P|\) |
| | sml_inode_info | 6 | 544 | 135 | 51 | 5 | 5 | \(\sum P_{i}\) | 444 | \(\sum |P|\) |
| | kmem_cache | 7 | 204 | 51 | 39 | 3 | 3 | \(\sum P_{i}\) | 36 | \(\sum |P|\) |
| File System| files_struct | 8 | 308 | 10 | 41 | 3 | 3 | \(\sum P_{i}\) | 153 | \(\sum |P|\) |
| | fs_struct | 9 | 48 | 12 | 7 | 2 | 2 | \(\sum P_{i}\) | 68 | \(\sum |P|\) |
| | file | 10 | 160 | 40 | 11 | 2 | 2 | \(\sum P_{i}\) | 243 | \(\sum |P|\) |
| | proc_inode | 11 | 144 | 63 | 16 | 2 | 2 | \(\sum P_{i}\) | 27220 | \(\sum |P|\) |
| | ext3_inode_info | 12 | 432 | 112 | 49 | 4 | 4 | \(\sum P_{i}\) | 400 | \(\sum |P|\) |
| | vfsmount | 13 | 612 | 151 | 58 | 1 | 1 | \(\sum P_{i}\) | 166 | \(\sum |P|\) |
| | innode_security_struct | 14 | 108 | 23 | 23 | 4 | 4 | \(\sum P_{i}\) | 1884 | \(\sum |P|\) |
| | sysfs_dirent | 15 | 100 | 16 | 0 | 2 | 2 | \(\sum P_{i}\) | 4782 | \(\sum |P|\) |
| Network | socket_alloc | 16 | 44 | 11 | 7 | 1 | 1 | \(\sum P_{i}\) | 61 | \(\sum |P|\) |
| | socket | 17 | 87 | 18 | 7 | 8 | 8 | \(\sum P_{i}\) | 142 | \(\sum |P|\) |
| | sock | 18 | 436 | 114 | 48 | 1 | 1 | \(\sum P_{i}\) | 149 | \(\sum |P|\) |
| Others | hdev_inode | 19 | 568 | 141 | 63 | 6 | 6 | \(\sum P_{i}\) | 6429 | \(\sum |P|\) |
| | mb_cache_entry | 20 | 56 | 12 | 10 | 6 | 6 | \(\sum P_{i}\) | 166 | \(\sum |P|\) |
| | signal_struct | 21 | 412 | 99 | 25 | 4 | 4 | \(\sum P_{i}\) | 290 | \(\sum |P|\) |
| | user_struct | 22 | 52 | 13 | 4 | 6 | 6 | \(\sum P_{i}\) | 394 | \(\sum |P|\) |
7.2.2 Dynamic Refinement
In this experiment, we carry out the dynamic refinement phase as described in Section 6. The depth and the size of signatures before and after pruning are presented in the “SigGraph Signature” columns in Table 2, with \(D\) the depth and \(\sum |P|\) the number of pointer fields. Note that the signature generation algorithm has to be run again on the pruned data structure definitions to ensure uniqueness. Observe that since pointer fields are pruned and hence the graph topology gets changed, our algorithm has to perform a few more expansions to re-deem uniqueness, and hence the depth of signatures increases after pruning for some data structures, such as task_struct.
7.2.3 Value Invariant based Signatures
To compare our approach with value invariant based signatures [33, 31, 12, 8], we also implemented a basic value-invariant signature generation system. In particular, we generally derive four types of invariants for each field, (1) zero-subset: a field is included if it is always zero across all instances during training runs; (2) constant: a field is always constant; (3) bitwise-AND: the bitwise AND of all values of a field is not zero, that is, they have some non-zero common bits; and (4) alignment: if all instances of a field are well-aligned at a power of two (other than 1) number.
To derive these value invariants, we perform two types of profiling: one is access frequency profiling (to prune out the fields that are
never accessed by the kernel), the other is to sample their values and produce the signatures. The access frequency profiling is achieved by instrumenting QEMU to track memory reads and writes. Sampling is similar to the sampling in our dynamic refinement phase.
All the data structures have value invariants, and the statistics of these signatures are provided in the last four columns of Table 2. The total numbers of zero-subset, constant, bitwise-AND, and alignment are denoted as $|Z|$, $|C|$, $|B|$, and $|A|$, respectively.
### 7.2.4 Results
The final results for each signature when scanning a test image is shown in Table 3. The second column shows the total number of true instances of the data structure, which is acquired by the modified crash utility [2]. The $|R|$ column shows the number of instances the signature detected. Due to the limitation of crash, these objects have to be live, i.e., reachable from global or stack variables. However, signature approaches are able to identify free objects. Hence, the detected free objects are determined as false positives (FPs) based on the ground truth from crash. We further take the free but not-yet-overwritten objects, which can also be traversed by crash if the slab allocator haven’t released it to free pages, to better evaluate the real FPs. We present the FPs without considering free objects in the $|FP|$ column and the FPs considering free objects in the $|FP'|$ column. The false negative $|FN|$ is computed by comparing with the ground truth objects from crash.
Observe that among the examined 23 data structures, when free objects are not considered, there are 16 that our approach precisely and completely identifies all instances (both $|FP|$ and $|FN|$ are zero). However, value invariant has only 5 such data structures. If we consider free objects, 20 can be perfectly identified with our approach, whereas 9 can be detected via the value based approach. Note for value invariant signature systems, high false positive rates imply the derived signatures are hardly useable. In other words, value invariant systems may report no signature for these data structures. For the 23 data structure we listed, SigGraph produces high quality signatures.
From the table, we could see our system has false positive for three of the data structures, in particular the $\text{vm\_area\_struct}$ (ID 5 in Table 3), dentry (ID 11) and sysfs_dirent (ID 16). We carefully examined the corresponding snapshot, and found the reason is that some of them are truly freed object (the dentry case), and some of them are caused by our profiling that failed to capture some ground truth data (for $\text{vm\_area\_struct}$ and $\text{sysfs\_dirent}$). The detailed false positive analysis on all these cases is presented in Appendix II.
### Summary
No FNs are observed for our approach, while some are observed for the value invariant based approach. Our approach also has a very low FP rate. We believe the reasons are the following. (1) Graph based signatures are more informative as they include information of data structures at lower levels whereas value-based signatures only look at one level (namely the fields of the data structure itself). (2) Graph-based signatures are more stable and their uniqueness can be algorithmically determined, that is, we can expand the signature along points-to edges as many times as we want to achieve uniqueness, which is hard to perform for value-based signatures.
### More Capability in Memory Forensics
We also observe that signature approaches, including both our approach and value-invariant based approaches, can be used to identify free objects, such as in the cases of $\text{mm\_struct}$ and $\text{fs\_struct}$ data structures. However, our approach can perform better and have identified more free objects, such as in the case of $\text{inode\_security}$, dentry, and $\text{mb\_cache\_entry}$, than previous approaches. Note that object traversal based approach is not able to identify free objects.
### 7.3 Effectiveness without Memory Graph
Memory graph based techniques construct a global reference graph that connects all live objects. The roots are global and stack variables. Objects become invisible if pointers are corrupted so that they are not reachable from the roots. In contrast, SigGraph explores individual graph patterns related to the provided data structure, without constructing a global graph. Therefore, we believe SigGraph provides more robustness against global/stack variable corruption.
To verify our claim, we developed a rootkit to test this feature. In particular, the rootkit (a kernel module per se) overwrites several global variables which are related to process list and the management of slab cache, including $\text{pid\_hash}$, $\text{init\_task}$, and $\text{task\_struct\_cachep}$.
Before loading our rootkit, we took a snapshot, which has 78 running process. Then we run our rootkit. The system crashed as expected due to the pointer corruption. We took another snapshot. Next, we run the crash utility (which takes a memory graph-based approach) on these two images, for the first image, we run the $\text{crash}$ utility. Then we run the $\text{task\_struct\_cachep}$.
### Table 3: Experimental results of our graph based signature and value-invariant signature
| ID | $|R|$ | SigGraph Signature | Value-Invariant |
|----|-----|-------------------|----------------|
| 1 | 88 | 88 0.00 0.00 0.00 | 88 0.00 0.00 0.00 |
| 2 | 88 | 88 0.00 0.00 0.00 | 83 6.45 6.45 1.08 |
| 3 | 22 | 0.00 0.00 0.00 | 19 0.00 0.00 15.79 |
| 4 | 54 | 3.70 0.00 0.00 | 55 5.45 0.00 0.00 |
| 5 | 2233| 2.64 0.40 0.00 | 2405 9.61 7.52 0.00 |
| 6 | 2232| 0.00 0.00 0.00 | 226 0.00 0.00 2.85 |
| 7 | 127 | 0.00 0.00 0.00 | 5124 97.52 97.52 0.00 |
| 8 | 55 | 0.00 0.00 0.00 | 50 0.00 0.00 6.00 |
| 9 | 60 | 13.33 0.00 0.00 | 60 13.33 0.00 0.00 |
| 10 | 791 | 0.00 0.00 0.00 | 791 0.00 0.00 0.00 |
| 11 | 38186| 17.60 0.00 0.00 | 38186 0.00 0.00 0.00 |
| 12 | 885 | 885 0.00 0.00 | 470 0.00 0.00 88.30 |
| 13 | 38153| 0.00 0.00 0.00 | 38153 0.00 0.00 0.00 |
| 14 | 28 | 28 0.00 0.00 0.00 | 28 0.00 0.00 0.00 |
| 15 | 40067| 0.00 0.00 0.00 | 142290 71.84 76.93 0.00 |
| 16 | 2105| 0.00 0.00 0.00 | 88823 97.63 97.63 0.00 |
| 17 | 75 | 75 0.00 0.00 0.00 | 75 0.00 0.00 0.00 |
| 18 | 55 | 55 0.00 0.00 0.00 | 49 0.00 0.00 12.24 |
| 19 | 55 | 55 0.00 0.00 0.00 | 43 0.00 0.00 27.90 |
| 20 | 25 | 25 0.00 0.00 0.00 | 24 1.65 1.65 0.00 |
| 21 | 631 | 17.85 0.00 0.00 | 638 18.50 18.50 0.00 |
| 22 | 73 | 0.00 0.00 0.00 | 72 0.00 0.00 1.39 |
| 23 | 10 | 10 0.00 0.00 0.00 | 10391 99.91 99.91 0.00 |
**7.4 Multiple Signatures**
One powerful feature of SigGraph is that multiple signatures can be generated for the same data structure. We perform the following experiment with $\text{task\_struct}$ data structure. In each run of the experiment, we exclude one of the 38 pointer fields of $\text{task\_struct}$ (assuming that the pointer is corrupted) before running Algorithm 1. In each of the 38 runs, the algorithm is still able to compute a unique, alternative signature for $\text{task\_struct}$. Next, we increase the number of corrupted pointer fields from 1 to 2, and conduct $C_{38}^{2}$ runs of Algorithm 1 (exhausting the combinations of the two pointers excluded). The algorithm is still able to generate a valid signature for each run.
structure values – especially those of the pointer fields. For example, fuuId, linux-fu and hp-1.0.0 manipulate the next and the previous pointers in task_struct at offsets 128 and 132 so that the task_struct for the malicious process is disconnected from the task's list. Yet SigGraph is still able to recover all instances of task_struct (including the disconnected ones) from the memory image, thanks to the existence of multiple alternative signatures of task_struct in the absence of those corrupted pointers (Section 7.4). We have performed experiments to confirm the success of SigGraph in the face of these rootkits (demonstrated in the video clip submitted). In particular, the alternative task_struct signature has \( \sum |P| = 221 \).
While SigGraph has no problem handling the existing rootkits, we envision that there may be more sophisticated attempts to evade SigGraph in the future. We will discuss them in the following. We assume that the attacker has knowledge about SigGraph and has gained control of the kernel. Evasion can be approached by manipulating pointer fields or non-pointer fields.
**Malicious Pointer Value Manipulation** Since SigGraph relies on inter-data structure topology induced by pointers, manipulating pointers would be a natural attempt to defeat SigGraph. However, compared to non-pointer values, pointers are more sensitive to mutation because any changes to a pointer value may very likely lead to kernel crashes. Note that re-pointing a pointer to another data structure instance of the same type may not affect SigGraph in discovering the mutated instance. While the attacker may try to manipulate pointer fields that are not used, recall that SigGraph has a dynamic refinement phase that gets rid of such unused or undependable fields before signature generation.
The attack may try extra hard by destroying a pointer field after a reference, and then restoring it before its next reference. As such, it is likely for a snapshot not to see the true value, depending on the timing. However, carrying out such attacks is challenging as there may be many places that access the pointer field. All such places need to be patched in order to respect the original semantics of the kernel. We can anticipate that demands a complex and expensive static analysis on the kernel. To achieve an under-approximation of the demanded efforts. We conducted a profiling experiment on task_struct. We collect the functions that access each field, including both pointers and non-pointers. The results are shown in Figure 7(a). We observe that on average fields are accessed by at least 6 functions. Some fields have even been accessed by 70 functions (the statistics is shown in Figure 7(b)). Note that these are only profiled numbers, the static counterparts may be even larger. Even if the attacker achieves some success, SigGraph can still leverage its multiple signature capability to avoid using pointers that are easily manipulatable.
**Malicious Non-Pointer Value Manipulation** Another possible way to confuse SigGraph is to mutate a non-pointer value to resemble that of a pointer. SigGraph has also built-in protection against such attacks. First of all, the dynamic refinement phase will get rid of most fields that are vulnerable to such mutation. Moreover, compared to mutation within a domain, such as changing an integer field (with the range from 1 to 100) from 55 to 56, cross-domain mutation, such as changing the integer field to a pointer, has a much higher chance to crash the system. Hence, we suspect that not many non-pointer fields are susceptible. In the future, we plan to use fuzzing, similar to [12], to study how many fields allow such cross domain value mutation. In fact, we can simply integrate SigGraph signatures with the value-invariant signatures (e.g., those derived by [12]) for the same data structure, which is likely to achieve stronger robustness against malicious non-pointer manipulation.
**Other Possible Attacks** The attacker can change data structure layout...
to evade SigGraph. However, such attacks are challenging. He/she needs to intercept the corresponding kernel object allocations and deallocations to change layout at runtime. Furthermore, all accesses to the affected fields need to be patched. Without knowing how the layout is changed, SigGraph will fail.
Furthermore, the attacker could also try to generate fake data structure instances to thwart the use of SigGraph. However, we should point out that fake instance creation is a generally hard problem across all signature-based approaches, including the value-invariant approaches. In fact, SigGraph makes such attacks harder as the attacker would have to fake the multiple data structures involved in a graph signature and make sure that all the points-to relations among these data structures are setup properly.
9. RELATED WORK
Memory Forensics Memory forensics is a process of analyzing a memory image to explain the current state of a computer system. It has been evolving from basic techniques such as string search to more complex methods such as object traversal (e.g.,[23, 30, 10, 18, 9]) and signature based scanning (e.g., [33, 31, 12, 8, 4]).
Object traversal techniques search memory by walking through OS data structures. They rely on building a whole reference graph of all data structures. Hence, they mostly work for live data because “dead” (i.e. freed) data cannot be reached by the reference graph. Constructing reference graphs relies on precisely resolving types of memory objects, which is often hard in the presence of void pointers or unknown data structures. For example, kernel objects that are part of a rootkit data structure cannot be traversed via the reference graph as the rootkit data structure type is unknown, even though the kernel data structure definitions themselves are known. Also, if a pointer in the reference graph is corrupted, then the memory region being pointed to cannot be visited. However, in SigGraph, we can avoid such problems as we do not rely on a fully connected global reference graph.
Signature scanning directly searches memory using signatures. In particular, Schuster [31] presented PTfinder for linearly searching Windows memory to discover process and thread structures, using manually created signatures. Similar to PTfinder, GREPEXEC [4], Volatility [33], Memparser [8] are the other systems that have more capabilities of searching other objects. As signatures are the key to these systems, Dolan-Gavitt et al. [12] proposed an automated way to derive robust data structure signatures. SigGraph complements these systems by deriving another scheme for data structure signature generation.
Rootkit Detection Kernel-level rootkits pose a significant threat to the integrity of operating systems. Earlier research uses specification based approach deployed in hardware (e.g., [34, 21]), virtual machine monitor (e.g., Livewire [14]), or binary analysis [16] to detect kernel integrity violations. Recent advance includes state-based control flow integrity checking (e.g., SBCFI [24] and KOP [9]), and data structure invariant based checking (e.g., [22, 7, 12]).
Our work is inspired by the data structure invariant detection, and hence closely related to [22, 7, 12]. In particular, Petroni et al. [22] proposed examining semantic invariants (such as a process must be on either the wait queue or the run queue) of kernel data structures to detect rootkits. The key observation is that any violations of semantic invariants indicate rootkit presence. However, the extraction of semantic invariants was based on manually created rules. Afterwards, Baliga et al. [7] presented using dynamic invariant detector Daikon [13] to extract data structure constraints. The invariants detected include membership, non-zero, bounds, length, and subset relations. In contrast, we focus on structural patterns. We believe our approach is complementary to theirs. Most recently, Dolan-Gavitt et al. [12] proposed a novel system to automatically select robust signatures for kernel object signatures. Their observation is that value-invariants could be evaded by attackers and thus they propose to use fuzzing technique to test the robustness of value-invariants. The key difference is that they focus on value invariants while we focus on pointer-induced topological patterns between data structures. As discussed earlier, the best practice is likely the integration of the two approaches.
Malware Signature Derivation based on Data Structure Pattern Data structures are one of the important and intrinsic properties of a program. Recent advance has demonstrated that data structure patterns can be used as program signature. In particular, Laika [11] shows a way of inferring the layout of data structure from snapshot, and use the layout as signature. Their inference is based on an unsupervised Bayesian learning and they assume no prior knowledge about program data structures. Laika and SigGraph are substantially different: (1) Laika focuses on how to derive a program signature from data structure patterns, whereas SigGraph focuses on how to discover data structure instances from data structure patterns and how to derive such patterns. (2) Technically, Laika does not aim to accurately infer the data structure patterns (a large number of wrong layout could not hurt their system as they just want to have a classifier to classify the program), however we have to accurately match the instance, otherwise the high false positive and high false negative ratios would render the system unusable. (3) Laika is not interested in any particular type of objects, whereas the output of SigGraph is the specific data structure instances.
Data Structure Type Inference There is a large body of research in program data structure type inference, such as object oriented type inference [20], and aggregate structure identification [26], binary static analysis based type inference [5, 6, 27], abstract type inference [19, 15], and dynamic heap type inference [25]. Most these techniques are static, aiming to infer types of unknown objects in code. SigGraph is more relevant to dynamic techniques. Dynamic heap type inference by Polishchuk et al. [25] focuses on typing heap objects in memory, using various constraints, such as size and type constraints. Heap object types are decided by resolving these constraints. The difference between their work and ours is that they assume all the heap objects are known, including their sizes and locations in the heap. This is done through instrumentation. However, SigGraph’s input is simply a memory image.
10. CONCLUSION
In this paper, we have demonstrated that the points-to graphs between data structures can be used as data structure signatures. We present SigGraph, a system that automatically derives such graph-based data structure signatures. It complements the value-invariant signature systems by covering the majority of kernel data structures with pointer fields. Our experiments show that the signatures generated by SigGraph achieve zero false negative rate and very low false positive rate. Moreover, the signatures are not affected by the absence of global memory graphs and are robust against the corruption of pointer fields. For best effect, we advocate the combination of our graph-based signatures and the value-invariant-based signatures.
11. REFERENCES
Appendix I: The Proof of Theorem 1
PROOF. For each data structure $D$ different from $T$, either condition [1] or [2] is not satisfied according to the preconditions of the theorem.
If [1] is not satisfied, $IPP(T)$ can be used to distinguish $T$ from $R$.
If [2] is not satisfied, there must be an $i$ such that $t_i$ is not isomorphic to $r_i$. There must be a minimal $k$, after $k$ levels of expansions, the pointer pattern of $t_i$ is different from $r_i$'s. Hence, the pointer pattern of $T$ after $k_{\text{max}}$ levels of expansions can distinguish $T$ from any other individual data structure.
Appendix II: False Positive Analysis
In this appendix, we analyze the three false positive cases in detail for data structure $\text{vm_area_struct}$, $\text{dentry}$ and $\text{sysfs_dirent}$.
For $\text{vm_area_struct}$, we have 9 false positives among the total 2233 detected instances. After dynamic refinement, some pointer fields are pruned, such as the pointer field at offset 12 (as shown in Figure 8). Finally, the generated unique signature contains only the first layer pointer structure, in particular, it consists of a pointer field at offset 0 ($\text{mm_struct}$), and then a sequence of non-pointer fields, and so on. However, the $\text{task_structure}$ starting from offset 156 has the identical sub-pattern except the offset 160 is a pointer. But in some rare occasions (which are not captured by our profiler), the pointer field at offset 160 could be 0, leading to a false positive. This is due to the difference between the training images and the test image. We find 9 FP's in this case.
We have 2 FPs for $\text{dentry}$, which are shown in Figure 9(a). We classify these two instances as FPs because they cannot be found in either the pool of live objects or the pool of free objects. However, if...
we carefully check each field value, especially the boxed ones: the 0xdead4ead (SPINLOCK MAGIC at offset 12) and 0xcf91fe00 (a pointer to dentry_operations at offset 88), it is hard to believe these are not dentry instances, when compared with the true instance. As such, we suspect they are not FPs, and they are the cases that the slab allocator has freed the memory page of the destroyed dentry instances.
We have 6 FPs in sysfs_dirent data structure among the 2116 detected instances. The detailed memory dump of these 6 FP cases is shown in Figure 9(b). After our dynamic refinement, the fields at offsets 32 and 36 are pruned because they often contain null pointers, and the final signature entails checking two list_head data structures followed by a void* pointer at offset 4, 8, 12, 16 and 20, and four non-pointer field checking. Note one list_head has only two fields: previous and next pointer. However, there are 6 memory chunks that match our signature in the testing image. The chunks are not captured as part of the ground truth of any data structures. We suspect that it could be the case that they are aggregations of multiple data structures and the aggregations coincidentally manifest the pattern.
Appendix III: Performance Overhead
We also measured the performance overhead of our scanner (i.e., the parser). We run both our scanner and value invariant scanners on the testing image (256MB) in a machine with 3GB memory and an Intel Core 2 Quad CPU (2.4Ghz) running Ubuntu-9.04 (Linux kernel 2.6.28-17). The final result of the normalize performance overhead is shown in Figure 10. We could see the performance overhead for our scanner is still acceptable. We need to do address translation when there is a memory de-reference, but there is no need in value-invariant scanner. Thus, in all the case value-invariant inevitably performs better than our scanner. If the depth is relatively small, such as the 10 case with depth $D = 2$, our scanner only has 10X to 20X overhead than value invariant scanner. The deeper, the worse in our scanner, because more nodes need to be examined and more address translation needs to be involved, this is why the case of inode_security (with $D = 7$) and mb_cache_entry (with $D = 6$), we have big performance overhead. Thus, if the depth is not so high for the desired data structure, our system may be used as an online scanner. For example, in our experiment, it actually only takes a few seconds when
|
{"Source-Url": "https://www.cerias.purdue.edu/assets/pdf/bibtex_archive/2010-04-report.pdf", "len_cl100k_base": 15874, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 50742, "total-output-tokens": 17606, "length": "2e13", "weborganizer": {"__label__adult": 0.0005788803100585938, "__label__art_design": 0.0007691383361816406, "__label__crime_law": 0.0015707015991210938, "__label__education_jobs": 0.0007314682006835938, "__label__entertainment": 0.00014150142669677734, "__label__fashion_beauty": 0.00024437904357910156, "__label__finance_business": 0.00027298927307128906, "__label__food_dining": 0.0003862380981445313, "__label__games": 0.0016241073608398438, "__label__hardware": 0.004425048828125, "__label__health": 0.0005350112915039062, "__label__history": 0.0005145072937011719, "__label__home_hobbies": 0.0001608133316040039, "__label__industrial": 0.0007166862487792969, "__label__literature": 0.0005102157592773438, "__label__politics": 0.0004208087921142578, "__label__religion": 0.0006074905395507812, "__label__science_tech": 0.21728515625, "__label__social_life": 0.00012671947479248047, "__label__software": 0.0233612060546875, "__label__software_dev": 0.74365234375, "__label__sports_fitness": 0.0003170967102050781, "__label__transportation": 0.0005974769592285156, "__label__travel": 0.00021195411682128904}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67285, 0.09392]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67285, 0.39474]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67285, 0.88241]], "google_gemma-3-12b-it_contains_pii": [[0, 5835, false], [5835, 10841, null], [10841, 17188, null], [17188, 23491, null], [23491, 29118, null], [29118, 36090, null], [36090, 43586, null], [43586, 50988, null], [50988, 55034, null], [55034, 62983, null], [62983, 64819, null], [64819, 67285, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5835, true], [5835, 10841, null], [10841, 17188, null], [17188, 23491, null], [23491, 29118, null], [29118, 36090, null], [36090, 43586, null], [43586, 50988, null], [50988, 55034, null], [55034, 62983, null], [62983, 64819, null], [64819, 67285, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67285, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67285, null]], "pdf_page_numbers": [[0, 5835, 1], [5835, 10841, 2], [10841, 17188, 3], [17188, 23491, 4], [23491, 29118, 5], [29118, 36090, 6], [36090, 43586, 7], [43586, 50988, 8], [50988, 55034, 9], [55034, 62983, 10], [62983, 64819, 11], [64819, 67285, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67285, 0.2397]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
c63cc9a5c54d5b6259a8ef42585e0d8ff36b97d0
|
Adding Semantic Modules to improve Goal-Oriented Analysis of Data Warehouses using I-star
Alejandro Maté\textsuperscript{a,}\textsuperscript{*}, Juan Trujillo\textsuperscript{a}, Xavier Franch\textsuperscript{b}
\textsuperscript{a}Lucentia Research Group, Department of Software and Computing Systems, University of Alicante, Carretera San Vicente del Raspeig s/n - 03690 San Vicente del Raspeig - Alicante, Spain
\textsuperscript{b}BarcelonaTech, Universitat Politècnica de Catalunya, Calle Jordi Girona, 31 - 08034 Barcelona, Spain
Abstract
The success rate of data warehouse (DW) development is improved by performing a requirements elicitation stage in which the users’ needs are modeled. Currently, among the different proposals for modeling requirements, there is a special focus on Goal-Oriented models, and in particular on the i* framework. In order to adapt this framework for DW development, we previously developed a UML profile for DWs. However, as the general i* framework, the proposal lacks modularity. This has a specially negative impact for DW development, since DW requirement models tend to include a huge number of elements with crossed relationships between them. In turn, the readability of the models is decreased, harming their utility and increasing the error rate and development time. In this paper, we propose an extension of our i* profile for DWs considering the modularization of goals. We provide a set of guidelines in order to correctly apply our proposal. Furthermore, we have performed an experiment in order to assess the validity our proposal. The benefits of our proposal are an increase in the modularity and scalability of the models which, in turn, increases the error correction capability, and makes complex models easier to understand by DW developers and non expert users.
Keywords: Data Warehouses, modules, user requirements, i-star
1. Introduction
Organizations manage huge amounts of information, and wish to take informed decisions by using that information. Nowadays, there is an increasing importance of the Business Intelligence (BI) in the enterprise environment. In
fact, the Gartner Group showed that, during the recent recession period, the BI market not only did not decrease, but instead it grew a 4% [1].
At the core of the BI, among other technologies, is the Data Warehouse (DW). DWs integrate several heterogeneous data sources in multidimensional structures (i.e., facts and dimensions) in support of the decision-making process [2, 3]. Therefore, the development of the DW is a complex process which must be carefully planned in order to meet user needs. This process can be even more complex, if we consider that requirements for the DW change as the organization’s information needs change. For this reason, the modeling of user needs is a very important aspect of DWs, which can be accomplished by means of goal-oriented models. These models represent the users’ intentions in a requirements model using goals and are easily understandable by them. Among the goal-oriented approaches, the i* framework [4], is currently one of the most widespread goal modeling frameworks. This framework has been applied for modeling organizations and system requirements among others.
However, due to the idiosyncrasy of DWs, a specialization of the i* framework was required, in order to correctly model the desired information goals. In our previous work, we presented the required specialization, along with our development methodology for DWs. In our proposal, we follow the Model Driven Architecture (MDA) [5], starting from a Computation Independent Model (CIM) layer where requirements are modeled. From this layer, the DW schema is derived into a Platform Independent Model (PIM) layer, reconciliated with the information present in the data sources, and derived into its implementation. Therefore, the CIM layer is crucial, since it acts as the starting point.
Nevertheless, as pointed in [6], the i* framework lacks scalability due to the absence of modularity. Modularity is a well-known concept in software engineering. As far as the start of the 70s, modular programming became a hot topic and the benefits of splitting complexity using some well-defined criteria were subject of several seminal papers [7]. Afterwards, modularity spread over other life-cycle activities and artifacts, and became very popular especially in the context of system design, where the notion of decomposing a system into its parts offers several benefits like better flexibility, management and testability, to name a few. Since we are interested in modularity applied to specification models, it can be defined as the ability to decompose a large model into several sub-models, such that they independently have a well-defined meaning, and whose combination solves the original problem.
Since the work presented in [8] is a specialization of the original framework, it lacks modularity as well. As DW requirements models may become very complex, this hurts their readability and comprehension, becoming more difficult to correct and update as requirements change. We have experienced this drawback ourselves, as some of our real projects had over 16 goals, 15 tasks and 53 resources for a single actor. These models became huge for correction and communication with the users. Sometimes these models even included repeated DW elements in the same model with different structure, since designers forgot which elements were already defined. Therefore, it is important to improve this aspect in order to manage corrections and changes in requirements in an easier
way.
In the short version of this paper [9] we proposed an extension of our i* profile [8], in order to adapt it and improve its modularity. In turn, this increases the their manageability, as well as the comprehension capability of the user when dealing with complex models. With these modifications, the communication between users and developers is improved, leading to higher success rates. We also provide a set of guidelines to correctly apply the proposal. Moreover, we performed an experiment in order to assess the validity our proposal.
In addition, in this long improved version, we (i) include the definitions of the main goals (strategy, decision, and tactic) in which we classify the final user’s needs, (ii) perform an ontology mapping between concepts in the i* framework and the DW context, and include Decision, Information, and Hierarchy modules, increasing the scalability of the models, (iii) include an extended case study in order to show the applicability and benefits of applying our proposal, as well as (iv) describe a second, deeper analysis of the results, reaching new conclusions to better define and organize the modules.
The rest of the paper is structured as follows. Section 2 presents the related work in this area. Section 3 presents our i* profile for DWs. Section 4 proposes the different types of modules for our i* profile. Section 5 presents an example of application and the experiment performed. Finally, Section 6 summarizes the conclusions and future work.
Basic knowledge of i* is assumed in the paper, see [4] and the i* wiki (http://istar.rwth-aachen.de) for a thorough presentation.
2. Related Work and Background
Scalability is probably the best-known and widely acknowledged problem of i*. It is fact that i* models quickly grow in size (see [10] for an illustrative example of large-scale using the original i* model) making them rapidly difficult to manage. As argued by [11], the scalability problem is a direct consequence of the lack of mechanisms for modularization. In that work, the authors conducted an empirical study on different aspects related to i* as a modeling language, and it was concluded that modularity is not supported in i*, consequently we may say that scalability is not supported either. Since the core of the language has not evolved since then, the problem persists nowadays.
When dealing with scalability issues, other works have focused on i* modularity in general, like the one in [6]. However, these modules do not have meaningful semantics for being applied in DWs, which could favor the understandability of the modularization process. Therefore, before performing any kind of adaptation, a study of the target domain must be performed along with a mapping between the concepts. Then, the necessary modules should be defined accordingly to how the target domain is structured. This approach has been applied in other areas successfully. For example, in [12] the authors introduce new elements in the notation of task models that summarize several elements in the diagrams, allowing the designers to manage their complexity while keep-
ing the models meaningful. However, an analysis of both the domain and the notation used in the diagrams is required in order to introduce these elements.
Within the area of DW requirements modeling, initial works such as [13] propose to represent DW requirements by means of use case diagrams. Use cases divide DW requirements into an actor dependency diagram and several use case specifications. However, use case notation is difficult for users to understand. Therefore, more recent works focus on representing DW requirements in terms of goals, both i* based, such as [8, 14], and non-i* based [15]. The i* based approaches suffer from the lack of modularity inherent to the original framework, as they model user goals without providing any mechanisms to control the complexity and size of the diagrams. Unfortunately, non-i* based models do not include any modularization elements either, thus the complexity and size of the diagrams is only determined by the complexity of user requirements themselves.
In our previous work, we developed a UML profile for modeling DWs at conceptual level [16], where the importance of packages was shown, in order to improve the modularity of DW conceptual models. The packages included were StarPackage, for differentiating cubes, DimensionPackage, for aggregating dimensions along with their hierarchies, and FactPackage, which included the associated fact. These packages allow the developer to analyze the model at different levels of detail, hiding those elements on which he has no interest, lowering the complexity of the model and increasing its readability. In turn, this aspect makes the developing of the schemata less error prone.
However, since the conceptual level is closer to developers than to users, we required models with a higher level of abstraction in the development process. Therefore, in order to improve the communication with the users, and increase the success rate of DW projects, we included a RE phase in our methodology [8]. In this RE phase, requirements are captured on a model by using a UML profile [8] based on the i* framework [4]. From these requirements, the conceptual model is automatically derived by means of Model Driven transformations [17], transforming the different Business Process, Contexts, and Measures associated with the goals at requirements level into Facts, Dimensions and Measures at the conceptual level.
Nevertheless, although our i* profile incorporated the necessary semantics and methodology, it lacks any kind of modularity. In turn, this hurts the communication with the users, since complex requirements models can become huge and difficult to read and understand. Now, in this work, we complement our approach, by improving the modularity and scalability of our i* profile. We include modules for the decision and information goals, as well as for hierarchies of contexts. By improving the modularity, the models are easier to read, which, in turn, reduces the error rate and increases user satisfaction.
3. i* Profile for DWs
Our i* profile, presented in [8], follows a Goal-Oriented Requirements Engineering (GORE) approach. GORE is concerned about modeling goals, thus
obtaining user requirements by following a refinement process [18]. The i* modeling framework [4] provides mechanisms to represent actors, their dependencies, and structuring the business goals that organization pretends to achieve. This framework establishes two models: the strategic dependency (SD) model for describing the dependency relationships among various actors in an organizational context, and the strategic rationale (SR) model, used to describe actor interests and concerns, and how they might be addressed. From now on, we focus on the SR models to model goals and information requirements of decision makers.
The first step is aligning the ontology of i* with the target domain. In the DW domain, the requirements model specifies the informational needs of different stakeholders in order to support the decision-making process. This information is used to improve the performance of a business activity. In our observation, several types of goals which arise naturally during the design process.
- **Strategic goals.** They represent a desired change from a current situation into a future one. A strategic goal is always related to the main objectives of the business process (see below) that is being improved. Therefore, strategic goals always have an objective to be met, either clear, i.e. Sales increased, or fuzzy, i.e. Number of clients significantly increased. They are long-term goals that cause an immediate benefit for the organization when fulfilled.
- **Decision goals.** They operationalize strategic goals into appropriate actions by answering the question: “how can a strategic goal be achieved?”. Decision goals represent decisions that make use of information in order to provide a benefit for the organization. Decisions can be described either in terms of objectives, i.e. Some kind of promotion offered, or in terms of tasks, i.e. Open new stores. The benefit obtained by a decision goal is directly related to the achievement strategic goals by means of the decision goal.
- **Information goals.** They identify the information required for a decision goal to be achieved by answering the question: “how can decision goals be achieved in terms of information required?”. Information goals specify the necessary information to be gathered, typically by means of an analysis. Therefore, they can be defined in terms of goals, i.e. Customer purchases analysed, or in terms of the analysis process, i.e. Examine the stocks daily. The satisfaction of information goals allows decision makers to take decisions and fulfill decision goals.
These three types of goals have a decreasing level of abstraction, from strategic (most) to informational (less). In addition, there is a contextualization relationship among goals: decision goals only take place within the context of strategic goals, and informational goals only take place inside the context of decisional goals.
Along with these goals, the DW domain includes several key concepts related to the multidimensional level of DWs [19]. These description of these concepts, presented in Figure 1, is as follows:
- **Business Processes**. Represent an activity on which the user wishes to influence by means of strategies. These business processes have associated a series of performance indicators, represented as measures of the business process. Sometimes business processes can be described in terms of the goal pursued by the activity, i.e. Contracts agreed, or in terms of the activity itself, i.e. Make sales.
- **Information Requirements**. Represent the necessary information in order to achieve an information goal. They are always considered in terms of information gathering tasks. Information requirements are decomposed into context and measures, that represent the information to be gathered by the information requirement.
- **Contexts**. Describe the necessary additional data in order to analyze a given business process. They represent information about entities involved in the business processes of the organization, i.e. Department or Customer, and can be grouped into hierarchies, i.e. All customers within the same city.
- **CIM measures**. Represent indicators of performance of a business process. They provide quantitative information that can be assessed by decision makers in order to evaluate if business processes are performing as expected. PIM measures are the multidimensional counterpart of indicators.
- **Bases**. Represent the multidimensional counterpart of contexts. They describe the levels of abstraction within a dimension of the data warehouse.
Table 1: Alignment of the DW concepts with the i* framework
<table>
<thead>
<tr>
<th>DW</th>
<th>i* concept</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Strategic goal</td>
<td>Goal</td>
<td>Sales increased</td>
</tr>
<tr>
<td></td>
<td>Softgoal</td>
<td>Number of clients significantly increased</td>
</tr>
<tr>
<td>Decision goal</td>
<td>Goal</td>
<td>Some kind of promotion offered</td>
</tr>
<tr>
<td></td>
<td>Task</td>
<td>Open new stores</td>
</tr>
<tr>
<td>Information goal</td>
<td>Goal</td>
<td>Customer purchases analysed</td>
</tr>
<tr>
<td></td>
<td>Task</td>
<td>Examine stocks daily</td>
</tr>
<tr>
<td>Business Process</td>
<td>Goal</td>
<td>Contracts agreed</td>
</tr>
<tr>
<td></td>
<td>Task</td>
<td>Make sales</td>
</tr>
<tr>
<td>Information Requirement</td>
<td>Task</td>
<td>Record task assignments and durations</td>
</tr>
<tr>
<td>Context</td>
<td>Resource</td>
<td>Market; Department</td>
</tr>
<tr>
<td>Measure</td>
<td>Resource</td>
<td>Discount; Income generated</td>
</tr>
</tbody>
</table>
- **Dimensions.** Represent a context of analysis to analyze a fact, and are formed by sets of hierarchies. Each hierarchy can have one or more groups of bases, forming classification and generalization hierarchies in the multidimensional model and defining the structure of the data warehouse.
- **Facts.** Represent the multidimensional counterpart of the business process which wants to be improved.
After having presented the target domain concepts, we proceed to map the DW concepts with the i* ontology, as shown in Table 1. As can be perceived, not all the elements are aligned. Specifically, the concepts of dimension, fact, base, and PIM Measures, are not considered part of the requirements engineering process, thus they are left aside as external elements. Moreover, some DW concepts can be mapped into more than one i* intentional type depending on the level of abstraction and the cut criterion chosen.
Once we have defined and mapped the concepts in our i* profile, we will describe them through an example, shown in Figure 2. In this example, we start the requirements analysis from a business process (BP), related to the decision-maker. The BP, which is the center of the analysis, models an activity of interest for the decision-maker, in this case the *Make Contracts*, and has associated a series of strategic goals, in order to improve the business performance. Strategic goals represent the highest level of abstraction. They are thought as changes from a current situation into a better one in terms of business process objectives. In our case, the strategic goals associated with the BP are *Cost of contracts minimized* and *Quality of workers increased*. Other examples of strategic goals would be *Increase sales*, *Increase number of customers*, *Decrease cost*, etc. Their fulfillment causes an immediate benefit for the organization.
In order to achieve these strategic goals, there are a series of decision goals that must be met. Decision goals represent the medium level of abstraction in our SR models. They try to answer the question “how can a strategic goal be
Figure 2: Example of the current monolithic CIM representation
achieved?”, and they aim to take the appropriate actions to fulfill a strategic goal. They are related to strategic goals by intentional means-end relationships. In our example, in order to achieve Cost of contracts minimized, it has been decided that it is necessary to Minimum number of new contracts made as well as CV requirement introduced for new workers, in order to achieve the strategic goal. However, decision goals can affect more than one strategic goal. In our case, the last decision goal is related with Quality of workers increased strategic goal as well, since the CV affects the quality of the new workers being employed. Other examples of decision goals would be Determine some kind of promotion or Open new stores. Their fulfillment only causes a benefit for the organization if it helps to reach strategic goals, since decision goals only take place within the context of a strategic goal.
As with the strategic goals, the decision goals can be achieved by having the necessary information available. This required information is modeled by means of the informational goals. Information goals represent the lowest level of abstraction. They try to answer the question: “how can decision goals be achieved in terms of information required?”, and they are related to the information required by a decision goal to be achieved. In our example, the information required is Hours of work and workers per task analysed and Tasks performed by the workers analysed for each decision goal, whereas the information about Sick leaves per worker analysed affects only the Overall happiness maintained decision goal. Other examples of information goals are Analyze customer purchases or Examine stocks. Their fulfillment helps to achieve decision goals and they only happen within the context of a decision goal.
Finally, informational goals are achieved by means of information requirements. In our case, we need to Record Task duration, Record Task assignments and Record Illness reports per worker in order to gather the required informa-
Each of these requirements is decomposed into Contexts and Measures. The example includes the Task, Worker and Illness report contexts as well as the Income generated, Average sick leave duration and Average number of sick leaves measures, which determine the performance of the BP.
As has been shown in the example, a lower-level goal can be a part of different higher-level goals. This process is repeated at all levels, leading to highly interrelated elements in the model, making difficult to comprehend the business strategy in huge models. In order to solve this issue, we propose a series of modules, packaging all the elements related to a given higher-level goal on each module.
4. Definition of Modules and Guidelines
In this section, we will present the extension to our i* profile for DWs, by defining the proposed modules and the extended metaclasses. Furthermore, we will also present some guidelines to the application of the modules proposed.
4.1. Definition of Modules
First, we will define our proposed modules, in order to decrease the complexity of the goal models. The modules which we will define are strongly related with the identified concepts in the DW domain. Therefore, each module has a specific semantic associated adapted for the DW domain. We have not included a module for strategic goals since typically there is only a few of them.
- Decision modules include the elements related to a given decision goal. They can include decision goals, information goals, requirements, contexts, measures, other decision modules, information modules, and hierar-
Figure 4: i* profile with modules extension for DW
modules. They contain all the necessary information to take a given decision, which helps achieving a strategic goal.
- **Information modules** include the elements related to a given information goal. They can include information goals, requirements, contexts, measures, other information modules, and hierarchy modules. They aggregate all the information which is necessary to satisfy a given information goal.
- **Hierarchy modules** include the elements which constitute a hierarchy. They are formed by the different contexts which represent the different levels of aggregation of a dimension. They can only include contexts. These modules help with the reusability of the dimensions at the requirements level, and hide the complexity of hierarchies when it is unnecessary.
These modules are shown in Figure 4 together with the rest of the elements in the i* for DWs profile. The modules defined are loosely coupled with the core i* elements, shown in Figure 3, and extend from the Package element. Moreover, they include an intermediate element, iModule, in order to help with the definition of OCL constraints. After having defined the modules, we will present a set of guidelines to apply them while minimizing the drawbacks.
4.2. Guidelines
In this section, we will give some guidelines to use the provided modules, in order to maximize their benefits. It is not mandatory to package every element, although it is recommended for the sake of uniformity and to provide different abstraction levels, which is a more intuitive approach (G1). However, if some parts of the goal tree have a low complexity, it might not be necessary to group
them in a separate package (G2). For each package created, there should be a single root element, corresponding to the type of package, which acts as a connection for higher level elements. This element should have no dependencies to other elements inside the same package (G3). The name of the package should be the same as the root element, in order to help with the identification of the corresponding packaged subtree (G4). This helps keeping in mind which lower level elements support each higher level goals. For each decision goal a Decision module should be created (G5). Inside a decision module there should be an Information module for each information goal which supports the decision goal (G6). If included in a CASE tool, elements should not be repeated, but instead imported from packages where they were first defined (G7). Information modules should include all the elements related to the information goal, importing elements where necessary, and always including a Hierarchy module for each different hierarchy of contexts present (G8). These Hierarchy modules represent the lowest level of abstraction in the strategic rationale, and should be always separated from the goal tree, in order to hide the details of the hierarchies of contexts unless they are necessary (G9).
4.3. Improvements in Scalability
In order to demonstrate the improvements in scalability obtained with the introduction of modules it is first necessary to define the concept of scalability. Scalability is a term often used intuitively, but with no clear definition. When used in the context of software engineering notations and diagrams [20], it usually refers to “Scalability in the context of software engineering is the property of reducing or increasing the scope of methods, processes, and management according to the problem size [...] Inherent in this idea is that software engineering techniques should provide good mechanisms for partitioning, composition, and visibility control. It includes the ability to scale the notation to particular problem needs, contractual requirements, or even to budgetary and business goals and objectives.” In practice, scalability problems arise typically when models become too large to be handled adequately, as shown in the previous sections.
In the particular case of i*, inherited by i* for DWs, the lack of modularization elements limits the capability of the designer to partition the model, control the visibility of elements, and scale the notation to particular needs, i.e. decision maker’s goals vs data warehouse structural requirements. The modules proposed in this section enable the designer to (i) perform partitioning, dividing a single diagram into multiple ones, thus reducing the visual complexity of each individual sub-diagram, (ii) control the visibility of unnecessary elements, hiding lower abstraction goals and their structure by means of packages, and (iii) manage the scope of the diagrams, by separating decision maker’s goals from data warehouse structural requirements (contexts and measures) derived from these goals.
5. Example of Application and Experiment Results
In this section we will present the application of our proposal to an example, as well as the results of an experiment performed in order to analyze how users and developers perceive the modularized models.
5.1. Example of Application
The following example presents a simpler goal tree, as opposed to the one presented in section 3, whereas the contexts and hierarchies are better defined at requirements level than previously, and the scope of each element may be hard to identify. In this case, the contexts can be aggregated at different levels of detail, presenting market and electronic product contexts as the lowest level, which can be aggregated up to state and section levels.
This example can be modularized using the proposed packages, decreasing its complexity and providing different levels of detail. In this sense, now there is a first level providing an overview of the strategies related to the business process and their corresponding decisions. In this case, the goal tree presents the different decision packages as its leaves, which are further detailed in their corresponding models. Figure 6 presents the previous business process with 3 related strategies and the corresponding 3 decision packages.
For each decision, we have a different package which includes their related information goals and presents the intermediate level of detail. The elements corresponding to each information goal are also modularized in their own packages, which are the leaves of the decision models.
Finally, for each information goal, we have a package which includes their related information requirements, presenting the corresponding hierarchy packages and measures. Figure 7 presents a information goal with 3 different information requirements, which account for a total of 2 measures and 2 hierarchies.
In this model, hierarchies are included at CIM level, but are separated into their own packages. This hides the lowest level of detail, which acts as a bridge between the requirements and conceptual models, whenever it is necessary, allowing us to focus on the modeling of the goals and their related elements.
5.2. Experiment Results
We have performed an experiment, with participants ranging from non-expert people to DW designers and experts on i* modeling, in order to evaluate the impact of our proposal. This experiment is part of a family of experiments for assessing the validity and impact of the proposal, following the same methodology as in [21]. There were two rounds of experiments. The first round presented two examples, one smaller (see Figure 2, Example 1) and one bigger (see figure 5, Example 2). Both examples were presented in generic i* notation with our own stereotypes, in order to make the questionnaires more accessible for all the participants. Monolithic models were presented in a single sheet, whereas modularized models were presented in multiple sheets. Both base examples were small in comparison with real project models, presenting fewer goals and contexts in order to make them manageable. These examples were presented in the four combinations:
- Questionnaire 1.A: Example 1 without modules, Example 2 with modules.
- Questionnaire 1.B: Example 2 with modules, Example 1 without modules.
- Questionnaire 2.A: Example 2 without modules, Example 1 with modules.
- Questionnaire 2.B: Example 1 with modules, Example 2 without modules.
A total of 28 participants filled the questionnaire. Each participant was given one kind of questionnaire and they were asked to identify and mark a series of elements on each model (which were the same for both modularized
and monolithic versions of the same example). The participants were not able to modify their answer once they finished a question. After completing the identification tasks on each model they were asked to give scores for a series of characteristics of the model, ranging from 0 to 3. Finally, after having finished identifying elements in both models, they were asked abstract questions about how they would add a new element at different levels (decision goal, information goal and a set of contexts), while not referencing any example. The group of participants was formed by 14 self-evaluated beginners, 8 participants with some experience and 6 participants were advanced users/experts. Regarding the accumulated experience, 17 participants had less than 1 year of experience in the i* framework, 8 participants had between 1 and 5 years of experience and 3 participants had over 5 years of experience. Given this sample, the hypothesis for our experiment are:
Null hypothesis, $H_0$: There is no statistically significant correlation between the modularization of models and the time required for different tasks and the characteristics perceived.
Hypothesis $H_1$: $\neg H_0$.
The independent variables in the experiment are those whose effects should be evaluated. In our experiment, this variable corresponds to how the model is structured (modularized or monolithic). On the other hand, dependent variables for the experiment are the understandability and manageability of the models, evaluated accordingly to the time necessary to perform different tasks on the models. As there was no statistically significant correlation between the structure of the models and most tasks, we did not calculate further values like efficiency and effectiveness. Therefore, the results will be discussed in terms of trends. The experiment results for the first round are shown in Table 2. Time is measured in seconds.
In order to obtain the results, in every step, first, outliers were identified and filtered. Then, the second step was to perform a variance analysis of the data (ANOVA), in order to identify significant differences between the models. After the first step, 27 questionnaires were left, which were used for the statistical analysis. The significance analysis ($\rho < 0.05$) revealed that the reading time for the Sales model was significantly different (inferior) than when built in a monolithic way. The only other significant difference perceived was the scalability of both examples, which had a notably increase.
Table 2: Tasks performed (left) and independent (top) variables for experiment 1
<table>
<thead>
<tr>
<th></th>
<th>Monolithic</th>
<th>Modularized</th>
<th>$\rho$</th>
</tr>
</thead>
<tbody>
<tr>
<td>Avg. reading time Sales</td>
<td>299.31</td>
<td>210.31</td>
<td>0.037</td>
</tr>
<tr>
<td>Identif. task 1 Sales</td>
<td>190.08</td>
<td>278.62</td>
<td>0.074</td>
</tr>
<tr>
<td>Identif. task 2 Sales</td>
<td>190.94</td>
<td>165.08</td>
<td>0.396</td>
</tr>
<tr>
<td>Avg. reading time Contracts</td>
<td>162.73</td>
<td>181.33</td>
<td>0.576</td>
</tr>
<tr>
<td>Identif. task 1 Contracts</td>
<td>150.07</td>
<td>211.5</td>
<td>0.112</td>
</tr>
<tr>
<td>Identif. task 2 Contracts</td>
<td>124.33</td>
<td>161.00</td>
<td>0.096</td>
</tr>
<tr>
<td>Avg. errors per questionnaire Sales</td>
<td>0.82</td>
<td>0.47</td>
<td>0.247</td>
</tr>
<tr>
<td>Avg. errors per questionnaire Contracts</td>
<td>0.33</td>
<td>0.36</td>
<td>0.906</td>
</tr>
<tr>
<td>Readability score Sales</td>
<td>2</td>
<td>1.93</td>
<td>0.826</td>
</tr>
<tr>
<td>Scalability score Sales</td>
<td>1.41</td>
<td>2.26</td>
<td>0.016</td>
</tr>
<tr>
<td>Comprehension score Sales</td>
<td>1.5</td>
<td>1.87</td>
<td>0.229</td>
</tr>
<tr>
<td>Modifiability score Sales</td>
<td>1.5</td>
<td>2.06</td>
<td>0.079</td>
</tr>
<tr>
<td>Readability score Contracts</td>
<td>2.27</td>
<td>2.33</td>
<td>0.803</td>
</tr>
<tr>
<td>Scalability score Contracts</td>
<td>1.67</td>
<td>2.41</td>
<td>0.011</td>
</tr>
<tr>
<td>Comprehension score Contracts</td>
<td>2.13</td>
<td>2.05</td>
<td>0.857</td>
</tr>
<tr>
<td>Modifiability score Contracts</td>
<td>1.73</td>
<td>2.17</td>
<td>0.128</td>
</tr>
</tbody>
</table>
However, we perceive an increase in time spent in order to identify and mark elements. The identification tasks required to identify and mark all elements related to a decision goal (task 1) and only the lowest level (contexts and measures) elements related to another goal. This increase in time can be due to marking a higher number of elements in 4 different sheets, as opposed to a single sheet in the monolithic model. Nevertheless, the number of wrong answered questions notably diminished in the Sales example when it was modularized. This is specially relevant, since participants identifying elements in the modularized example had to correctly identify the detail level of a package in the next sheet, whereas those in the monolithic example did not suffer from this drawback. Even though, participants identifying elements in the monolithic Sales model systematically forgot different contexts and measures.
Finally, when asked about how they would structure the models, most of the participants chose to organize them in a modularized fashion. Out of 27 participants 17 chose to package the decision goals and their related elements, 16 packaged the information goals, and 19 chose to package a new hierarchy and include it inside another package wherever it was necessary. It is noteworthy that, although we also analyzed the results according to the participants expertise and years of experience on the i* framework, no significant correlation nor trend was found. This suggests that the addition of modules affects similarly to participants without regards to their experience.
After the first round, we performed a second round with 21 participants, including modification tasks over existing models, as well as the creation of a new model. The examples were the same as in the previous round, and they were presented in the same fashion. The group of participants in this second round was formed by 9 self-evaluated beginners, 5 participants that had some
Table 3: Tasks performed (left) and independent (top) variables for experiment 2
<table>
<thead>
<tr>
<th>Task Description</th>
<th>Monolithic</th>
<th>Modularized</th>
<th>p</th>
</tr>
</thead>
<tbody>
<tr>
<td>Modif. task 1 Sales</td>
<td>202</td>
<td>154.27</td>
<td>0.327</td>
</tr>
<tr>
<td>Modif. task 2 Sales</td>
<td>223.6</td>
<td>290</td>
<td>0.217</td>
</tr>
<tr>
<td>Modif. task Contracts</td>
<td>128.73</td>
<td>197.6</td>
<td>0.002</td>
</tr>
<tr>
<td>Avg. Time drawing</td>
<td>1306.67</td>
<td>1891.44</td>
<td>0.019</td>
</tr>
<tr>
<td>Avg. Time/element</td>
<td>50.10</td>
<td>44.34</td>
<td>0.809</td>
</tr>
<tr>
<td>Avg. number of elements</td>
<td>25.67</td>
<td>42.89</td>
<td>0.000</td>
</tr>
<tr>
<td>Avg. unique non package elements</td>
<td>25.67</td>
<td>27.67</td>
<td>0.021</td>
</tr>
</tbody>
</table>
experience, and 5 participants who were advanced users/experts. Furthermore 2 participants did not provide details about their background. As in the previous case, no correlation between the results and the expertise of the participants was found. The results are shown in Table 3.
After the first step, 4 questionnaires were excluded for the modification tasks, leaving a total of 17 questionnaires. However, the statistical analysis did not show any significant differences in the modification tasks. As previously, we can also perceive a decrease in time spent when the model is bigger and we perform small modifications on a single module (task 1), whereas there is an increase when we require information from multiple modules (task 2).
Finally, the creation of a new model from the scratch had a sample of 15 questionnaires, with a significant correlation between the structure of the model created and every result. Time spent was notably superior for models created with a modularized approach while time spent per element drawn was inferior when the model was modularized. Most importantly, the average number of elements identified from the text which described the model was superior when modules were applied, as opposed to the monolithic structure. Additionally, some monolithic models (filtered in the outliers analysis), presented repeated elements, which should not be created, and tend to increase in number as the model gets bigger.
A second, more detailed review of the results revealed an interesting result. Table 2 shows the number of questions incorrectly answered (average number of errors), either because of a single mistake or because of multiple mistakes. When analyzing the exact nature of errors, we found out that participants using monolithic models mixed different branches of the goal tree and overlooked several elements. On the other hand, participants using the modularized models overlooked systematically overlooked measures when they were requested to identify hierarchies and measures. This is a significant result since, currently, information modules include both goals and DW elements. When participants tried to locate DW elements, they kept going deeper in the diagram until they found only DW elements, i.e. hierarchy modules. Thus, they systematically forgot measures in the answer.
According to these results, we intend to redefine the modules, substituting information modules with information requirement modules, more focused on
DW elements. This way, we expect participants to identify easier where DW elements and user goals are located in the diagram. Furthermore, this redefinition also reduces the amount of diagrams required to interact with the users to validate the goal tree.
6. Conclusions and Future Work
Traditionally, i* models lack any modularity, suffering from scalability and readability issues. Regardless its widespread adoption, the i* framework is still facing several open issues. For instance, [22] mentions as directions of further research: clear definition of the i* language core, proposal of modeling methodologies and analysis techniques, and proposal of modularity constructs. Lack of modularity has been reported to harm model scalability and readability.
Therefore, although the profile presented in [8] is adapted for the semantics present in DWs, it suffers from the same issues as the original framework, since it provides no additional modularity. In turn, when real project models become huge, they turn from a useful tool for communicating with the user into a burden which requires too much work to correct, use and modify. Therefore, an improve in modularity is required in order to maintain the quality of the requirement analysis for DWs, while maintaining the specific semantics for them.
In this work, we have presented a proposal for applying modules, specially designed for DWs. We have defined our proposal, and provided some guidelines on how to correctly apply it. We also have shown an example of application and we have performed an experiment, with our proposal, including participants ranging from new users to experts on i* modeling. The results show a significant increase the scalability of the models, as well as a reduced error rate when identifying the scope of an element present in the model, while helping to create richer goal models. We also perceived an increase in the time necessary to perform different tasks over the models, which may be reduced if these tasks were performed with a CASE tool. Finally, experiment results show that most people tend to group elements in packages at different levels of abstraction, as opposed to adding them in a global schema, which may be helpful in the communication of models.
According to the new findings obtained from a deeper analysis, it would be positive to redefine the modules by substituting the intermediate level (information) by a lower abstraction level that completely separates user goals from information itself (information requirement). This way, both DW designers and users can focus on analyzing the validity of the current set of goals or the current information considered to make decisions.
Finally, an interesting research direction is to analyze how the set of modules could be further extended to consider advanced types of data warehouses, such as distributed spatio-temporal DWs and stream DWs [23, 24, 25, 26]. In these cases, the special nature of the information store should be considered, allowing not only to better package their requirements, but also improving the maintainability and change management of the data warehouse structure.
Acknowledgments.
This work has been partially supported by the ProS-Req (TIN2010-19130-C02-01) and by the MESOLAP (TIN2010-14860) and SERENIDAD (PEII-11-0327-7035) projects from the Spanish Ministry of Education and the Junta de Comunidades de Castilla La Mancha respectively. Alejandro Maté is funded by the Generalitat Valenciana under an ACIF grant (ACIF/2010/298).
|
{"Source-Url": "https://upcommons.upc.edu/bitstream/handle/2117/166456/ModulesOnIStarDWExtendedReviewed.pdf?isAllowed=y&sequence=5", "len_cl100k_base": 9381, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 41691, "total-output-tokens": 11249, "length": "2e13", "weborganizer": {"__label__adult": 0.0003094673156738281, "__label__art_design": 0.0008044242858886719, "__label__crime_law": 0.0003643035888671875, "__label__education_jobs": 0.002567291259765625, "__label__entertainment": 8.487701416015625e-05, "__label__fashion_beauty": 0.0001984834671020508, "__label__finance_business": 0.0012235641479492188, "__label__food_dining": 0.0003483295440673828, "__label__games": 0.0005884170532226562, "__label__hardware": 0.0006384849548339844, "__label__health": 0.00049591064453125, "__label__history": 0.000392913818359375, "__label__home_hobbies": 0.000125885009765625, "__label__industrial": 0.0007219314575195312, "__label__literature": 0.0003333091735839844, "__label__politics": 0.00027370452880859375, "__label__religion": 0.0003790855407714844, "__label__science_tech": 0.0826416015625, "__label__social_life": 0.00011396408081054688, "__label__software": 0.0215911865234375, "__label__software_dev": 0.884765625, "__label__sports_fitness": 0.00023484230041503904, "__label__transportation": 0.0006060600280761719, "__label__travel": 0.00022125244140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48536, 0.04394]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48536, 0.38713]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48536, 0.92941]], "google_gemma-3-12b-it_contains_pii": [[0, 2129, false], [2129, 5619, null], [5619, 8747, null], [8747, 11935, null], [11935, 14846, null], [14846, 16521, null], [16521, 19696, null], [19696, 21812, null], [21812, 23402, null], [23402, 25104, null], [25104, 28195, null], [28195, 29754, null], [29754, 31864, null], [31864, 34399, null], [34399, 37677, null], [37677, 40886, null], [40886, 44041, null], [44041, 46234, null], [46234, 48536, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2129, true], [2129, 5619, null], [5619, 8747, null], [8747, 11935, null], [11935, 14846, null], [14846, 16521, null], [16521, 19696, null], [19696, 21812, null], [21812, 23402, null], [23402, 25104, null], [25104, 28195, null], [28195, 29754, null], [29754, 31864, null], [31864, 34399, null], [34399, 37677, null], [37677, 40886, null], [40886, 44041, null], [44041, 46234, null], [46234, 48536, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48536, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48536, null]], "pdf_page_numbers": [[0, 2129, 1], [2129, 5619, 2], [5619, 8747, 3], [8747, 11935, 4], [11935, 14846, 5], [14846, 16521, 6], [16521, 19696, 7], [19696, 21812, 8], [21812, 23402, 9], [23402, 25104, 10], [25104, 28195, 11], [28195, 29754, 12], [29754, 31864, 13], [31864, 34399, 14], [34399, 37677, 15], [37677, 40886, 16], [40886, 44041, 17], [44041, 46234, 18], [46234, 48536, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48536, 0.22989]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
a11860e9ba76237055feb3b6146642f082faeb3f
|
Discovering Model Transformation Pre-conditions using Automatically Generated Test Models
Jean-Marie Mottu, Sagar Sen, Juan Cadavid, Benoit Baudry
To cite this version:
Jean-Marie Mottu, Sagar Sen, Juan Cadavid, Benoit Baudry. Discovering Model Transformation Pre-conditions using Automatically Generated Test Models. IEEE International Symposium on Software Reliability Engineering, ISSRE 2015, Nov 2015, Washington DC, United States. hal-01228715
HAL Id: hal-01228715
https://hal.archives-ouvertes.fr/hal-01228715
Submitted on 13 Nov 2015
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
Discovering Model Transformation Pre-conditions using Automatically Generated Test Models
Jean-Marie Mottu
Université de Nantes, LINA
Nantes, France
Email: mottu-jm@univ-nantes.fr
Sagar Sen
Simula Research Laboratory
PB 134, 1325 Lysaker, Norway
Email: sagar@simula.no
Juan Cadavid
CEA, LIST
Gif-sur-Yvette, France
Email: Juan.Cadavid@cea.fr
Benoit Baudry
INRIA
Rennes, France
Email: Benoit.Baudry@inria.fr
Abstract—Specifying a model transformation is challenging as it must be able to give a meaningful output for any input model in a possibly infinite modeling domain. Transformation pre-conditions constrain the input domain by rejecting input models that are not meant to be transformed by a model transformation. This paper presents a systematic approach to discover such pre-conditions when it is hard for a human developer to foresee complex graphs of objects that are not meant to be transformed. The approach is based on systematically generating a finite number of test models using our tool, RAMANA, first cover the input domain based on input domain partitioning. Tracing a transformation’s execution reveals why some pre-conditions are missing. Using a benchmark transformation from simplified UML class diagram models to RDBMS models we discover new pre-conditions that were not initially specified.
Keywords: Model transformation, Testing, Model Generation, Pre-condition, Incomplete Domain Specification
I. INTRODUCTION
Model transformations are core Model Driven Engineering (MDE) components that automate important steps in software development such as refinement of an input model, refactoring to improve maintainability or readability of the input model, aspect weaving into models, exogenous/endogenous transformations of models, and the classical generation of text such as code from models. Transformations are different from general-purpose languages such as Java as they raise the level of abstraction to facilitate the processing of models which are graphs of interconnected objects specified by an input metamodel. Examples of transformation languages include those based on graph rewriting [5], imperative execution (e.g. Kermeta [27]), and rule-based transformation (e.g. ATL [18]).
Testing model transformations presents several new challenges [6]. Model transformation testing ensures that the implementation is correct w.r.t a specification. The tester should first consider the correctness of the specification, i.e. the transformation produces the expected output model from a given input model. In this paper, we consider the case in which the specification is possibly incomplete, i.e. there are missing pre-conditions. The execution of such an incompletely specified transformation can lead to its computation not finishing or producing incorrect output models. Ideally we must specify a model transformation such that it can appropriately handle all models in its input modeling domain. This means that a model transformation must correctly transform models that it is supposed to transform and reject those that it is not designed to transform. For instance, the input domain for an object persistence transformation [7] comprises of UML class models (UMLCD) and output domain of entity-relationship (RDBMS) models. Classes must have at least one primary attribute (an unique identifier) for it to be transformed to entities in the RDBMS model. Any model in the input domain with a class that does not have a primary attribute is not eligible for transformation and must be rejected.
A model transformation’s specification entails pre-conditions as contracts on the input domain of a model transformation to prevent it from processing ineligible models. However, pre-conditions can be notoriously hard to foresee and specify for a model transformation given that the input domain is a set of infinite objects (for example, due to 0..* multiplicities in a metamodel) with potentially infinite ways of being interconnected. Our hypothesis is that a finite representative subset of models in the input domain can help improve the specification of a model transformation’s pre-condition. How can we automatically generate this finite set of models and consequently discover new pre-conditions for a model transformation? This is the question that intrigues us and we present an approach to address it.
Incremental Pre-condition Discovery: Our approach consists of (1) Automatic generation of a finite set of input test models \( I \) for a transformation based on input domain partitioning in the current specification (consisting of input metamodel, invariants on it, and initial set of pre-conditions) of the input domain. We use the tool PRAMANA based on previous work [30] that solves an ALLOY specification \( A \) of the input domain to generate these models. (2) We dynamically analyze the execution of a transformation using test models in \( I \). Test models that either run into an infinite loop transformation resulting in a stack overflow, or, transform to an output model not in the specified output domain are deemed as failed inputs. Either those failed inputs are out of the input domain, or the transformation is unable to correctly transform them. In both cases, the specification is possibly incomplete, and it should be completed with new pre-conditions. For every failed input we produce an execution trace to identify the modeling pattern (objects and relationships) that leads to failure. (3) We introduce a human-in-the-loop to transform the modeling patterns to new pre-conditions and repeat the generation and test process until all generated test models in are executed correctly by the transformation. New pre-conditions are represented as new ALLOY facts in \( A \). They are also represented by the human expert as OCL constraints (the classical constraint modeling language) to improve the specification of the input domain.
We apply our approach to discover new pre-conditions for the benchmark model transformation of simplified Unified Modelling Language Class Diagram (UMLCD) to Relational Database Management Systems (RDBMS) models called class2rdbms. The transformation class2rdbms was initially specified by a panel of experts at the MTIP workshop in Models 2005 [7] with one pre-condition. We discover 12 new pre-conditions for class2rdbms. This discovery of knowledge can be seen as valuable gems added to the initial specification of class2rdbms. The new pre-conditions also illustrate the fact that some modeling patterns have a potentially complex structure that cannot be foreseen by a human modeler. For instance, we discovered a pre-condition that rejects an input model for class2rdbms because it contains a class A which inherits from a persistent class B and has an attribute with the same name and type of an attribute in persistent class B. A model like this cannot be persisted into an RDBMS model because the columns will conflict. The discovery of pre-conditions was based on executing up to 13 series of 1890 automatically generated test models in each iteration and several hours of computation on two high-end computers.
We summarize our contributions as follows:
**Contribution 1:** A systematic approach to discover new model transformation pre-conditions
**Contribution 2:** Discovery of a set of 12 new pre-conditions for the benchmark transformation class2rdbms [7].
The paper is organized as follows. In Section II, we present the transformation case study class2rdbms as a running example and use it to describe the problem. In Section III, we present foundational ideas to understand the paper. In Section IV, we present our approach for pre-condition discovery based on automatic test model generation and input domain partitioning. In Section V, we present the experimental setup to generate models and present the discovered pre-conditions. In Section VI, we present threats to validity. In Section VII, we present related work. We conclude in Section VIII.
II. CASE STUDY AND MOTIVATION
Our general objective is to discover novel pre-conditions for a model transformation $MT$ for a program applied on a set of input models $I$ to produce a set of output models $O$ as illustrated in Figure 1. The set of all input models is specified by a metamodel $MM_I$ (for example, simplified UMLCD in Figure 2). The set of all output models is specified by a metamodel $MM_O$. Post-conditions $post(MT)$ constrains $MT(I, O)$ to producing a subset of all possible output models. The model transformation is developed based on a set of textual specification of requirements $MT_{Requirements}$.
**A. Transformation Case Study**
Our case study is the transformation from simplified UML Class Diagram models to RDBMS models called class2rdbms.
In this section we briefly describe class2rdbms.
In Figure 2, we present the simplified UMLCD input metamodel for class2rdbms. The concepts and relationships in the input metamodel are stored as an Ecore model [10] (Figure 2 (a)). **Four invariants** among a total of ten on the simplified UMLCD Ecore model, expressed in Object Constraint Language (OCL) [29], are shown in Figure 2 (b). The Ecore model and the invariants together represent the input domain for class2rdbms. The Ecore and OCL are industry standards used to develop metamodels and specify different invariants on them. OCL is not a domain-specific language to specify invariants. However, it is designed to formally encode natural language requirements specifications independent of its domain.
The input metamodel $MM_I$ gives an initial specification of the input domain. In addition, the model transformation itself has a set of pre-conditions $pre(MT)$ that input models need to satisfy to be correctly processed. Constraints in the pre-condition for class2rdbms include: (a) All class objects must have at least one primary `Property` object. (b) The type of a `Property` object can be a `Class C`, but finally the transitive closure of the type of `Property` objects of `Class C` must end with type `PrimitiveDataType`. In our case we approximate this recursive closure constraint by stating that `Property` object can be of type `Class up to a depth of 3` and the 4th time it should have a type `PrimitiveDataType`. This is a finitization operation to avoid navigation in an infinite loop. (c) There are no associations between class in an inheritance hierarchy. The first pre-condition (a) was in the initial specification of MTIP [7] and the two other ones (b and c) have been added when the transformation has been implemented and previously studied. We use the implementation written in Kermeta. Kermeta is a language for specifying metamodels, models, and model transformations that are compliant to the Meta Object Facility (MOF) standard [28].
We choose class2rdbms as our representative case study to address our problem of pre-condition discovery. It serves as a sufficient case study for several reasons. The transformation is the benchmark proposed in the MTIP workshop at the MoDELS 2005 conference [7] to experiment and validate model transformation language features. The input domain metamodel of simplified UMLCD covers all major metamodeling concepts such as inheritance, composition, finite and infinite multiplicities. The constraints on the simplified UMLCD metamodel contain both first-order and higher-order constraints. There also exists a constraint to test transitive closure properties on the input model such as there must be no cyclic inheritance (Figure 2 (b)). class2rdbms is not just a refactoring, it is an exogenous transformation: input and output metamodels are different. The class2rdbms exercises most major model transformation operators such as navigation, creation, and filtering (described in more detail in [25]) enabling us to find loops due to several transformation operators. Among the limitations the simplified UMLCD metamodel does not contain `Integer` and `Float` attributes. There are also no inter-metamodel references in the metamodel.
**B. Motivation**
Any computer program has limitations on what it can process: e.g. a division of integers is not supposed to divide per
zero. Programs have a limitation on memory and computation capacity for any given algorithm. Design by contracts [16], [21] is a programming paradigm that emerged at the turn of the 21st century as an effective and practical means to prevent programs from processing faulty inputs and producing faulty outputs due to specification of pre and post conditions. However, specifying contracts from model transformations in the form of pre-conditions is more complex. The input domain of a model transformation for instance is a set of potentially infinite graphs of interconnected objects (for instance, due to multiplicities 0..*). It is hard to foresee graph like patterns that could crash a model transformation and subsequently become pre-conditions.
The specification provided in [7] specifies how several structures in the models have to be transformed. For instance, it is specified that the “recursive nature of the drilling down” should be considered. Therefore, the initial specification contains a pre-condition (b) ensuring that the type of a Property object can be a Class C, but finally the transitive closure of the type of Property objects of Class C must end with type PrimitiveDataType. And the model transformation is able to process models with such structures. However, some model structures allowed by the input metamodel are not specified in the class2rdbms specification. The consequence is that the implementation of class2rdbms fails processing them. For instance, it fails when attributes are typed with their containment class. This failure leads the implementation of class2rdbms to loop infinitely. Therefore, we have to complete the spec-
ification to consider that structure (illustrating Figure [3], for instance preventing it in the input models.
Another motivating sample with class2rdbms is that an input model could be transformed into an output model with two identical columns which is incorrect as it violates an output model invariant.
Our challenge is to focus on discovering pre-conditions that ensure that:
- A model transformation does not loop infinitely and consequently leading to a stack overflow.
- Output models are correct, i.e., they always conform to the output metamodel and do not violate a post-condition in the set post(MT).
III. FOUNDATIONS
This section presents foundational ideas used by the methodology for generating models to discover pre-conditions in Section IV. We briefly describe PRAMANA for automatic test model generation in Section III-A. Test model generation in this paper is guided by coverage criteria based testing strategies, which are input domain independent. These testing strategies are described in Section III-B.
A. PRAMANA: A Tool for Automatic Model Generation
We use the tool PRAMANA previously introduced (with the name CARTIER) in our paper [30] to automatically generate test input models (test models in the rest of the paper since we do not consider output models). PRAMANA transforms the input domain specification of a model transformation to a common constraint language ALLOY. Solving the ALLOY model gives zero or more models in the input domain of a transformation. PRAMANA first transforms a model transformation’s input metamodel expressed in the Eclipse Modeling Framework [10] format called Ecore using the transformation rules presented in [30] to ALLOY. Basically, classes in the input metamodel are transformed to ALLOY signatures and implicit constraints such as inheritance, opposite properties, and multiplicity constraints are transformed to ALLOY facts.
Second, PRAMANA also addresses the issue of transforming invariants on metamodels and pre-conditions expressed in Object Constraint Language (OCL) to ALLOY. The automatic transformation of OCL to ALLOY presents a number of challenges that are discussed in [11]. We do not claim that all OCL constraints can be manually/automatically transformed to ALLOY for our approach to be applicable in the most general case. The reason being that OCL and ALLOY were designed with different goals. OCL is used mainly to query a model and check if certain invariants are satisfied. ALLOY facts and predicates on the other hand enforce constraints on a model. This is in contrast with the side-effect free OCL. The core of ALLOY is declarative and is based on first-order relational
logic with quantifiers while OCL includes higher-order logic and has imperative constructs to call operations and messages making some parts of OCL more expressive. In our case study, we have been successful in transforming all meta-constraints on the UMLCD metamodel to ALLOY from their original OCL specifications. Nevertheless, we are aware of OCL’s status as a current industrial standard and thus provide an automatic mapping to complement our approach.
Previous work exists in mapping OCL to ALLOY. The tool UML2Alloy [1] takes as input UML class models with OCL constraints. The authors present a set of mappings between OCL collection operations and their ALLOY equivalents. Here we present our version of such transformation derived from [1] and written in Kermeta.
The context of an OCL constraint (which is what defines the value of the self function) determines the place of the constraint within the generated ALLOY model. It is added as an appended fact. The mappings in Table I taken in part from [1] show the set of transformation rules that can be implemented. OCL constraints in this article were transformed manually to ALLOY due to their complexity.
However, some classes of OCL invariants cannot be automatically transformed to ALLOY using the simple rules in Table I. For example, consider the invariant for no cyclic inheritance in Figure 2(b) [1]. The constraint is specified as the fact in Listing 1. This is an example in which the richness of the ALLOY language overcomes OCL - it is not possible to specify this constraint in OCL without using recursive queries since there is no transitive closure operator.
<table>
<thead>
<tr>
<th>OCL Expression Type</th>
<th>ALLOY Abstract Syntax Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>context T inv expr</td>
<td>sig (T, {expr})</td>
</tr>
<tr>
<td>col</td>
<td>forAll(v : T</td>
</tr>
<tr>
<td>col</td>
<td>forAll(v : col</td>
</tr>
<tr>
<td>expr and expr2</td>
<td>expr1 & expr2</td>
</tr>
<tr>
<td>expr or expr2</td>
<td>expr1</td>
</tr>
<tr>
<td>not be</td>
<td>be</td>
</tr>
<tr>
<td>col</td>
<td>size()</td>
</tr>
<tr>
<td>col</td>
<td>includes(o : T)</td>
</tr>
<tr>
<td>col</td>
<td>excludes(o : T)</td>
</tr>
<tr>
<td>col</td>
<td>includesAll(col2)</td>
</tr>
<tr>
<td>col</td>
<td>excludesAll(col2)</td>
</tr>
<tr>
<td>col</td>
<td>including(o : T)</td>
</tr>
<tr>
<td>col</td>
<td>excluding(o : T)</td>
</tr>
<tr>
<td>col</td>
<td>isEmpty()</td>
</tr>
<tr>
<td>col</td>
<td>notEmpty()</td>
</tr>
<tr>
<td>expr</td>
<td>propertyCallExpr</td>
</tr>
<tr>
<td>if expr then expr else expr2</td>
<td>be ⇒ expr1 else expr2</td>
</tr>
<tr>
<td>expr</td>
<td>oclHasUnimplemented</td>
</tr>
<tr>
<td>expr</td>
<td>oclIsKindOf(o : T)</td>
</tr>
<tr>
<td>col</td>
<td>union(col2)</td>
</tr>
<tr>
<td>col</td>
<td>intersection(col2)</td>
</tr>
<tr>
<td>col</td>
<td>product(col2)</td>
</tr>
<tr>
<td>col</td>
<td>sum</td>
</tr>
<tr>
<td>col</td>
<td>symmetricDifference(col2)</td>
</tr>
<tr>
<td>col</td>
<td>select(be)</td>
</tr>
<tr>
<td>col</td>
<td>allNames(propertyCallExpr)</td>
</tr>
</tbody>
</table>
Listing 1. ALLOY Fact for No Cyclic Inheritance
B. Test Selection Strategies
We guide automatic model generation to select test models that cover the input domain of a model transformation following our previous works [15, 30]. We define a strategy as a process that generates ALLOY predicates which are constraints added to the ALLOY model synthesized by PRAMANA as described in Section IV. This combined ALLOY model is solved and the solutions are transformed to model instances of the input metamodel that satisfy the predicate. We guide model generation based on input-domain partition based strategies where we combine partitions on domains of all properties of a metamodel (cardinality of references and domain of primitive types for attributes). A partition of a set of elements is a collection of n ranges A1, ..., An such that A1, ..., An do not overlap and the union of all subsets forms the initial set. These subsets are called ranges. We use partitions of the input domain since the number of models in the domain are infinitely many. Using partitions of the properties of a metamodel we define two coverage criteria that are based on different strategies for combining partitions of properties. Each criterion defines a set of model fragments for an input metamodel. These fragments are transformed to predicates on metamodel properties by PRAMANA. For a set of test models to cover the input domain at least one model in the set must cover each of these model fragments. We generate model fragment predicates using the following coverage criteria to combine partitions:
- **AllRanges Criteria**: AllRanges specifies that each range in the partition of each property must be covered by at least one test model.
- **AllPartitions Criteria**: AllPartitions specifies that the whole partition of each property must be covered by at least one test model.
The notion of coverage criteria to generate model fragments was initially proposed in our paper [15]. The accompanying tool called Meta-model Coverage Checker (MMCC) [15] generates model fragments using different test criteria taking any metamodel as input. Then, the tool automatically computes the coverage of a set of test models according to the generated model fragments. If some fragments are not covered, then the set of test models should be improved in order to reach a better coverage.
In this paper, we use the model fragments generated by MMCC for the UMLCD Ecore model (Figure 2). We use the criteria AllRanges and AllPartitions. For example, in Table I, mfAllRanges1 and mfAllRanges2 are model fragments generated by PRAMANA using MMCC for the name property of a classifier object. The mfAllRanges1 states that there must be at least one classifier object with an empty name while mfAllRanges2 states that there must be at least one classifier object with a non-empty name. These values for name are the ranges for the property. The model fragments chosen using AllRanges mfAllRanges1 and mfAllRanges2 define two partitions partition1 and partition2. The model fragment mfAllPartitions1 chosen using AllPartitions defines both partition1 and partition2. The Table I lists the 27 consistent model fragments used in our experiments. Several model fragments are inconsistent with respect to the input metamodel and other fragments. In [25] we discuss why fragments such as mfAllRanges7 are inconsistent.
These model fragments are transformed to ALLOY predicates by PRAMANA. For instance, model fragment `mfAllRanges8` is transformed to the predicate in Listing 2.
Listing 2. ALLOY Predicate for `mfAllRanges8`
IV. APPROACH
In this section we present a methodology to discover pre-conditions for a given model transformation. We use `class2rdbms` as a running example to illustrate the methodology. The process is divided into 8 steps as illustrated in Figure 5. Section IV-A describes how we detect that an input model is outside the input domain of the model transformation (in steps 3 and 4). The Section IV-B describes the identification of incorrect input excerpts based on transformation traces (in steps 2, 5, and 6). The Section IV-C describes how the tester can write a new pre-condition (in step 8) based on incorrect input model pattern obtained by generalizing a set of incorrect input excerpts (in step 7).
A. Detecting incorrect input models
We identify two reasons why an input model should not be selected as a model transformation entry: when the transformation is unable to transform it, and when it is transformed into an incorrect output model.
1) Non-transformable input model (Step 3): In Step 3 of Figure 5, we find out why an input model is non-transformable. For this, we consider a fundamental characteristic of model transformations: they are designed to navigate through the model and find modeling elements to transform. Navigation is one of the three main operations performed by a model transformation [25]. When it navigates a model it can enter into navigation loops and no output will never be returned. The transformation can run infinitely but most of the time it will crash (in particular once the memory stack is full, or if a time limit is reached). We detect that a transformation loops when our experiments return stack overflow errors.
In the Figure 4, we present a model excerpt extracted from an input model that loops when executed by class2rdbms. The transformation hence never returns an output model. This input model contains an association named “15” (names in generated models have a string type but have an integer value to simplify solving with Alloy) which is supposed to be transformed into a column in an output RDBMS model. This association has a destination non persistent class named “7”. The attributes of this class need to be transformed into columns in the output RDBMS model. The attribute of this class “7” named “16”, is supposed to be transformed to a column typed with the non persistent class named “12” which in turn is the source class for the association named “15”. The Figure 4 illustrates a closed loop and the transformation will infinitely navigate via the association named “12”. Loops such as this will not allow the transformation class2rdbms to terminate.
Identifying the problematic input excerpt is complicated as a tester should identify the model excerpt that loops in a potentially large input model. This particular excerpt in Figure 4 contains 4 objects (2 classes, 1 association, and 1 attribute). However, the excerpt was found in an input model containing 50 objects and their properties (names, etc.).
2) Transformed into an incorrect output model (Step 4): Output models are incorrect when they do not conform to the output metamodel+invariants or when they do not satisfy the transformation’s post-conditions. For instance, an RDBMS model should not have a table with several identical columns (same name and type). This is an invariant that must be satisfied by any RDBMS model. This invariant, written in OCL, is:
```
context Table
cols->forall(c1, c2 | (c1.name = c2.name and c1.type = c2.type) implies c1=c2)
```
When an input model produces an incorrect output model, the constraint checking mechanism in Kermeta identifies the incorrect part in the output model by raising an exception. For instance, if an input model CD is transformed to an RDBMS model with two identical columns with the same name and type then it will violate the post-condition above.
In the Figure 6, we present the incorrect excerpt from an output model. Both columns have identical names and
Fig. 5. Methodology for Pre-condition Discovery
Fig. 6. Incorrect excerpt of an output model
types. This incorrect excerpt has been identified when the invariant is unsatisfied on an RDBMS model returned by the transformation.
The difficulty to create a pre-condition from an incorrect output model is harder than the previous point in Section IV-A since we have to consider an output excerpt. This excerpt has only 3 objects, whereas the entire output model has 67 objects and its input model has 40 objects with their properties making it hard to discover the problematic excerpt.
When an input model (i) cannot be transformed or when (ii) its output model is incorrect, we know that the input model is incorrect and the model transformation’s specification should prevent it from being processed. At the end of those steps 3 and 4, we identify incorrect input models, and we know when the output model is produced which output excerpt is incorrect. But in both cases, we still have to study entire incorrect input models (at this point due to space limitations we use the Figure 8 to illustrate only an excerpt of an entire incorrect input model; entire input models are referred in the appendix A).
B. Identifying incorrect input excerpt
Incorrect input models are identified in the previous Section IV-A. We need to precisely identify the concerned elements in each incorrect input model. Finding these incorrect input excerpts can be hard as these models can be quite large. We will use them as an incorrect input excerpt to create new pre-conditions. That identification is made easier thanks to traceability in a model transformation.
1) Creating Trace (Step 2): While executing the model transformation, we collect a trace linking input elements with output elements. We also collect the transformation rules involved in each link, but it is not used in this work for the moment.
Various traceability approaches have been developed, but they are dedicated to a specific transformation language e.g. [14] or they take into account only classes and not their attributes [12]. A traceability approach has been developed [2] that is transformation language independent. We successfully used it previously considering test model improvement [3]. Each creation/modification of an element by a rule leads to the creation of a unique traceability link. Each link is a relation of three sets of elements referring to (i) a set of source elements (attribute or class instances), (ii) a set of target elements and (iii) the transformation rule that leads to this creation/modification. Each link corresponds to an execution of a rule, that may be executed several times on different input elements. Figure 8 illustrates an example. Link1 indicates that the output instance of Table has been created from one input instance of Class. Moreover, Link1 specifies that the instances it binds have been read and created by the transform rule.
Each trace captures relations between input/output models and the transformation. Traces can be analyzed independently and are not transformation language dependent.
2) Identifying non-executable input excerpt (Step 5): The trace produced from a non-executable input model is incomplete since no output model is produced. At the moment, we model a trace from a textual output of the trace in the
console of the model transformation (such as the one of the Figure 6) to obtain an analyzable trace model. In this trace, we identify the loop, which is a series of identical links. These links refer the input model elements which are involved in the loop. Therefore, we can extract from the non transformable input model an excerpt which is incorrect, such as the one illustrated Figure 4.
3) Identifying out of the scope input excerpt (Step 6): Combining the trace and the incorrect excerpt of an output model, we identify incorrect excerpt in the input model. Input excerpt of the Figure 7 corresponds to the output excerpt of the Figure 6.
C. Creating new pre-condition
Once we detect one or more input excerpt, we generalize from it an input pattern which is finally used to create a pre-condition.
1) Generalizing input excerpts identifying incorrect input pattern (Step 7): The input excerpts are extracted from concrete input models that may contain several other elements not all useful to help us make new pre-conditions. For instance, the values of name in the Figure 4 are not important: the transformation will still loop even if they are different. In other excerpts, the values of name are important like in the sample of the Figure 3, columns are identical when their names are identical (and their types are identical).
There are many properties in a model, therefore the excerpts could be all different with potentially one unique incorrect excerpt per incorrect model. We will see in the next section that they can be numerous input excerpts. Moreover, it would be ineffective to create a pre-condition for each one of them. For example, considering the excerpt of the Figure 7, it is useless to create a pre-condition preventing the creation of a model with a class exactly named "-4", with an attribute exactly named "-15", and so on.
Therefore, we generalize the input excerpts, rejecting useless properties and producing input patterns. For this, we develop the two-pass step 7. The first pass creates a pattern following two methods, the second pass controls pattern accuracy since too many properties could be rejected.
First method: We merge similar input excerpts keeping their similarities and rejecting their differences. We select subset of input excerpts to be merged based on the class and their assembly. We can use a tool such as EMF Compare which can be specialized to compare only what we are interested in.
Then each set of similar excerpts is merged, the result is a generalized pattern.
Second method: When an input excerpt doesn’t have similar excerpts to be merged with, we generate additional models. Since the objective here is to reject useless properties, we should compare several models with different properties’ values. We apply the same technique than when generating test models at the step 1. Partitioning each properties domain, we generate additional input models. Therefore they are transformed, and those which are incorrect are analyzed identifying incorrect excerpts to be merged following the first method of the previous paragraph.
For instance, we produce the incorrect input pattern illustrated Figure 9 merging the excerpts of the Figure 7 with similar incorrect patterns. We keep only the two useful properties is_persistent = False: they are always false in the merged excerpts. We identify that names and is_primary properties should not been considered since they differ in the different model excerpts which have been refined creating this input pattern.
Once we get an incorrect pattern, we should control its accuracy in a second pass. It is accurate when it contains all the necessary properties to create an effective pre-condition. Indeed, it is possible that merging rejects too many properties. One reason is that the number of generated models is limited, then useful properties combinations can be missing. Moreover, correctness of a model can depend on several properties of one model at the same time This is the case in the excerpt of the Figure 7 RDBMS invariant is violated only if both names of two different attributes are equal. However, merging this excerpt with similar excerpts would reject the properties name of Attribute, since their values are not equal between different models randomly generated per PRAMANA.
Therefore, we introduce a second pass which systematically modified in the incorrect input model the values of the properties that were in the excerpt and are no more in the pattern. The altered input models are executed, and step 3 and 4 are used to control if they are still incorrect models. Otherwise it means that the pattern is not accurate, and needs improvements.
This control is useful with the excerpt of the Figure 7. In that case, at the first pass, the merged pattern won’t consider that the attributes’ names in a model should be equals. During the control pass, the top attribute name is changed into “a1-15aa”, and the bottom attribute name is changed into “a1-15ab”. Therefore, the output model satisfies the invariant, and the input model is not incorrect anymore. A human can easily understand the problem reading the output invariant, and correct the pattern as illustrated Figure 10.
2) Writing new pre-condition (step 8): The incorrect input pattern is manually re-written to an ALLOY predicate. For instance, writing the predicate for the pre-condition G1, from the input pattern of the Figure 7
```alloy
fact noChainAssoFromClassTypeLevel1 {
all c1 : Class , assoc1 : Association |
all al1 .cl .atts | ( al .type == assoc1 .src and
assoc1 .dest == c1 ) == > ( cl . is_persistent= True or al .type .is_persistent=True )
}
```
7
We applied the methodology twelve times, obtaining twelve new pre-conditions. Synthetically, as illustrated Figure 11, we rejected 580 models at the first iteration and only 22 after the last one.
V. EVALUATION
We applied the proposed methodology on class2rdbms to discover new pre-conditions. The experiments are performed as an iterative process. During each iteration, we apply our methodology and discover one new pre-condition. We could detect several pre-conditions per iteration, however during the experiments we wanted to measure the improvement between two successive iterations. An improvement occurs when the number of incorrect input models decreases thanks to a new pre-condition. The first iteration has an initial set of three pre-conditions.
A. Experiments set-up
We generate test models for class2rdbms using PRAMANA. We generate 10 non-isomorphic CD models (using symmetry breaking [33]) for each one of the 27 predicates. This gives us a set of 270 test models.
We replicate the generation 7 times obtaining 7 sets of test models. Each set is generated using different factorial design parameters, as summarized in Table III. For each set we ask ALLOY to find models made of a different number of Class-Model, Classes, Associations, Attributes, PrimitiveDataTypes,
and we give a specific range for the integer values of the properties. We obtained 1890 input models per iteration with diversity governed by the design parameters. We generate a total of 24,570 model, applying our methodology for pre-condition discovery 12 times and generating a final set to measure the final number of incorrect models (1890 * (12+1)).
B. Discovered Pre-conditions
We discovered 12 input patterns that lead to failure of execution of a transformation and we created 12 new pre-conditions, one in each iteration. We already explained in the Approach Section (IV) how we create the pre-condition GI (Section IV-C2) which was the fourth one we made.
The appendix A of the paper synthesizes the creation of two pre-conditions among the twelve ones we created. All the experimental material is available online [24].
C. Improvements
We drove the experiments trying to reduce the number of non-transformable models first, then the number of input models transformed into incorrect output models.
Thanks to the constraint GI, we had no more non-transformable models and the dashed curve is at 0. However, we observe that new non-executable models appear then. This is due to side effect of the new pre-condition created. It is dedicated to consider one incorrect input pattern, and once the new pre-condition is applied, this pattern does not get generated anymore. But preventing such pattern, it allows PRAMANA to explore into generating other “structures” in the models using the symmetry breaking scheme in ALLOY [33]. This leads to discovery of new incorrect patterns that we have to consider for newer pre-conditions.
While the 4 first pre-conditions (C, F1, F2, G1) (Figure 1 and Appendix A) reduces the number of non-executable models, they increase the number of incorrect output models. And when the 5th pre-condition (D1) reduces the number of incorrect output models, then the number of non-transformable models increases a bit.
If we consider globally the number of incorrect models, 10 among 12 pre-conditions improve the set of test models. The pre-condition A2 and C2 are the only ones which increase the number of non transformable models. However, they fully achieve their own objectives, because each one removes the incorrect pattern they were considering.
We observe that the addition of new pre-conditions continuously leads to discovery of newer modeling patterns that are not handled by the initial specification [7] of class2rdbms produced by a group of human experts. However, we are unsure if this process of creating pre-conditions will terminate. We stop at 12 pre-conditions at the current state we still have 22 models that are not transformable correctly. Will extracting more pre-conditions from these models lead to pre-conditions that in turn lead to other types of strange and unforeseen patterns? Will this process every terminate? This is our challenge for the future.
VI. THREATS TO VALIDITY
Our framework for creating pre-conditions has 8 steps (Figure 5). While the first step is completely automatic, during our experiments the other steps still need human interaction. As explained before, generating a trace is complicated when the transformation crashed. The automation of the Step 5 and 6, identifying non transformable input excerpts, is in progress, without major difficulties. The refinement of the Step 7, producing incorrect input model patterns, can be done using EMF Compare, specializing the comparison. This step can be considered as automatic, even if we don’t yet have a framework that would launch all those comparisons. Finally the Step 8 is manual now since if require domain and modeling experts contribution. However, since those pre-conditions will be part of the specification, it is better to ensure that they are validated by a tester.
Today there is no guarantee for the minimality and generalizability of the set of all pre-conditions. However, we empirically control pattern accuracy in the second pass of Step 7. Moreover, we can test that known correct models from previous iterations of pre-condition improvement to ensure that all models that were transformed into correct output models earlier always are in the new formulation of a pre-condition.
At the end of the 13 iterations, 22 input models are still incorrect. We could have continued to iterate. However, the transformation is complex (this is the reason why we use it as a running example), and could potentially involve chains of navigation through several different classes creating complex recursive closures. In our case we approximate this recursive closure constraint by stating a maximum depth considered in the pre-conditions. For instance, F1 and F2 constraints have depth 1 and 2 (Appendix A): when F1 prevents the creation of a cycle with one association, F2 prevents the creation of a cycle with two associations. It is not possible to use the Alloy transitive closure, such as the one of the Listing 4 because an Association is a class linked to the class Class through its two properties src and dest (Figure 2(a)). Another example is the 3 input models still non transformable at the end of the experiments. They require two new pre-conditions which are evolutions of the constraint C2.
Pre-conditions discovery is done in our experiments assuming a correct model transformation. In that case, every new pre-condition rejects failed inputs as being out of the input domain. When a new pre-condition completes the specification by more precisely specifying the transformation behavior it is not yet considered. First, it implies considering the testing and debugging of the transformation. Second, it is more complicated to create a pre-condition in Alloy or OCL when it should describe a transformation behavior depending on input model properties. Both these cases will be considered in future work.
This difficulty to create some pre-conditions can be circumvented by implementing the pre-condition into the transformation as a rule/operation. Using an imperative language such as Kermeta allows it. Moreover, this limitation will complicate the testing, preventing it’s automation, but the tester can consider those constraints as soon as they are described textually even if they are not implemented. For this reason, we believe that our contribution is achieved as soon as the pre-condition is described, and even further when we can implement it.
We considered a model transformation implemented in Kermeta, nevertheless the approach is not language dependent.
VII. RELATED WORK
We have considered the testing of model transformations previously. After identifying its challenges [6], we have listed model transformations’ main operations that should be tested [24]. We successfully considered the partitioning of its input domain when testing [15]. In [9] we present an automated generation technique for models that conform only to the Ecore diagram of a meta-model specification. Finally, the tool PRAMANA consider the meta-model specification with all its constraints [30]. We have already used PRAMANA to test model transformation based on static analysis [26].
Accurately specifying the input domain of a model transformation is the problem addressed in this paper. The object constraint language (OCL) [12] is the standard to specify model transformation pre-conditions to prevent it from processing input models outside its true input domain. Model transformation developers find it intuitive to transform specific patterns in an input model to elements of the output model such as by example [35] or demonstration [44]. In [46], the authors go a step further and automate model transformation by example using inductive logic programming. In [21] the authors use a search-based technique to find transformations (from a repository) for example input models. Model transformation executability has also been explored in [11], where the authors verify transformation executability by solving pre and post conditions as a constraint program. Deciding on correct transformation rules for an input model such that its transformation is efficient and does not appear to loop is a challenge addressed in [19]. The authors present an approach based on dynamic scope discovery using a naive bayes classifier trained with rules mapped to input modeling patterns. To the best of our knowledge, the literature on specifying model transformations discusses little about identifying and handling modeling patterns that may not have been foreseen by a transformation developer. This set of input models is infinite and its impact on the transformation is unknown.
In this article, we systematically explore the potentially infinite input domain to specify a model transformation’s contracts (pre-condition in particular). We generate models that can break a model transformation’s execution by running into an infinite loop or violating a post-condition. Model generation is more general and complex than generating integers, floats, strings, lists, or other standard data structures such as dealt with in the Korat tool of Chandra et al. [8]. Korat is faster than ALLOY in generating data structures such as binary trees, lists, and heap arrays from the Java Collections Framework but it does not consider the general case of models which are arbitrarily constrained graphs of objects. The constraints on models makes model generation a different problem than generating test suites for context-free grammar-based software [23] which do not contain domain-specific constraints. Test models are complex graphs that must conform to an input meta-model specification, a transformation pre-condition and additional knowledge such as model fragments to possibly reveal violation of a post-condition or run into an infinite loop. Such a methodology using graph transformation rules is presented in [13]. Generated models in both these approaches do not satisfy the constraints on the meta-model. In [31] we presented a method to generate models given partial models by transforming the meta-model and partial model to a Constraint Logic Programming (CLP). We solve the resulting CLP to give model(s) that conform to the input domain. However, the approach does not add new objects to the model. We assume that the number and types of models in the partial model is sufficient for obtaining complete models. The constraints in this system are limited to first-order horn clause logic.
VIII. CONCLUSION
In this paper we presented an approach to discover new pre-conditions completing a model transformation’s specification. We use traceability from automatically generated test models to identify such pre-conditions. The eight-step approach helps identify incorrect input patterns in numerous and large input models. Those patterns are transformed into pre-conditions preventing input models to loop infinitely or to be transformed into incorrect output models. The experimental results show that this semi-automated approach produces pre-conditions drastically reducing the number of incorrect input models. The paper can be also interpreted as evidence of the fact that the specification of a model transformation is quite complicated to write completely, and that such a dynamic approach helps improve its completeness.
The new pre-conditions are added to the specification of a model transformation. This has helped improve specification to help a tester find bugs in the implementation and improve it. He/she can choose how the pre-conditions are used:
- He/she can choose to use the pre-condition to reduce the input domain, rejecting input models not supposed to be transformed.
- He/she can embed the pre-condition in the implementation with a behavior considering the input models’ incorrectness. For instance, it can raise an exception which will be caught properly without crashing the transformation (e.g. division by zero should raise an ArithmeticException), or implement transformation rules to process this incorrect part of an input model (e.g. ignoring this part in the output model for instance).
In future, we plan to automate generation of concise and effective ALLOY predicates directly from traces to feedback the model generation process itself. For instance, in [32], the authors have automated the completion of partial models specified in a model editor by generating ALLOY predicates from a partial model. Finally, we explore a general completion criteria to discover all possible pre-conditions in a transformation given a set of trace links as input (Figure [5] in a feedback loop of executing a transformation with every refinement of its input domain.
REFERENCES
APPENDIX
All of the experiments material is available online [24].
Here we list 2 new Alloy Preconditions F1 and F2, used to illustrate the Section VI. We also illustrate 2 iterations among the 12 ones that we processed producing 12 new preconditions.
A. Pre-conditions F1 and F2 illustrating transitive closure of different depths
// F1. No association loop between one non-persistent class
fact no1CycleNonPersistent { all a : Association | (a.dest == a.src) => a.dest_is_persistent = True }
// F2. No association loop between 2 non-persistent classes
fact no2CycleNonPersistent { all a1 : Association, a2 : Association | (a1.dest == a2.src and a2.dest == a1.src) => a1.src_is_persistent = True or a2.src.is_persistent = True }
B. Fourth Iteration: creating pre-condition G1
1) Identified non-transformable input models: Here is part of the list of the non-transformable models which have been identified during the fourth iteration.
i. model 7 created with the 4th predicate, using AllRanges strategy (mfAllRanges4), in the set 1
ii. model 4 created with the 4th predicate, using AllRanges strategy (mfAllRanges4), in the set 4
iii. model 9 created with the 3rd predicate, using AllRanges strategy (mfAllRanges3), in the set 6
2) Model of the trace: We used the trace illustrated Figure [12] to identify the non-transformable excerpt from the model iii. It lists traceabilityLinks referring the sourceElements which are transformed. We do not illustrate the transformation rules (not used in this work) and the output model element since the transformation doesn’t return any. The transformation loops on a series of two links (two on the left, then two on the right, etc.). We used them identifying the non-transformable excerpt of the Figure 4 p.5
Fig. 12. Part of the model of the trace used to identify non-transformable input excerpt from a non-transformable input model
3) Identified non-transformable input excerpt: Illustrated Figure [4] p.5
4) Refined incorrect input pattern: Illustrated Figure [9] p.8
5) New pre-condition G1 preventing generating incorrect output models: The pre-condition G1 specifies that it should be no loop type - association between 2 non-persistent classes. It is listed in Section IV-C2
C. Fifth Iteration: creating pre-condition D1
1) Identified incorrect output models: During the fifth iteration, we identified a set of incorrect output models which have been generated from incorrect input models:
I. model number 4 created with the Predicate 3, using AllPartitions strategy (mfAllPartitions3), in the set 1
II. model number 2 created with the Predicate 3, using AllPartitions strategy (mfAllPartitions3), in the set 1
III. model number 4 created with the Predicate 6, using AllRanges strategy (mfAllRanges6), in the set 4
IV. etc.
2) Model of the trace: We used the trace illustrated Figure [13] to identify the non-transformable input excerpt from the incorrect output model I.
III. model number 4 created with the Predicate 6, using AllRanges strategy (mfAllRanges6), in the set 6
5) New pre-condition D1 preventing generating incorrect output models: Listed in in Alloy and in OCL:
// D1. A class A which inherits from a persistent class B can’t have an attribute with the same name and type that one attribute of that persistent class B
fact classInheritsOutgoingNotSameNameAttrib
{
all A:Class | all B:A.parent | B.
is_persistent == True implies (no a1: A.attribs, a2:B.attribs | (a1.name=a2.name and a1.type=a2.type))
}
correct Class
self.allParents() -> includes(c1 | c1.
is_persistent) implies self.attribs -> forAll (a1 | c1.attribs -> select(a2 | a1.name = a2.name) -> isEmpty())
Fig. 13. Part of the model of the trace used to identify the incorrect input excerpt from an incorrect output model
3) Identified incorrect input excerpt producing incorrect output model: Illustrated Figure [6] p.6
4) Refined incorrect input pattern: Illustrated Figure [10] p.8
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01228715/file/issre2015MottuSen.pdf", "len_cl100k_base": 11470, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 47226, "total-output-tokens": 14097, "length": "2e13", "weborganizer": {"__label__adult": 0.0003361701965332031, "__label__art_design": 0.0004162788391113281, "__label__crime_law": 0.0002963542938232422, "__label__education_jobs": 0.001178741455078125, "__label__entertainment": 6.717443466186523e-05, "__label__fashion_beauty": 0.00016987323760986328, "__label__finance_business": 0.00024580955505371094, "__label__food_dining": 0.00028777122497558594, "__label__games": 0.0005784034729003906, "__label__hardware": 0.0006899833679199219, "__label__health": 0.0004127025604248047, "__label__history": 0.0002951622009277344, "__label__home_hobbies": 8.726119995117188e-05, "__label__industrial": 0.00042557716369628906, "__label__literature": 0.0003476142883300781, "__label__politics": 0.00023937225341796875, "__label__religion": 0.0004658699035644531, "__label__science_tech": 0.0352783203125, "__label__social_life": 9.679794311523438e-05, "__label__software": 0.007282257080078125, "__label__software_dev": 0.94970703125, "__label__sports_fitness": 0.00025916099548339844, "__label__transportation": 0.0004851818084716797, "__label__travel": 0.00019741058349609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60831, 0.02843]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60831, 0.35171]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60831, 0.87941]], "google_gemma-3-12b-it_contains_pii": [[0, 823, false], [823, 6751, null], [6751, 13009, null], [13009, 17348, null], [17348, 23562, null], [23562, 27738, null], [27738, 31079, null], [31079, 36758, null], [36758, 38048, null], [38048, 43924, null], [43924, 50711, null], [50711, 57612, null], [57612, 60831, null]], "google_gemma-3-12b-it_is_public_document": [[0, 823, true], [823, 6751, null], [6751, 13009, null], [13009, 17348, null], [17348, 23562, null], [23562, 27738, null], [27738, 31079, null], [31079, 36758, null], [36758, 38048, null], [38048, 43924, null], [43924, 50711, null], [50711, 57612, null], [57612, 60831, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60831, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60831, null]], "pdf_page_numbers": [[0, 823, 1], [823, 6751, 2], [6751, 13009, 3], [13009, 17348, 4], [17348, 23562, 5], [23562, 27738, 6], [27738, 31079, 7], [31079, 36758, 8], [36758, 38048, 9], [38048, 43924, 10], [43924, 50711, 11], [50711, 57612, 12], [57612, 60831, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60831, 0.10895]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
da3f2229ae8932d4934ad21e23b977a04ff7c442
|
COMPARISON ON CORRECTNESS, TIME TAKEN AND MEMORY USED IN WEB APPLICATIONS USING UNIT AND INTEGRATION TESTING
ELHADI ELFITORY ALGARAI
A thesis submitted in fulfillment of the requirements for the award of the Degree of Master of Computer Science (Software Engineering)
The Department of Software Engineering
Faculty of Computer Science and Information Technology
Universiti Tun Hussein Onn Malaysia
MARCH 2014
ABSTRACT
Web testing is the name given to software testing that focuses on web applications. A complete testing of a web-based system before going live can help to address issues before the system is revealed to the public. Issues such as the security of the web application, the basic functionality of the site, its accessibility to handicapped users and fully able users as well as readiness for expected traffic and number of users, and the ability to survive a massive spike in user traffic are related to load testing. This project describes the generation of various test cases for web application in two case studies by using unit testing and integration testing and the comparison in terms of Correctness, Memory Used and Time Taken. The experimental results showed the same Correctness rate for both unit and integration testing with the 80% for the case study 1 and 75% for the case study 2. Magnitude of relative error (MRE) for Time Taken using unit testing was 0.227 in case study 1 and 0.214 in case study 2. Meanwhile, for Integration testing, MRE for Time taken was 0.149 in case study 1 and 0.108 in case study 2. MRE for memory used during unit testing was 0.060 in case study 1 and 0.066 in case study 2. When using integration testing, MRE for memory used was 0.161 in case study 1 and 0.169 in case study 2. Based on the experimental results, MRE for Time taken using Integration testing is better than MRE for Time taken using Unit testing. However, the MRE for Memory used using Unit testing is better than MRE for Memory used using Integration testing.
Pengujian Web adalah nama yang diberikan kepada ujian perisian yang memfokuskan kepada aplikasi web. Ujian lengkap bagi sistem berasaskan web sebelum sistem dilancarkan boleh membantu menangani isu-isu sebelum sistem didedahkan kepada orang ramai. Isu-isu seperti keselamatan aplikasi web, fungsi asas laman web, akses kepada pengguna kurang upaya dan pengguna berupaya sepenuhnya, serta kesediaan untuk menjangkakan trafik dan bilangan pengguna dan keupayaan untuk meneruskan ledakan trafik pengguna adalah berkaitan dengan beban ujian. Projek ini menerangkan penjanaan pelbagai kes-kes ujian untuk aplikasi web dalam dua kes kajian menggunakan ujian unit dan ujian integrasi dan perbandingan dari segi (Ketepatan, Memori digunakan dan Masa yang diambil). Keputusan eksperimen menunjukkan kadar ketepatan adalah sama bagi kedua-dua ujian Unit dan ujian Integrasi dengan 80% pada kes kajian 1 dan 75% bagi kes kajian 2. Magnitud ralat relatif (MRE) untuk Masa yang diambil menggunakan ujian unit adalah 0.227 dalam kes kajian 1 dan 0.214 dalam kes kajian 2. Sementara itu, bagi ujian Integrasi MRE untuk Masa yang diambil adalah 0.149 dalam kes kajian 1 dan 0.108 dalam kes kajian 2. MRE untuk Memori yang digunakan menggunakan ujian unit adalah 0.060 dalam kes kajian 1 dan 0.066 dalam kes kajian 2. Apabila menggunakan Integrasi ujian, MRE untuk Memori yang digunakan adalah 0.161 dalam kes kajian 1 dan 0.169 dalam kes kajian 2. Berdasarkan keputusan eksperimen, MRE bagi masa yang diambil menggunakan ujian Integrasi adalah lebih baik berbanding MRE menggunakan ujian Unit. Walau bagaimanapun, MRE bagi Memori yang digunakan menggunakan Ujian unit adalah lebih baik berbanding MRE bagi Memori yang digunakan menggunakan Ujian Integrasi.
# CONTENTS
<table>
<thead>
<tr>
<th>Title</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>TITLE</td>
<td>i</td>
</tr>
<tr>
<td>DECLARATION</td>
<td>ii</td>
</tr>
<tr>
<td>DEDICATION</td>
<td>iii</td>
</tr>
<tr>
<td>ACKNOWLEDGEMENT</td>
<td>iv</td>
</tr>
<tr>
<td>ABSTRACT</td>
<td>v</td>
</tr>
<tr>
<td>ABSTRAK</td>
<td>vi</td>
</tr>
<tr>
<td>CONTENTS</td>
<td>vii</td>
</tr>
<tr>
<td>LIST OF TABLE</td>
<td>x</td>
</tr>
<tr>
<td>LIST OF FIGURES</td>
<td>xii</td>
</tr>
<tr>
<td>LIST OF SYMBOLS AND ABBREVIATIONS</td>
<td>xii</td>
</tr>
</tbody>
</table>
## CHAPTER 1 INTRODUCTION
1.1 Background of Study
1.2 Problem Statement
1.3 Project Objectives
1.4 Scope of Project
1.5 Thesis Outline
## CHAPTER 2 LITERATURE REVIEW
2.1 Introduction
2.2 Software Testing
2.2.1 Web Application Testing
2.2.2 Automated Testing
2.2.3 Unit Testing
2.2.4 Integration Testing
2.3 Selenium Tool
2.3.1 Selenium components
2.3.2 Performing the Unit and Integration with Selenium
CHAPTER 3 METHODOLOGY 18
3.1 Introduction 18
3.2 Flow Chart of the Project Work 19
3.3 Creating two Case Studies 20
3.4 Application Unit and Integration Testing in Two Case Study 20
3.4.1 Test Cases for Integration Testing in SISPEK System 20
3.4.2 Test Cases for Unit Testing in SISPEK System 25
3.5 Application Unit and Integration Testing in Two Case Study 26
3.5.1 Test cases for Integration Testing in Woodman 27
3.5.2 Test cases for Unit Testing in Woodman 31
3.6 Results Analysis 33
3.7 Summary 33
CHAPTER 4 IMPLEMENTATION & RESULTS ANALYSIS 34
4.1 Introduction 34
4.2 Implementation for Unit and Integration in Two Case Studies 34
4.2.1 Implementation of Test Cases for Unit in SISPEK 34
4.2.2 Implementation Test cases for Integration in SISPEK 40
4.2.3 Implementation of Unit Testing Cases for Woodman 45
4.2.4 Implementation for Integration in Woodman 51
4.3 Analysis of the Result in Two Case Studies 56
4.3.1 Magnitude of relative error (MRE) 56
4.3.2 Analysis of the results in SISPEK System 57
4.3.3 Analysis of the results in Woodman System 69
4.4 Summary 82
CHAPTER 5 CONCLUSIONS 83
5.1 Objectives Achievement 83
5.2 Conclusion 84
5.3 Future Work 83
REFERENCES 85
VITA 88
LIST OF TABLE
4.1 Test cases in SISPEK using Unit testing 35
4.2 Experiment results for Test Login using Unit testing in SISPEK 36
4.3 Results for Test Creating Student using Unit testing in SISPEK 37
4.4 Experiment results for Test Updating Student using Unit in SISPEK 37
4.5 Experiment results for Test Deleting Student using Unit testing in SISPEK 38
4.6 Experiment results for Test Creating Asset using Unit testing in SISPEK 38
4.7 Experiment results for Test Updating Asset using Unit testing in SISPEK 39
4.8 Experiment results for Test Deleting Asset using Unit testing in SISPEK 39
4.9 Experiment results for Test View Student using Unit testing in SISPEK 39
4.10 Experiment results for Test View Student using Unit testing in SISPEK 40
4.11 Experiment results for Test Login using Integration testing in SISPEK 42
4.12 Experiment results for Creating Student using Integration in SISPEK 42
4.13 Experiment results for Updating Student using Integration in SISPEK 43
4.14 Experiment results for Deleting Student using Integration in SISPEK 43
4.15 Experiment results for Test Creating Asset using Integration in SISPEK 44
4.16 Experiment results for Test Updating Asset using Integration in SISPEK 44
4.17 Experiment results for Test Deleting Asset using Integration in SISPEK 45
4.18 Experiment results for Test View Student using Integration in SISPEK 45
4.19 Test cases in Woodman using Unit testing 46
4.20 Experiment results for Test Login using Unit testing in Woodman 47
4.21 Experiment results for Test View User using Unit testing in Woodman 48
4.22 Experiment results for Creating User using Unit testing in Woodman 48
4.23 Experiment results for Updating User using Unit testing in Woodman 49
4.24 Experiment results for Deleting User using Unit testing in Woodman 49
4.25 Experiment results for Test Creating Supervisor using Unit in Woodman 50
4.26 Experiment results for Test Updating Supervisor using Unit in Woodman 50
4.27 Experiment results for Test Deleting Supervisor using Unit in Woodman 50
4.28 Test cases in Woodman using Integration testing
4.29 Experiment results for Test Login using Integration testing in Woodman
4.30 Experiment results for Test View User using Integration in Woodman
4.31 Experiment results for Test Creating User using Integration in Woodman
4.32 Experiment results for Test Update User using Integration in Woodman
4.33 Experiment results for Test Deleting User using Integration in Woodman
4.34 Results for Test Creating Supervisor using Integration in Woodman
4.35 Experiment results to Updating Supervisor using Integration in Woodman
4.36 Experiment results to Deleting Supervisor using Integration in Woodman
4.37 Experiment results in terms of Correctness using Unit testing in SISPEK
4.38 Experiment results in terms of Correctness using Integration in SISPEK
4.39 Experiment results in terms of Time Taken using Unit testing in SISPEK
4.40 Experiment results in terms of Time Taken using Integration in SISPEK
4.41 Experiment results in terms of Memory used using Unit in SISPEK
4.42 Experiment results in terms of Memory using Integration in SISPEK
4.43 Criteria in SISPEK System
4.44 Experiment results in terms of Correctness using Unit in Woodman
4.45 Experiment results in terms of Correctness using Integration in Woodman
4.46 Experiment results in terms of Time Taken using Unit in Woodman
4.47 Experiment results in terms of Time Taken using Integration in Woodman
4.48 Experiment results in terms of Memory used using Unit in Woodman
4.49 Experiment results in terms of Memory using Integration in Woodman
4.50 Criteria in Woodman Estate System
# LIST OF FIGURES
<table>
<thead>
<tr>
<th>Figure</th>
<th>Description</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>2.1</td>
<td>Simplified Architecture Diagram</td>
<td>9</td>
</tr>
<tr>
<td>2.2</td>
<td>Display output of test case using Selenium Tool</td>
<td>11</td>
</tr>
<tr>
<td>3.1</td>
<td>Flow Chart the steps of the project work</td>
<td>19</td>
</tr>
</tbody>
</table>
## LIST OF SYMBOLS AND ABBREVIATIONS
<table>
<thead>
<tr>
<th>Abbreviation</th>
<th>Full Form</th>
</tr>
</thead>
<tbody>
<tr>
<td>SISPEK</td>
<td>SistemPendaftaranPerkakasanElektrikPelajar</td>
</tr>
<tr>
<td>Woodman</td>
<td>SistemPemantauanPekerjaAsing</td>
</tr>
<tr>
<td>MM-path</td>
<td>Method-Message Path</td>
</tr>
<tr>
<td>HTTP</td>
<td>Hypertext Transfer Protocol</td>
</tr>
<tr>
<td>SBST</td>
<td>Search Based Software Testing</td>
</tr>
<tr>
<td>MRE</td>
<td>Magnitude of Relative Error</td>
</tr>
<tr>
<td>I&T</td>
<td>Integration Testing</td>
</tr>
</tbody>
</table>
CHAPTER 1
INTRODUCTION
1.1 Background of Study
Testing is a major component of any software engineering process meant to produce high quality applications. The testing aims at finding errors in the tested object and give confidence in its accurate performance by executing the tested object with input values. Web applications are the fastest growing classes of software systems today. They are being used to support a wide range of important activities: business transaction, scientific activities (information sharing), and medical systems (an expert system-based diagnoses). Web applications have been deployed at a fast pace and have helped in fast adoption, but have also decreased the quality of the software. Therefore, all the entities of web application must be tested. In order to make a web based application widely and successfully adopted, the testing methodologies must be flexible, automatic, and able to handle their dynamic nature (Arora & Sinha, 2012).
Unit testing is a method by which the individual units of source code, the sets of one or more computer program modules, together with the associated control data, usage procedures, and operating procedures are tested to determine if they are fit for use (William & Nathaniel, 2011).
At a high-level, unit testing refers to the practice of testing certain functions and areas or units of the code. This enables the ability to verify that the functions work as expected. That is to say that for any function and a given set of inputs, it can be determined if the function is returning the proper values. If it will gracefully handle failures during the course of execution invalid input should be provided.
Ultimately, this helps to identify failures in the algorithms and/or logic to help improve the quality of the code that composes a certain function. As more and more tests were being written, it ended up creating a suite of tests that can run at any time during development to continually verify the quality of the work.
A second advantage to approaching development from a unit testing perspective is that, a code that is easy to test will be written. Since the unit testing requires that the code is easily testable, it means that the code must support this particular type of evaluation. As such, it is more likely to have a higher number of smaller, more focused functions that provide a single operation on a set of data rather than having large functions that perform a number of different operations.
A third advantage for writing solid unit tests and well-tested code is that future changes from the breaking functionality can be prevented. Since the code is being tested as the functionality is being introduced, a suite of test cases will start to develop that can be run each time the logic is being worked on. When a failure happens, it is known that there is something used to address the Integration test (Zhiyong et al., 2012).
Integration testing (sometimes called integration and testing, abbreviated I&T) is the phase in software testing where individual software modules are combined and tested as a group. It occurs after unit testing, before validation testing. Integration testing takes as its input modules that have been unit tested and teamed in larger aggregates, then the defined tests are applied in an integration test plan on those aggregates, and the integrated system is delivered as its output that is ready for system testing (Sacha et al., 2010).
Integration testing is a logical extension of unit testing. In it’s the simplest form; two units that have already been tested are combined into a component and the interface between them is tested. A component, in this sense, refers to an integrated aggregate of more than one unit. In a realistic scenario, many units are combined into components, which in turn, aggregated into even larger parts of the program. The idea is to test combinations of pieces and eventually expand the process to test the modules with other groups. Eventually, all the modules making up a process are tested together. Beyond that, if the program is composed of more than one process, they should be tested in pairs rather than all at once (Sebastian, 2009).
Integration testing identifies problems that occur when units are combined by using a test plan that requires to testing each unit and ensuring the viability of each
before combining units. Any errors that are discovered when combining units are likely related to the interface between units. This method reduces the number of possibilities to a far simpler level of analysis (Giuseppe & Di, 2012).
1.2 Problem Statement
The wide diffusion of the Internet has produced a significant growth demand of Web-based applications with stricter requirements of reliability, usability, interoperability, and security. Due to market pressure and very short time-to-market, the testing of Web-based applications is often neglected by developers as too time consuming and lacks a significant payoff (Giuseppe & Di, 2012). This depreciable habit affects negatively the quality of the applications and, therefore, it triggers the need for adequate, efficient, and cost effective testing approaches for verifying and validating them. Though the testing of Web-based applications shares the same objectives of ‘traditional’ application testing, in most cases, traditional testing theories and methods cannot be used just as they are because of the peculiarities and complexities of Web applications. Indeed, they have to be adapted to the specific operational environment and new approaches for testing them are needed (Edward & Robert, 2011). The aim of Web application testing consists of executing the application using combinations of input and state to reveal failures. A failure is the manifested inability of a system or component to perform a required function within specified performance requirements (Ye, 2011). There are many techniques used to test web applications such as Unit testing and Integration testing. Unit Testing is a level of the software testing process where individual units/components of a software/system are tested. The purpose is to validate that each unit of the software is performs as designed (Per, 2006). Integration testing is the testing applied when all the individual modules are combined to form a working program. Testing is done at the module level, rather than at the statement level as in unit testing. Integration testing emphasizes the interactions between modules and their interfaces (Manar & James, 2010). The project is the generation of various test cases using unit testing and integration testing for web applications in two case studies. The results for Unit and Integration testing were compared using performance parameters (Correctness, Memory Used and Time Taken).
1.3 **Project Objectives**
The objectives of this research are:
(i) To generate test cases for web application using integration technique in two case studies; Sistem Pemantauan Pekerja Asing Woodman Estate Sarawak and Sistem Pendaftaran Perkakasan Elektrik Pelajar KKTDT (SISPEK).
(ii) To generate test cases for web application using Unit technique in two case studies; Sistem Pemantauan Pekerja Asing Woodman Estate Sarawak and Sistem Pendaftaran Perkakasan Elektrik Pelajar KKTDT (SISPEK).
(iii) To compare the results are using performance parameters (Correctness, Memory Used and Time Taken) in web application using unit and integration testing for the two case studies.
1.4 **Scope of Project**
This study focuses on the problem of web application testing. Therefore, various methodologies are proposed to Web application testing. The integration and Unit techniques are used to test a Web application. These two testing techniques (Correctness, Memory Used and Time Taken) of Web application testing will be compared using integration and unit for the two case studies.
1.5 **Thesis Outline**
This thesis consists of five chapters. Chapter 1 is an overview and main objectives of the project. It consists of the scope of work covered and the objectives of the project. Chapter 2 illustrates the literature review of unit and integration testing and brief explanation in general information on the automated testing for enterprise systems in this project. Chapter 3 discusses the methodology and tools to obtain the entire objectives of this project. Chapter 4 explains the implementation and detailed steps used in this work. Chapter 5 includes the objectives achieved, disadvantages, future work, and conclusion.
CHAPTER 2
LITERATURE REVIEW
2.1 INTRODUCTION
The overall goals of this chapter are establishing the significance of the general field of study. The greater part of this chapter is about critical evaluation of different methodologies used in this field so as to identify the appropriate approach for investigating objectives of the project.
2.2 Software Testing
Software testing is a costly and time-consuming process but is essential if a high quality product is to be produced. The importance of software testing and establishment of good testing skills must begin as early as possible in computing curricula complementing programming skills. Various techniques exist for test design and execution, Some tests do not involve running the system at all, some require inside knowledge of how the system works, some run step by step by the tester, while in other cases, a computer does the test execution, though skilled test engineers must perform the test design and results interpretation, automated testing or testing using simulators (Jim & Kalpana, 2005).
2.2.1 Web Application Testing
Three related algorithms and a tool, are introduced for automated web application testing using Search Based Software Testing (SBST). The algorithms significantly
enhance the efficiency and effectiveness of traditional search-based techniques, which exploit both static and dynamic analysis. The combined approach yields a 54% increase in branch coverage and a 30% reduction in test effort. Each improvement is separately evaluated in an empirical study on 6 real world web applications (Nadia, 2011).
Models are considered essential steps in capturing different system behaviours and simplifying the analysis that is required to check or improve the quality of software. The verification and testing of web software require effective modelling techniques that address the specific challenges of web applications. In this study, 24 different modelling methods were used in web site verification and testing was measured. Based on a short catalogue of desirable properties of web applications that require analysis, two different views of the methods are presented: a general categorization by modelling level, and a detailed comparison based on property coverage (Nadia, 2011).
2.2.2 Automated Testing
Trends are in an automated testing for enterprise systems. The results of an industry market research survey commissioned by Work soft Inc. were presented and performed by an independent third party to study the state of test automation in operating companies. The results include responses from 699 respondents at 504 companies, primarily located in North America and Europe, and most with annual revenues greater than $500 million USD. The overwhelming majority (93.4%) are companies that use SAP, although a small number use other packaged software as their primary ERP system (Reiner, 2013).
2.2.3 Unit Testing
Unit testing is defined as the testing of a single unit, separated from other units of the program (Eklun & Fernlund, 1998).
Sometimes, when the units are strongly interdependent, a unit must be tested together with all units that the first unit depends on (Lindegren & Hakan, 2003).
In object-oriented development process, a unit is normally a class or an interdependent cluster of classes, i.e. it’s not just a snapshot or a script of code that does some specific work (Binder & Robert, 1999).
The testing of the lower levels of a system (i.e. the unit testing) will require highly technical testers. Also, low-level testing is a difficult, time-consuming and expensive task to be accomplished (Hutcheson & Marnie, 2003). Less and less low-level testing is done in top-down approaches to software development, arguing that “if the system seems to give the correct response to the user, why look any further in favor of unit testing. It has been recognised that “the problem is that the really tough, expensive faults often reside in the lower-level areas (Hutcheson & Marnie, 2003).
Another argument for performing unit testing for the software verification is that the unit testing will localize the faults found to the unit tested. If unit testing is not performed, faults found later during integration testing of the system may lead to time-consuming work because there are too many places to look for the faults (Patton & Ron, 2001).
Unit testing will help in removing local faults, but does not exercise the interactions among different units, whereas Integration testing is the activity of exercising such interactions by pulling together the different modules composing a system. It is characterized by involving different interacting units, which have been, in general, developed by different programmers. In this case the code is still visible, but with higher granularity (Alessandro, 2006).
### 2.2.4 Integration Testing
A technique defined (regarding both the unit testing and the integration testing test cases) for reducing the combinatorial explosion of the number of test cases for covering all combinations of polymorphic caller, callee, parameters, and related states. The technique is based on latin squares: a set of specific orthogonal arrays used to identify the subset of combinations of the state of each object and its dynamic type to be tested. The method ensures coverage of all pairwise combinations. It applies to single calls, but does not consider the combined effects of different calls (McGregor & Korson, 1994).
A pairwise integration approach is described based on the relationships between the system classes, and a heuristic method for selecting test cases based on
the states of objects. The method allows for identifying some infeasible combinations, and hence, limiting the number of generated test cases for integration testing, focusing on the integration order (Paradkar, 1996).
The notion of method-message path (MM-path) has been introduced, and defined as a sequence of method executions linked by messages. For each identified MM-path, integration is performed by pulling together classes involved in the path and exercising the corresponding message sequence. More precisely, Jorgensen and Erickson identify two different levels for integration testing:
(i) Message quiescence: This level involves testing a method together with all methods it invokes, either directly or transitively (McGregor & Korson, 1994).
(ii) Event quiescence: This level is analogous to the message quiescence level, with difference that it is driven by the system level events. Testing at this level means exercising message chains (threads), such as the invocation of the first message of the chain is generated at the system interface level (i.e., the user interface) and, analogously, the invocation of the last message results in an event that can be observed at the system interface level. An end-to-end thread is called an atomic system function (Jorgensen & Erickson, 1994).
The main drawback of this method is the difficulty in the identification of ASFs, which requires either the understanding of the whole system or an analysis of the source code (Jorgensen & Erickson, 1994).
A methodology called wave front integration is described, based on a specific development technique. Developers reach an agreement on the functionality to be achieved for each component during each integration process. To achieve such functionality, all involved classes must provide a subset of their features. Therefore, development proceeds across all of the classes at the same time. This methodology can be considered a variation of the threads integration strategies, characterised by development and testing being tightly coupled. The main drawback of this approach is that it requires much communications among different teams. Its main advantage is the little need for scaffolding (McGregor & Korson, 1994).
2.3 Selenium Tool
Selenium is a portable software testing framework for web applications. It provides a record/playback tool for authoring tests without learning a test scripting language (Selenium IDE). It also provides a test domain-specific language (Selenese) to write tests in a number of popular programming languages including Java, C#, Groovy, Perl, PHP, Python and Ruby. The tests can then be run against most modern web browsers. Selenium deploys on Windows, Linux, and Macintosh platforms (Alan, 2010).
2.3.1 Selenium components
The Selenium Server, which launches and kills browsers, interprets and runs the Selenese commands passed from the test program, and acts as a HTTP proxy, intercepting and verifying HTTP messages passed between the browser and the AUT. Client libraries provide the interface between each programming language and the Selenium Server. Figure 3.1 displays a simplified architecture diagram.

The diagram shows that the client libraries communicate with the server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command. This runs the selenese action or verification specified in test script (Roy, 2012).
2.3.2 Performing the Unit and Integration Testing with Selenium
The generation of the test cases to unit testing is by writing the code compiler inside the first case study, as well as generation of the test cases to unit testing by writing the code compiler inside the second case study. Generation of test cases to integration testing is also by writing the code compiled inside first case study, and generation of the test cases to integration testing by writing the code compiled inside the second case study. All test cases executed are as follow:
(i) The Client driver will first establish a connection with the Selenium server.
(ii) The Selenium Server will do the following:
- It will create a session for that particular request.
- It will launch the desired browser (specified in the code IE, FF, Chrome).
- Loads the Selenium cores JavaScript file into specified browser (So as the selenium server will have to handle with the webpage for performing the Selenese action).
(iii) Now the Client driver will send the program that have been written in eclipse IDE as selenese (by making conversion) and send it to Selenium server.
(iv) The Selenium server is intelligent enough to understand the selenese command and triggers the corresponding JavaScript execution in the web browser.
(v) Here the Selenium Server act as a “Proxy Server” between the AUT (Application under Test) and actual browser, due to the restriction of “Same origin policy”. Selenium server performs “Proxy Injection”. Being a proxy gives the Selenium Server the capability of “lying” about the AUT’s real URL.
(vi) Now, the Selenium server requests the actual webserver for the page open request and, then, it receives the page and sends it to the browser.
(vii) Now, any operation or request that the browser makes will eventually pass through Selenium RC server to the actual webserver and vice versa.
At the end of the testing process, the selenium tool will display the following on the screen: correctness, time taken and memory (Alan, 2010).

2.4 Testing Challenges
The integration testing challenges are described, as the size of Web applications are growing due to the involvement of new emerging process like business processes and highly secure requirements from customers. The existing integrated solutions are the cheapest and the fastest way to develop such kinds of large Web-based applications. But testing of such application is a complex task due to its large size, integration of multilingual components, and use of different operating systems. The most important and commonly known challenges during integration testing are:
2.4.1 Inconsistent Infrastructure and Environment
Web-based applications consist of a number of different heterogeneous components and run on diverse environment. It means heterogeneity is one of the key features of Web-based applications; heterogeneity may introduce the incompatibilities between different programming languages, databases, different operating systems and external operational environments involved in development and deployment of Web-based applications. Complex integrated solutions consist of different software components, which are developed by using different programming languages and technologies. The assurance of compatibility and interoperability between these components is one of major concerns during the testing process (Jerry et al., 2003).
2.4.2 Inconsistent Interaction Models
Web-based applications are based on number of different Web components, which are developed by a different group of teams with the use of different methods and approaches; in complex Web-based applications, control protocols and data models play key role in the reliable communication and interaction among different integrated subsystems. Control protocols are responsible for defining the rules on how integrated components interact to each other. Data models define the contents and format of communication between them. Since Web-based applications can be based on a number of different components, most of the time, different groups of developers are involved in development process (Jerry et al., 2003).
2.4.3 Distributed Nature of Systems
Web-based applications are mostly developed under distributed environments, so the issues related to distributed systems, such as race condition and dead lock can be inherited. The distributed nature of systems can have a great impact on the working of Web-based applications, these issues can be solved during the integration testing. The existence of more than one version of the same software component generates multi version issues in the system (Jerry et al., 2003).
2.4.4 Performance and Reliability Issues due to Heterogeneity
The testing of Web-based application and assurance of key quality feature are challenging for the testing team to achieve the guarantee of these features required in most of the testing effort. Performance and reliability are the key quality features that can affect the overall working and presentation of Web application. The assurance of this quality feature also produce a good impact on customers and users of Web application. Heterogeneity allows integration of different subsystems or components that are developed in different programming languages, under different platforms and environments that can be achieved through standardization. The process of standardization produces the extra overhead during communication of components and this overhead causes the degradation of performance and reliability of the whole application (Jerry et al., 2003).
2.4.5 Interoperability
Interoperability is the ability of two or more systems, applications or components to exchange information and to use the information that has been exchanged. Interoperability itself is a critical testing challenge, which has further challenging factors and characteristics (Jerry et al., 2003).
2.5 Performance Parameters for Testing
When a program is implemented to provide a concrete representation of an algorithm, the developers of this program are naturally concerned with the correctness and performance of the implementation. Software engineers must ensure that their software systems achieve an appropriate level of quality. Software verification is the process of ensuring that a program meets its intended specification. One technique that can assist during the specification, design, and implementation of a software system is software verification through correctness proof. Software testing, or the process of assessing the functionality and correctness of a program through execution or analysis, is another alternative for verifying a software system (Gregory, 2008).
When performance is important, as it often is, we also need to choose an algorithm that runs quickly and uses the available computing resources efficiently. We are thus led to consider the often subtle matter of how we can measure the time taken of a program or an algorithm, and what steps can we take to make a program run faster. There are different test case design methods in practice today. These test case design methods need to be part of a well-defined series of steps to ensure successful and effective software testing. This systematic way of conducting testing saves time, effort and increases the probability of more faults being caught. These steps highlights when different testing activities are to be planned i.e. effort, time and resource requirements, criteria for ending testing, means to report errors, and evaluation of collected data. The schedule for accomplishing testing milestones is also included, which matches the time allocation in the project plan for testing. It is important that the schedule section reflect how the estimates for the milestones were determined, the failing test case is re-run along with other related test cases so as to be sure that the bug fix has not adversely affected the related functionality. This
practice helps in saving time and effort when executing test cases with higher probability of finding more failures, the test execution process involves allocating test time and resources, running tests, collecting execution information and measurements and observing results (Wasif, 2007).
There are two major groups of experimental evaluations for Memory Used: performance evaluation and semantic evaluation (debugging/testing/verification). The biggest challenge for performance evaluation of memories used is to propose benchmarks that are precise enough to emphasize Memory characteristics, but also realistic enough to match the behavior of common applications, Performance tests are generally longer than unit tests since they execute complex schedules to measure the performance of a Memory. More precisely, they use randomization and loops to test a large set of schedules (Derin et al., 2008).
### 2.6 Magnitude of Relative Error (MRE) for Performance Parameters
To illustrate the problem of MRE, let us consider two prediction models A and B, respectively. If MRE of model B is significantly lower than MRE of model A, one would conclude that model B is better than model A (B is “more accurate” than A in current software engineering terminology). To be able to draw the correct conclusion with regard to whether model A or model B is the best, it is crucial that the model evaluation metric selects the model that is closest to the true, Consider MRE ≤ 0.25 as acceptable for prediction models, and to get MRE follow the equation (Tron et al., 2002).
\[
MRE = \frac{1}{N} \sum_{i=1}^{n} \frac{|Y - Y_i|}{Y_i}
\]
(2.1)
where
- \(N\): Number of Values.
- \(Y\): Predicted Value.
- \(Y_i\): Actual Value.
2.7 Related Work
Several researchers have investigated many topics on the effectiveness and the efficiency of the regression testing (for both integration and unit testing) as summarized in the recent survey. While there is a large amount of work related to our thesis, only the most related topics on generated automated testing have been reviewed and discussed (Yoo & Harman, 2010).
An automated approach for testing JavaScript web applications has been described and implemented in the tool Kudzu. It combines the use of random test generation to explore the application’s event space (i.e., the possible sequences of user-interface actions) with the use of symbolic execution for systematically exploring an application’s value space (i.e., how the execution of control flow paths depends on input values). The main goal of their work is to find code injection vulnerabilities that result from untrusted data provided as arguments to, for example, eval. The symbolic execution part relies on an elaborated model for reasoning about string values and string operations (Saxena & Akhawe, 2010).
The dynamic analysis has been described to construct a state-flow graph that models the states of an AJAX application’s user-interface and transitions between these states. From this model, a set of equivalent static pages can be generated that can be used for various applications (e.g., applying search engines to their content, performing state-based testing). Crawljax relied on a heuristically-based approach for detecting “clickables”, i.e., elements of the DOM that may correspond to active user-interface components, and crawls the application by exercising these clickables in some random order (Mesbah & Bozdag, 2008).
A tool, which relies on Crawljax to create a model of the state space of an AJAX application is described. It can check this state space model for a number of common problems, including DOM invariants such as: situations where the application causes the HTML DOM to be malformed, situations where the DOM contains error messages such as “404 Not Found” and state machine invariants such as dead clickables (corresponding to URLs that are permanently unavailable) and situations where pressing the browser’s back-button results in inconsistent behavior (Mesbah & Van, 2009).
A framework for Automated Testing of JavaScript Web Applications is introduced. The framework was aimed for feedback directed testing of JavaScript applications. The framework in a tool called Artemis has been implemented and it created several effective test generation algorithms by instantiating the framework with different prioritization functions and input generators that employ simple feedback mechanisms, the experimental results described stated that the basic algorithm, events, produces good coverage (69% on average) if enough tests are generated. However, if test generation is directed by coverage information and read-write sets, a slightly better level of coverage (72% on average) can be achieved, and sometimes with lesser tests (Shay & Julian, 2011).
### 2.8 Summary
This chapter reviewed software testing and previous related works regarding testing techniques, and Selenium tool. The next chapter will look into research methodology of the study.
CHAPTER 3
METHODOLOGY
3.1 INTRODUCTION
This chapter discusses the methodology of this project. This chapter presents the preliminary knowledge, in order, to apply the Selenium tool for unit and integration testing in two case studies. Next, this section explains the research activities and all main phases in this project. Finally, all the steps of the application of the Selenium tool for the integration and unit testing are presented.
3.2 Flow Chart of the Project Work
Based on Figure 3.1, four phases are needed for applying Unit and Integration testing in two Case studies. They are 4 phases in the creating of two web application using the Yii Framework then using Unit testing and Integration testing in two Case studies. These phases are further discussed in the following sections.
3.3 Creating two Case Studies
The case studies are the building of two web applications using the Yii framework (Student Registration System, and Woodman Estate System).
(i) First Case Study
The first system is the SISPEK (Hamiza, 2013) is mainly aimed to register the students’ and the assets’ information, in order to be used later to track the assets of the students.
(ii) Second Case Study
The second system, Woodman Estate (Nor, 2013), is mainly aimed to register the users, supervisors and workers’ information, in order to be used to track the workers expiration date.
3.4 Application of Unit and Integration Testing in Two Case Study 1
In this section, the steps applied to the automated Integration and Unit testing by Selenium is explained in SISPEK.
3.4.1 Test Cases for Integration Testing in SISPEK System
There are eight (8) test cases for integration testing in SISPEK System. These eight test cases are: Login, Creating Student, Updating Student, Deleting Student, Creating Asset, Updating, Asset Deleting Asset and View User. They are discussed in the follows subsections.
3.4.1.1 Login Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Ensure that the login page is opened by ensuring that the text “Login Admin/Staff” is available in the page.
(iii) Ensure that the login page contains an input field for the username.
(iv) Type “admin” in the username field.
(v) Try to login by pressing on the login submit button.
(vi) Ensure that the web application showed an error that the password can’t be blank.
(vii) Type “admin123” in the password field.
(viii) Try to login again by pressing on the login submit button.
(ix) Ensure that the message “Password cannot be blank” has gone.
(x) Ensure that the web application has redirected the user to the home page that contains the logout link.
(xi) Run test case above with Selenium.
(xii) After applying the correct case, the errors in this test scenario were created (e.g. rename the field username to user_name).
3.4.1.2 Create Students Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Type “admin” in the username field.
(iii) Type “admin123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “Create Student”.
(vi) Ensure that the creation form includes the appropriate elements and then fill them.
(vii) Click on the submit button “Create”.
(viii) Ensure that the system is created correctly and has redirected to the View Student page.
(ix) Run test case above with Selenium.
(x) After applying the correct case, the errors in this test scenario were created (e.g. rename the field full_name to fullname).
### 3.4.1.3 Updating Students Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Type “admin” in the username field.
(iii) Type “admin123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “List Students”.
(vi) Click on the link “Update” link.
(vii) Enter some new values.
(viii) Click on the “Save” button.
(ix) Ensure that the system updated the student correctly and has redirected to the view student page.
(x) Run test case above with Selenium.
(xi) After applying the correct case, the errors in this test scenario were created (e.g. rename the field full_name to fullname).
### 3.4.1.4 Deleting Students Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Types “admin” in the username field.
(iii) Types “admin123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “List Students”.
(vi) Ensure that the student ’Muhammad Rabeeh Saeed’ is existed.
(vii) Click on the first delete link.
(viii) Ensure that the student ’Muhammad Rabeeh Saeed’ is no longer existed.
(ix) Run test case above with Selenium.
(x) After applying the correct case, the errors in this test scenario were created (e.g. rename the link Delete to delete_student).
3.4.1.5 Create Asset Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Type “staff” in the username field.
(iii) Type “staff123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “Create Asset”.
(vi) Ensure that the creation form includes the appropriate elements and then fill them.
(vii) Click on the submit button “Create”.
(viii) Ensure that the system created the asset correctly and has redirected to the view asset page.
(ix) Run test case above with Selenium.
(x) After applying the correct case, the errors in this test scenario were created (e.g. rename the field cateogry to asset_cateogry ).
3.4.1.6 Updating Asset Test
The integration test case steps are as the following:
(i) Open the web application and clicks the login link.
(ii) Type “staff” in the username field.
(iii) Type “staff123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “List Assets”.
(vi) Click on the link “Update” link.
(vii) Enter some new values.
(viii) Click on the “Save” button.
(ix) Ensure that the system updated the asset correctly and has redirected to the view asset page.
(x) Run test case above with Selenium.
(xi) After applying the correct case, the errors in this test scenario were created (e.g. rename the field cateogry to asset_cateogry).
3.4.1.7 Deleting Asset Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Type “staff” in the username field.
(iii) Type “staff123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “List Assets”.
(vi) Ensure that the asset 'USB Flash’ is existed.
(vii) Click on the first delete link.
(viii) Ensure that the asset 'USB Flash' is no longer existed.
(ix) Run test case above with Selenium.
(x) After applying the correct case, the errors in this test scenario were created (e.g. rename the link delete to delete_asset).
3.4.1.8 View Student Test
The integration test case steps are as the following:
(i) Open the web application and click the login link.
(ii) Type “admin” in the username field.
(iii) Type “admin123” in the password field.
(iv) Try to login by pressing on the login submit button.
(v) Click on the link “List Students”.
(vi) Click on the link “view” link.
(vii) Enter some new values.
(viii) Click on the “View” button.
(ix) Ensure that the system updated the student correctly and has redirected to the view student page.
(x) Run test case above with Selenium.
(xi) After applying the correct case, the errors in this test scenario were created (e.g. rename the field full_name to fullname).
REFERENCES
Hong Zhu, Xudong He. (2001). A Study of Integration Testing and Software Regression at the Integration Level. Department of Computer Engineering and Science Case Western Reserve University Cleveland, Ohio 44106.
Patton, Ron. (2001). Software testing. 800 E. 96th St., Indianapolis, Indiana, 46240 USA.
Sanjeev Patwa and Anil Kumar Malviya. (2012). Reusability Metrics and Effect of Reusability on Testing of Object Oriented Systems. *FASC, MITS (Deemed University), Lakshmangarh,Sikar, Raj., India.*
William Pugh, Nathaniel Ayewah. (2011). Unit Testing Concurrent Software. *Dept. of Computer Science Univ. of Maryland College Park, MD.*
|
{"Source-Url": "http://eprints.uthm.edu.my/6148/1/ELHADI_ELFITORY_ALGARAI_24.pdf", "len_cl100k_base": 10806, "olmocr-version": "0.1.50", "pdf-total-pages": 36, "total-fallback-pages": 0, "total-input-tokens": 71988, "total-output-tokens": 13629, "length": "2e13", "weborganizer": {"__label__adult": 0.0003910064697265625, "__label__art_design": 0.0004546642303466797, "__label__crime_law": 0.000362396240234375, "__label__education_jobs": 0.0067596435546875, "__label__entertainment": 8.165836334228516e-05, "__label__fashion_beauty": 0.0002005100250244141, "__label__finance_business": 0.0002486705780029297, "__label__food_dining": 0.0003466606140136719, "__label__games": 0.0007801055908203125, "__label__hardware": 0.0006499290466308594, "__label__health": 0.0004222393035888672, "__label__history": 0.0002880096435546875, "__label__home_hobbies": 0.00010091066360473631, "__label__industrial": 0.0002772808074951172, "__label__literature": 0.0004584789276123047, "__label__politics": 0.00021541118621826172, "__label__religion": 0.0003733634948730469, "__label__science_tech": 0.01165771484375, "__label__social_life": 0.00015676021575927734, "__label__software": 0.0083465576171875, "__label__software_dev": 0.966796875, "__label__sports_fitness": 0.0002727508544921875, "__label__transportation": 0.00039315223693847656, "__label__travel": 0.0002007484436035156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54733, 0.04182]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54733, 0.48954]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54733, 0.85419]], "google_gemma-3-12b-it_contains_pii": [[0, 413, false], [413, 1991, null], [1991, 3732, null], [3732, 4811, null], [4811, 5872, null], [5872, 6005, null], [6005, 8029, null], [8029, 9627, null], [9627, 9991, null], [9991, 10623, null], [10623, 12305, null], [12305, 14998, null], [14998, 17444, null], [17444, 19175, null], [19175, 20434, null], [20434, 22378, null], [22378, 24806, null], [24806, 27037, null], [27037, 28015, null], [28015, 30140, null], [30140, 31869, null], [31869, 34053, null], [34053, 36422, null], [36422, 38144, null], [38144, 40448, null], [40448, 41419, null], [41419, 41861, null], [41861, 42216, null], [42216, 43315, null], [43315, 44829, null], [44829, 46275, null], [46275, 47696, null], [47696, 49167, null], [49167, 50846, null], [50846, 52842, null], [52842, 54733, null]], "google_gemma-3-12b-it_is_public_document": [[0, 413, true], [413, 1991, null], [1991, 3732, null], [3732, 4811, null], [4811, 5872, null], [5872, 6005, null], [6005, 8029, null], [8029, 9627, null], [9627, 9991, null], [9991, 10623, null], [10623, 12305, null], [12305, 14998, null], [14998, 17444, null], [17444, 19175, null], [19175, 20434, null], [20434, 22378, null], [22378, 24806, null], [24806, 27037, null], [27037, 28015, null], [28015, 30140, null], [30140, 31869, null], [31869, 34053, null], [34053, 36422, null], [36422, 38144, null], [38144, 40448, null], [40448, 41419, null], [41419, 41861, null], [41861, 42216, null], [42216, 43315, null], [43315, 44829, null], [44829, 46275, null], [46275, 47696, null], [47696, 49167, null], [49167, 50846, null], [50846, 52842, null], [52842, 54733, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54733, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54733, null]], "pdf_page_numbers": [[0, 413, 1], [413, 1991, 2], [1991, 3732, 3], [3732, 4811, 4], [4811, 5872, 5], [5872, 6005, 6], [6005, 8029, 7], [8029, 9627, 8], [9627, 9991, 9], [9991, 10623, 10], [10623, 12305, 11], [12305, 14998, 12], [14998, 17444, 13], [17444, 19175, 14], [19175, 20434, 15], [20434, 22378, 16], [22378, 24806, 17], [24806, 27037, 18], [27037, 28015, 19], [28015, 30140, 20], [30140, 31869, 21], [31869, 34053, 22], [34053, 36422, 23], [36422, 38144, 24], [38144, 40448, 25], [40448, 41419, 26], [41419, 41861, 27], [41861, 42216, 28], [42216, 43315, 29], [43315, 44829, 30], [44829, 46275, 31], [46275, 47696, 32], [47696, 49167, 33], [49167, 50846, 34], [50846, 52842, 35], [52842, 54733, 36]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54733, 0.06566]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
d99b627c0e38fb73ef16dafdaecea4c12bd1d542
|
Shared State for Distributed Interactive Data Mining Applications *
Srinivasan Parthasarathy
Computer and Information Science
Ohio State University,
Columbus, OH 43235
srini@cis.ohio-state.edu
Sandhya Dwarkadas
Computer Science
University of Rochester
Rochester, NY-14627
sandhya@cs.rochester.edu
October 3, 2001
Abstract
Distributed data mining applications involving user interaction are now feasible due to advances in processor speed and network bandwidth. These applications are traditionally implemented using ad-hoc communication protocols, which are often either cumbersome or inefficient. This paper presents and evaluates a system for sharing state among such interactive distributed data mining applications, developed with the goal of providing both ease of programming and efficiency. Our system, called InterAct, supports data sharing efficiently by allowing caching, by communicating only the modified data, and by allowing relaxed coherence requirements specification for reduced communication overhead, as well as placement of data for improved locality, on a per client and per data structure basis. Additionally, our system supports the ability to supply clients with consistent copies of shared data even while the data is being modified.
We evaluate the performance of the system on a set of data mining applications that perform queries on data structures that summarize information from the databases of interest. We demonstrate that providing a runtime system such as InterAct results in a 10-30 fold improvement in execution time due to shared data caching, the applications’ ability to tolerate stale data (client-controlled coherence), and the ability to off-load some of the computation from the server to the client. Performance is improved without requiring complex communication protocols to be built into the application, since the runtime system uses knowledge about application behavior (encoded by specifying coherence requirements) in order to automatically optimize the resources utilized for communication. We also demonstrate that for our benchmark tests, the quality of the results generated is not significantly deteriorated due to the use of more relaxed coherence protocols.
---
*This is an expanded version of our conference paper in the First SIAM International Conference on Data Mining [36]. This work was supported in part by NSF grants CDA-9401142, EIA-9972881, CCR-9702466, CCR-998361, and CCR-9705594; and an external research grant from Compaq.
1 Introduction
The explosive growth in data collection techniques and database technology has resulted in large and dynamically growing datasets at many organizations. For these datasets to be useful, data mining, the process of extracting useful information from such datasets, must be performed. The datasets at these organizations are typically in a remote repository accessible via a local or inter-network. Despite advances in processor and network technology, remote data mining is made difficult by the prohibitive bandwidth requirements imposed by the size of the data involved and the low latency requirements imposed by the interactive nature of data mining. The size of the datasets prohibit transferring the entire data to the remote client(s). In addition, data mining is often an iterative process with the user tweaking the supplied parameters according to domain-specific knowledge. This compounds the problem of increased response times due to network and server delays.
These applications can often be structured so that subsequent requests can operate on relatively small summary data structures [41]. Once the summary structure is computed and communicated to the client, interactions can take place on the client without further communication with the server. Also, the mining processes are often independently deployed and perform very different operations, resulting in different traversals of the shared data. The summary is based on the snapshot of the actual data at any point in time. If the data is dynamically being modified, the summary is likely to change. In this scenario, the client’s copy of the summary structure must be kept up-to-date.
The above communication can be accomplished by employing some form of message passing or remote procedure call (RPC) in order to keep the data coherent. However, these techniques are often cumbersome, and can be inefficient. RPC mechanisms work well for “function shipping”—moving the process to the data—but they do not work well for moving data to the process. Using message passing requires users to invent ad-hoc communication and coherence protocols in order to manage data copies. Programming ease concerns suggest the need for an abstraction of shared
state that is similar in spirit to distributed shared memory (DSM) semantics. However, even the most relaxed DSM coherence model (release consistency [19, 11]) can result in a prohibitively large amount of communication for the type of environment in which data mining may typically be performed. These applications can often accept a significantly more relaxed—and hence less costly—coherence and consistency model, resulting in excellent performance gains. In fact, as we show in this paper, some tasks might require updates to shared data at regular intervals instead of whenever the data is modified, while others might require updates whenever the data is modified “by a certain amount”. In other words, such applications can tolerate stale data based on a temporal or change-based criterion, thereby reducing communication overhead and improving efficiency. Hence, overall system performance can be improved by allowing each client to specify the data shared as well as the coherence model required for its needs.
In this paper, we describe our runtime framework, called InterAct [35, 36], developed with such active data mining applications in mind, that allows efficient caching and sharing of data among independently deployed clients and servers. InterAct supports data sharing efficiently by communicating only the modified data, and by allowing individual clients to specify relaxed coherence requirements on a per data structure basis. Additional features of the system include dynamic data placement for memory locality (handling the problem of different traversals of the shared data by different processes and made feasible because of the address-independent nature of the system) and the ability to supply clients with consistent copies of shared data even while the data is being modified (made feasible through the use of virtual memory mechanisms to implement coherence and consistency).
The interface is general enough to support a wide range of application domains including the visualization of scientific simulations and the remote tracking of images. We focus here on several applications from the interactive data mining domain and use them to demonstrate the advantages of the InterAct system. These applications are structured so that the server is responsible for creating the data structure(s) (storing the summary), mapping them to a virtual shared dataspase, and subsequently
keeping them up-to-date. The client can then map the data structure(s) from the
in virtual shared datasetspace under an appropriate coherence model. We show that executing queries using the appropriate summary structure can improve performance significantly; up to a 23-fold improvement in query execution times was observed. When the clients cache the summary structure using relaxed coherence models, we also observed several orders of magnitude reduction in update costs. Furthermore, for these applications, using such relaxed models does not significantly affect the quality of the results (we observed <2% degradation in result quality).
The rest of this paper is organized as follows. In Section 2, we outline our overall system design goals and compare our system to related work in Section 3. In Section 4, we describe the interface and implementation of InterAct, and demonstrate its use through an example application. We evaluate the utility of the system using several applications from the interactive data mining domain, described in Section 5. Experimental results are presented in Section 6. Finally, our conclusions and on-going work are outlined in Section 7.
2 Design Goals
In order to accomplish the goal of efficiently providing shared state in a distributed environment, the runtime system must provide an interface that defines a mechanism to declare shared data that is address space independent and persistent (so that clients can join and leave at any time). In addition to the above minimal requirement for sharing, data mining applications have several properties that can be exploited, and key needs that ideally must be supported.
First, since clients have differing needs in terms of how up-to-date a copy of the data is acceptable, the system must identify, define, and support different relaxed coherence models that may be exploited for application performance. This feature of client-controlled coherence is similar to the notion of quasi-caching [4] (see Section 3).
Second, many data mining applications require the capability of obtaining a consistent version of a shared data structure at any time, even in the presence of an on-going update to the data. We refer to this feature as anytime updates.
Third, many data mining applications traverse these summary structures in an ordered manner. Different clients may have different access patterns depending on the kind of queries processed. This feature requires that the system export programmer-controlled primitives that allows data to be remapped or placed in local memory in a manner that mirrors how the data is likely to be accessed by a given user or client. We refer to this feature as client-controlled memory placement.
Fourth, the shared data, although significantly reduced (summary), can still be quite large, so re-sending it on each update can cause significant delays on a busy network. It is therefore important for the runtime system to identify which parts of the shared data have been modified since the client’s last update. Only the changes need be sent to the client on an update. In Section 4, we describe how our system, InterAct, can support the above data mining requirements while providing a general interface for a large class of applications.
3 Related Work
There is a rich body of literature studying the issues in caching and data sharing in many different computing environments. Distributed object-based systems [6, 26, 25, 30, 45, 51, 53, 7, 18], all support the basic requirement of sharing address-independent objects. However, update propagation in such systems, which are typically supported either by invalidate and resend on access or by RMI-style mechanisms, are inefficient (re-sending a large object or a log of operations (RMI)) and often infeasible (especially if the methods require data available only on the server side) for data mining applications. Distributed shared memory systems [3, 5, 11, 29, 46, 44, 22, 24, 55] all support transparent sharing of data amongst remote processes, with efficient update propagation, but most require tight coupling of processes with sharing that is not address-independent. None of the above systems support flexible client-controlled coherence, client-controlled memory placement (due to their address-dependent nature), or anytime updates.
Quasi-Caching [4] is very relevant to the topic of maintaining client-controlled coherence between a data source and cached copies of the data. Quasi-Caching as-
sumes that each object has a computer that stores the most recent version and other computers store quasi-replicas that may diverge. They considered both time-based and scalar value based divergence (coherence) models. In their work, the allowed divergence is specified by the user in a fixed manner. The quasi-caching work describes when to update a client’s cached copy but does not deal with the issue of how to do so efficiently. Furthermore, this work also does not support dynamically modifying the coherence model, or client-controlled memory placement.
Computer Supported Collaborative Work (CSCW) systems [48, 17, 14] share some of the features of InterAct (supporting interactive sessions across independent and potentially heterogeneous systems, update notification, etc.). However, most of these systems are tailored to a specific application, like cooperative engineering design, or distributed meetings. This has lead to a proliferation of isolated tools with little or no inter-operability.
There has also been some recent work on distributed data mining systems. The Kensington [21] architecture treats the entire distributed data as one logical entity and computes an overall model from this single logical entity. The architecture relies on standard protocols (such as Java Database Connectivity (JDBC)) to move the data. The Intelliminer [50] and Papyrus systems [20] are designed around data servers, compute servers, and clients as is the system presented in this work. All of the above systems rely on a message-passing-like interface for programming distributed data mining applications. InterAct provides a shared-object interface with features such as client-controlled coherence, memory placement, and anytime updates. In this paper, we limit ourselves to evaluating InterAct on client-server data mining applications although the InterAct system can be used for a broader class of distributed applications.
4 Runtime Framework
Shared data in InterAct are declared as complex-objects. Complex-objects are composed of nodes that may be linked together. Nodes may be C-style structs, basic
types, or some predefined InterAct types. Complex-objects could include recursive
data structures such as graphs, trees, lists, arrays or collections of nodes. In Figure 1,
we describe a general-purpose interactive mining algorithm mapped onto InterAct.
In this example, the client has mapped three complex-objects, an array, a directed
acyclic graph (DAG), and a list representing the shared data summaries, onto the vir-
tual shared dataspace. An element in the list points to the DAG, represented by the
connection. The server is responsible for creating and updating these data summaries.
The client specifies a coherence model when mapping the summaries, synchronizes
when required, and is responsible for the interactive querying component.
In InterAct, every complex-object moves through a series of consistent states, or
versions. When a client first maps a shared complex-object, it specifies the desired
coherence model. InterAct obtains a copy of the complex-object from the server on
the first client access. At the beginning of each semantically meaningful sequence of
operations, the client performs a synchronization operation, during which the system
ensures that the local copy of the complex-object is “recent enough”, as determined
by the specified coherence protocol. If not, it obtains a new version from the server.
One of the principal innovations in the runtime system is the provision of the abil-
ity to allow each individual process to determine when a cached copy of a complex-
object is “recent enough”, through the specification of one of a set of highly relaxed
coherence models. Changes to complex-objects must be made using mutually exclu-
sive access. As long as applications adhere to these synchronization requirements,
InterAct transparently handles all client-server communication including intra-object
consistency and coherence maintenance.
InterAct defines the following coherence models. One-Time Coherence specifies
a one-time request for data (complex-object) by the client. No history need be
maintained. This is the default coherence type. Polled Coherence indicates that
the client may request a current version when desired. The server may then attempt
to reduce communication requirements by keeping track of the staleness of the data
cached by the client. Immediate Coherence guarantees that the client will be not-
tified whenever there are any changes to the mapped data. Diff-based Coherence
guarantees that no more than \( x\% \) of the nodes comprising a complex-object is out of date at the time of synchronization. **Delta Coherence** [46] guarantees that the complex-object is no more than \( x \) versions out of date at the time of synchronization. **Temporal Coherence** guarantees that the complex-object is no more than \( x \) real-time units out of date at the time of synchronization. In all cases, \( x \) can be specified by the client. Section 5 details the use of the different coherence models by various data mining techniques.
The coherence models are motivated by the ability of a large number of data mining and other interactive applications to tolerate a certain level of data staleness. In all cases, the interface involves the use of synchronization in order to bring data up-to-date, or to make modifications to the data. The application programming interface (API) allows processes to acquire a read or a write lock on shared data. A read lock guarantees that the shared data is up to date subject to the coherence model requested. A write lock always guarantees strict coherence.
In order to provide client-controlled memory placement, our API provides primitives by which each process (clients or servers) can locally remap nodes within a complex-object to improve spatial locality. InterAct transparently handles the remapping as a byproduct of supporting address independence. We next discuss the InterAct API.
4.1 Interface
In Figure 1, we describe the current interface available to the user within the two grayed rectangular regions. Our interface is essentially a set of template classes. Node is the template in which user data (using Class User_Data) can be embedded and from which it can be accessed (using access_node). InterAct_Object is the template with predefined functions for creating a complex-object, remapping (remap_object) it in memory in a locality-enhancing manner, adding (add_node) nodes to an InterAct complex-object, and deleting (delete_node) nodes from an InterAct complex-object. In addition, there are various methods that allow one to access the root node (get_root) of an InterAct object, identify (num_child) how many nodes are connected to a given node within a complex-object, and access such children nodes (child).
There are also functions for synchronizing (acquire/release read/write lock\textsuperscript{1}) and modifying the required coherence type (cons_type). The User_Data class is used as a base to define what a node contains. The node may be composed of basic data types and pointers to other complex-objects. The interface requires the user to identify these special pointers (object_ptr, not in figure) to the system. We next describe how this interface can be used to create, map, and manipulate summary structures.
4.1.1 Example Usage
**Server code**: In this code fragment (Figure 2) the contents of each node within the complex-object to be created is first declared. This is done by deriving a sub-class
\textsuperscript{1}Note that our implementation of a write lock is \textit{relaxed}, in the sense that readers are permitted during a lock held in write mode.
Class lattice_node: public User_Data{
int id; // item id
int count; // support
}
Main(){
/* initialization routines */
/* create new InterAct object called lattice */
InterAct_Object <lattice_node> *at =
new InterAct_Object ("Lattice");
/* obtain a write lock on the new object */
at->acquire_lock(write);
/* insert itemsets to Lattice */
Add_Itemset(at, itemset, support);
/* update itemsets to Lattice */
Update_Itemset(at, itemset, support);
/* release write lock */
at->release_lock();
}
Add_Itemset(at, itemset){
/* get root node and add new child node */
Node <lattice_node> *root = at->get_root();
Node<lattice_node> *child = at->add_node(root);
lattice_node *data = child->access_node();
/* enter values for new itemset */
data->id = itemset.id;
data->count = itemset.count;
}
Update_Itemset(at, itemset){
Node <lattice_node> *root = at->get_root();
for (I = 0; I < at->numchild(root); I++)
if (at->child(root, I)->access_node()
->id == itemset.id)
break;
lattice_node *data =
at->child(root, I)->access_node();
/* update support */
data->count = itemset.count;
}
Class lattice_node: public User_Data{
int id; // item id
int count; // support
}
Main(){
/* initialization routines */
/* map new InterAct object called lattice */
InterAct_Object <lattice_node> *at =
new InterAct_Object ("Lattice", sync, par);
/* obtain a read lock on the new object */
at->acquire_lock(read);
/* execute prioritized association query */
Prioritized(at, at->get_root(), minsup, 40);
/* release write lock */
at->release_lock();
}
Prioritized(at, current, minsup, num_assoc)
/* if required #assoc have been displayed, return */
if (total_assoc >= num_assoc) return;
for (I = 0; I < at->numchild(current); I++){
/* get data for each child */
lattice_node *child_data =
at->child(root, I)->access_node();
/* if child has support value greater than minsup */
if (child_data->count > minsup)
/* if child has not yet been visited enqueue on priority queue */
if (!visited(child_data)){
PQ.enqueue(at->child(current, I));
} /* end for */
} /* end while */
while (PQ not empty){
Cnode = PQ.dequeue();
print(Cnode); /* display association */
total_assoc++;
if (total_assoc >= num_assoc) return;
/* recursively invoke Prioritized */
Prioritized(at, Cnode, minsup, num_assoc)
if (total_assoc >= num_assoc) return;
} /* end while */
/* end Prioritized */
called `lattice.node` from the abstract class `UserData` as shown. Each `lattice.node`
contains an itemset id and a count for that itemset. The main program in the
server initializes the `InterAct` framework and formally declares and creates an `In-
terAct` complex-object called Lattice (using the above defined `lattice.node`). The
server can then add, update, and delete (not shown) nodes after acquiring the neces-
sary lock on the complex-object.
For expository simplicity both the the AddItemset and UpdateItemset pseudo-
codes assume that the tree is only one-level deep, i.e. only children of the root node
have to be added or updated. The AddItemset procedure first identifies the root of
the complex-object using the `get_root` method, and then adds a child to the root
using the `add_node` method. The data within the child node can then be accessed
and added to by using the `access_node` method. The UpdateItemset procedure first
identifies the appropriate child node of the root node that needs to be updated (using
the `numchild` and `child` methods). It then accesses and updates the corresponding
child node using the `access_node` method.
**Client code:** Like the server, the client also has to define the `lattice.node`. After
performing the initialization operations the client can map a given object as shown
in Figure 3. The call to create a new `InterAct` Object specifies the coherence type
(`sync`) and coherence parameters (`par`) if any in addition to specifying the object
name. This call examines a file/database with information associating each object
name with a server (IP address and port number). If the process is determined to be a
client, the necessary communication with the server is performed in order to retrieve
the initial copy of the object. Once the object is mapped it can be synchronized with
the server version by acquiring the appropriate lock. In the pseudo-code shown in
Figure 3, the client invokes a procedure called Prioritized after acquiring a `read_lock`
After the procedure has been completed the client releases the `read_lock`
`Prioritized` is a recursive procedure (described in [33, 1]) that identifies the
`X` (`X = 40` in the figure) most frequent associations and displays them. Each call
to the procedure involves accessing the children of the current node and evaluating
their support counts against the minimum support criteria (using the child and access_node methods). Nodes representing itemsets that meet the minimum support criteria, are added to the priority queue (priority is determined by support counts). Then the priority queue is dequeued as many times as the number of associations \(X = 40\) requested. This procedure uses the child, numchild, and access_node methods to access and read the data contained within the complex-object.
4.2 Memory Management and Access
Like any distributed object-based system, our interface identifies any pointers and their associated types to the runtime system in order to provide address independence. During complex-object creation, the complex-object’s internal representation is divided into data and connection pages\(^2\) (this division is transparent to the user as long as the defined templates are used to declare and access shared data).
Data pages contain all the nodes for a complex-object. Nodes are created and allocated as fixed-size structures so that array index arithmetic \(^3\) may be used to access them efficiently (allowing variable sized nodes would simply involve a slightly less efficient access mechanism to the node). Separating connection information for a node (number of nodes linked to) allows the number of links to be variable and enables us to use array arithmetic on the data pages. Each node contains a single pointer into the connection pages that identifies the set of nodes that node links to. Information in the connection pages identifies the nodes within the complex-object in terms of an index, making address independence feasible. Separating connection and data information also co-locates all the pointers, enabling the runtime system to perform efficient pointer swizzling \([54]\).
Laying the data out in semi-contiguous order facilitates efficient address to node
\(^2\)Each complex-object is mapped to a disjoint set of pages, which enables our system to transparently detect changes to objects using virtual memory hooks. Since we are dealing with applications where the complex-objects are reasonably large relative to the size of a page, this does not result in memory wastage.
\(^3\)Note that since complex-objects can dynamically change in size, all the pages for a complex-object need not be contiguous, so a slightly modified form of array indexing is needed.
mappings as long as node sizes are fixed, resulting in fast identification of changes to a complex-object as outlined below in Section 4.3. The use of node identifiers coupled with the above scheme also enables fast node to address mapping that permits us to update node changes rapidly as well as maintain mappings independent of server mappings, as outlined below in Section 4.7.
4.3 Object Modification Detection
The technique we use to detect modifications is similar to that used by multiple-writer page-based software distributed shared memory systems [5, 8], except that we use a node as the granularity at which we detect modifications. At the start of every acquire of a write lock (see Figure 4), all relevant complex-object pages are marked read-only using the mprotect virtual memory system call. When a processor incurs a write fault, it creates a write notice (WN) for the faulting page and appends the WN to a list of WNs associated with the current interval, or region encapsulated by an acquire and a release. It simultaneously saves a pristine copy of each page, called a twin, and enables write permissions [8]. When the lock is released, the twin is used to identify the nodes modified within the interval.
At the release, all objects that have been modified (identified through the WN list) increment their associated object timestamp (or version number). These objects are efficiently identified since our WN list is maintained as a hash table containing the <page address, object identifier> pairs. Since we ensure that complex-objects reside on separate pages, a write to a page corresponds to a write to a single complex-object. Modified nodes are identified by comparing the modified pages to their twins. Comparison is thus limited only to those pages that are actually modified. These modified nodes are then communicated to the object manager along with the latest version number in order to keep the manager’s copy up-to-date. The object manager has a timestamp (or version) map associated with each object. A timestamp map contains an entry for each node indicating the last time it was modified (see Figure 4). Upon receiving modifications, the manager updates its copy of the data as well as of the timestamp map.
4.4 Updating an Object
When asked for changes by the caching process, the object manager (server) compares its timestamp map for the complex-object against the last time the client has been appraised of an update. The result of the timestamp comparison is a run-length encoding of the node data and node connections that have been modified, which constitute the diff of the complex-object (Figure 4). Header information also specifies the complex-object identifier, and number of node data and connection updates.
On the client side, we maintain information corresponding to the objects that are mapped and where they are stored in local memory. On receiving a diff message, we update the corresponding object by decoding the header to determine the object identifier. This object identifier is then used to determine the local location of the object. Data and connection information for nodes within the object are similarly address independent.
The issue of containment (or aggregation) in an object-oriented design is an important one for performance and correctness reasons. In our current implementation, when a client maps a particular object, we update all nodes that belong to the particular object immediately. However, if a node within this object points to another object or another node within another object, that object is not copied immediately. It is copied lazily upon client access or client request. The InterAct interface implicitly
gives the programmer control over what needs to be copied immediately and what can be lazily copied. All the programmer has to do is to create separate complex-objects in this case.
4.5 Generating Anytime Updates
If a client request comes in while a write lock on the object is held by the server or managing process, one approach would be to wait till the server transaction commits before sending an update to the client. This may not be acceptable for applications requiring a quick response, especially when the lock is held for a long time. Our approach is to twin the entire object on creation. When the write lock is released, the object twin is updated using the diff mechanism described above. If a client request comes in during a write lock, the system returns the update from the twin rather than the original object. During the application of the diff on the twin, the system returns the update from the original object. This ensures that the client rarely has to wait for the requested data in practice. This approach is costly in terms of space. An alternative approach which we considered is to twin only the pages modified (as described in Section 4.3) during the write lock and deliver updates for modified pages from these twins. However, this approach involves pointer tracking and associated synchronization and therefore is more costly in terms of time. One could potentially switch between the two approaches as a function of application requirements and system configuration.
4.6 Coherence Maintenance
The runtime system optimizes data communication by using the coherence model specified by the user to determine when communication is required. The goal is to reduce messaging overhead and allow the overlap of computation and communication. Implementation of the Immediate Coherence, Polled Coherence, and One-Time Coherence guarantees are fairly straightforward. One-Time Coherence does not require any meta-data (timestamp) maintenance, nor does it require
\footnote{In order to guarantee an atomic update, the data cannot be sent in an as is condition, as partial changes to the object may have occurred concurrently.}
the server to generate object diffs. **Polled Coherence** is implemented by having
the client send the most recent timestamp of the object it has seen. Under **Imme-
diate Coherence** the server keeps track of this information. Under both Polled and
Immediate coherence only those nodes with timestamps greater than this value are
communicated. The difference between Polled and Immediate coherence is that in
the latter the server notifies the client when a complex-object has been modified while
the former has no such notification protocol. This allows the runtime system under
Immediate coherence to check for notification messages before issuing an update re-
quest to the manager (server) eliminating some communication traffic. The upside to
Polled Coherence is that the server does not need to maintain client-specific state on
a per complex-object basis.
**Temporal Coherence** is supported by having the runtime system on the client’s
side poll for updates every $x$ time units, as defined by the user. To keep track
of **Diff-based Coherence**, the server maintains a cumulative count of nodes per
complex-object that are modified since the last client update. If this cumulative count
exceeds a preset user-defined value (referred to as the *diff* parameter), the client is
sent a notification (similar to Immediate Coherence) and a subsequent update. **Delta
Coherence** is kept track of in a manner similar to **Diff-based Coherence**. In these
cases as well, the server has to maintain the last timestamp seen by the respective
clients.
### 4.7 Memory Placement
Different clients may have different mining agendas, leading to different data structure
access. **InterAct** permits the clients to place the mapped data structure in memory
in a locality enhancing manner by using the `remap()`\(^5\) function. For example, if the
structure is a tree and most of the client interactions are going to induce a breadth-
first evaluation of the tree, then the tree can be placed in memory in a breadth-first
fashion to improve cache locality. **InterAct** currently supports breadth-first, depth-
---
\(^5\)Clients need to execute this only once. Subsequent updates from the server are automatically
handled correctly by our system’s address translation mechanisms.
first, and user-defined placement [38]. User-defined placement allows the programmer to define a condition that splits the nodes in an object into separate sets of contiguous memory.
5 Applications
In past work [37, 39, 40, 33], we have shown that it is possible to design useful summary structures for several mining applications so that subsequent queries can operate on these summary structures rather than the actual data. Within our framework of remote mining, these summary structures are generated and kept up-to-date by the data server, and subsequently mapped and operated on by the client. In this work, we simulate the updates on the server side according to real data and application update properties, described below.
Association and Sequence Mining: Given a database of transactions where each transaction consists of a set of items, association discovery [2] finds all the item sets that frequently occur together, and also the rules among them. Sequence discovery essentially involves association discovery over temporal databases. It aims to discover sets of events that commonly occur over a period of time.
For association and sequence mining, the summary structure we use is the Itemset Lattice [1, 33] (or Sequence Lattice [39]), which contains pre-mined patterns and the corresponding support\(^6\) information. Responses to user requests typically involve computing a constraint-based subset of the entries in the lattice. Updates to the lattice are handled as described in [52](39). Each incremental update, reflecting new data, typically combines multiple actual transactions, for performance reasons [52, 33]. There are two possible kinds of updates to the summary structure based on the type of mining being performed. When mining is performed on the entire database, new transactions are usually only added to the database — we call these additive updates. When mining is performed on a window of transactions in the database, changes in the database result in almost as many additions as deletions to the window.
\(^6\)Support is the number of times the pattern occurs in the dataset.
— we call these windowed updates. Both types of updates typically result in changes to anywhere from 0.1% to 10% of the summary data structure. This is because in typical scenarios the number of transactions being added or deleted is a small percentage (0.1%-1%) of the total number of transactions being represented (and in the case of sequence mining not all customers are part of each update), so the net impact on the summary is relatively low. Additive updates mostly result in modifications to support counts and a few pattern additions and deletions. However, for windowed updates, the changes tend to result in more associations being added and/or deleted. For these applications, since the user is usually interested in keeping track of less frequently occurring associations or sequences, a stricter coherence model such as **Polled Coherence** or **Immediate Coherence** is generally preferred.
**Discretization:** Discretization has typically been thought of as the partitioning of the space induced by one (say X) or more continuous attributes (base) into regions (e.g., X < 5, X >= 5), which highlights the behavior of a related discrete attribute (goal). Discretization has been used for classification in the decision tree context and also for summarization in situations where one needs to transform a continuous attribute space into a discrete one with minimum “loss”. Our program is an instance of 2-dimensional discretization (two base attributes, described in [37]).
Interactions supported include generating an optimal discretization (based on entropy or classification error), and modifying the location and number of control points (which partition the two-dimensional base attribute space). The summary structure required to support such interactions efficiently is the joint probability density function (pdf) of the base and goal attributes. This pdf is estimated at discrete locations. While several techniques exist to estimate the density of an unknown pdf, the most popular ones are histogram, moving window, and kernel estimates [13]. We use the histogram estimate described in [13]. The advantage of this estimate is that it can be incrementally maintained in a trivial manner (a histogram estimate is essentially the frequency distribution normalized to one). Moreover, the more complicated kernel estimates can easily be derived from this basic estimate [13]. Each update corresponds to one transaction and every update modifies exactly one entry in the array. Each
update is simply a small perturbation on the pdf estimate and as such does not affect the quality of discretization significantly. Thus, this technique would benefit from using **Diff-based Coherence** without affecting the quality of the results. The *diff* parameter specifies the amount of data that needs to change before it is significant to the application.
**Similarity Discovery in Datasets**: This application computes and maintains the similarity between two or more datasets. Such measures of similarity are useful for clustering homogeneous datasets. In [40], we define the similarity between two datasets to be a function of the difference between the set of associations induced by them, weighted by the supports of each association. To compute and maintain the similarity between $n$ datasets, the client maps the itemset lattices (containing the association patterns and their supports) from each of the distinct data sources and then computes the pairwise similarity measures.
It has been noted [12] that incorporating domain bias in the similarity measure via suitable interactions can be very useful. In this application, we support the following operations: similarity matrix re-generation after a data structure update, identifying influential attributes, and constraining the similarity probe set via constraint queries on the itemset lattices. Incrementally maintaining the association lattices has already been discussed above. However, since this application is more interested in general patterns, even if a large percentage of the mapped summary structure is modified over a period of several updates, it has been shown that the percentage change in the measured similarity is not significantly affected. The measured similarity directly correlates more to the magnitude of the change in data. This magnitude is not directly measurable without a large amount of overhead. However, the use of **Delta Coherence** captures this application’s requirements by allowing the data to be several versions out of date without affecting result quality.
**Other Applications**: We have described how one can define summary structures for four key data mining tasks. The same principles may be applicable to other data mining tasks as well and this issue is under investigation. For instance, for clustering one may choose to create, maintain (server-side), and map (client-side)
cluster descriptors. For decision-tree classifiers one could either create, maintain, and map the actual trees themselves or a compact representation of the tree such as an FFT representation [27]. For both neural networks and bayesian networks the actual network descriptors (weights and links) could be mapped.
<table>
<thead>
<tr>
<th>Application</th>
<th>Object Size</th>
<th>UPS</th>
<th>%Change</th>
<th>Change Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>Association Mining</td>
<td>3.3MB</td>
<td>0.5</td>
<td>4%</td>
<td>ADD/DEL</td>
</tr>
<tr>
<td>Sequence Mining</td>
<td>1.0MB</td>
<td>1</td>
<td>10%</td>
<td>MOD/ADD</td>
</tr>
<tr>
<td>Discretization</td>
<td>0.5MB</td>
<td>100</td>
<td>0.002%</td>
<td>MOD</td>
</tr>
<tr>
<td>Similarity(1)</td>
<td>0.5MB</td>
<td>5</td>
<td>10%</td>
<td>MOD/ADD</td>
</tr>
<tr>
<td>Similarity(3)</td>
<td>3X0.5MB</td>
<td>5</td>
<td>0.33%</td>
<td>MOD/ADD</td>
</tr>
</tbody>
</table>
Table 1: Server Update Properties
**Properties of Server Updates** We outline the exact nature of the updates\(^7\) used for our experiments for each application in Table 1. The second column refers to the size of the summary structure when the server starts up. UPS corresponds to updates per second on the server side. The column labeled %Change corresponds to the percentage of nodes in the summary structure that are changed over a single update, and are representative of realistic workloads for each of the applications. For Similarity Discovery, we computed the similarity among four databases. Updates on one of these databases (Similarity(1)) had different properties from the other three (Similarity(3)). The last column in the table refers to the dominant change type of the given update. ADD refers to the fact that the update adds new nodes, DEL refers to the fact that the update deletes nodes, MOD refers to the fact that the update modifies existing nodes. The order in which change types appear in column five of the table are in decreasing order of dominance. For example, ADD/DEL refers to the fact that on average, executing the corresponding update results in more additions than deletions to the summary structure.
\(^7\)The datasets used are described in [41].
6 Experimental Evaluation
We evaluate our framework in a distributed environment consisting of SUN workstations connected by 10 or 100 Mbps switched Ethernet. Unless otherwise stated, the clients use a 100 Mbps link, and are 270 MHz UltraSparc IIIi machines. The clients in each application interact with the server by sharing the summary data structures with the server. The server creates the summary data structure and updates it corresponding to changes in the database (which we emulate). The client maps these data structures using one of the provided set of coherence models. Updates are then transmitted to the client according to the coherence model chosen.
6.1 Runtime Overhead
We evaluated the overhead imposed by our system on the server side during normal execution without client connections. To evaluate this overhead, we compared the test application written using the InterAct interface against a program written using standard C++. Using UNIX malloc with the C++ program, we found that the application running on top of our framework executed slightly faster due to our improved memory allocation policy. We use a special memory placement library [38] in our system that improves locality and therefore cache performance. Comparing against the standard C++ program with calls to the UNIX malloc replaced by calls to our memory placement library, we found the runtime overhead imposed by using our template interface (which involves more indirect accesses) to be less than 5% for our application suite.
6.2 Client-Side Caching
In typical client-server applications, the client makes a request to the server, the server computes the result, and then sends the result back to the client. Since the interactions in our applications are often iterative in nature, caching the data structure on the client side so that repeated accesses may be performed locally eliminates
overhead and delays due to network latency and server load. The potential gain from client-side caching depends on a number of factors: the size of the shared data, the speed of the client, the network latency, and the server load.
In this experiment, we ran each of our applications under the following scenarios:
1. Client-Side Caching (CSC): the client caches the summary structure and executes the query on the local copy.
2. Server Ships Results to Client (SSRC): the client queries the server and the server ships the results back to the client. This scenario is similar to the use of an RPC mechanism. In order to better understand the impact of server load, we varied the number of clients serviced by the server from one (SSRC) to eight (Loaded-SSRC). For each of the applications considered, Associations, Sequences, Discretization, and Similarity, the average size of the results shipped by the server was 1.5MB, 0.25MB, 0.4MB and 0.75MB respectively.
We measured the time to execute each query under both scenarios. We evaluated each scenario on client machines that were either an UltraSparc (143Mhz) machine or an UltraSparc III (270Mhz). In each case, our server was an 8-processor 333 MHz UltraSparc III machine. Results are presented in Tables 2 and 3 for these scenarios under different network configurations. We varied the network configuration by choosing clients that are connected to the server via a 10 Mbps or a 100 Mbps Ethernet network.
<table>
<thead>
<tr>
<th>Application</th>
<th>Client(143)</th>
<th></th>
<th></th>
<th>Client(270)</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>CSC</td>
<td>SSRC</td>
<td>L-SSRC</td>
<td>CSC</td>
<td>SSRC</td>
<td>L-SSRC</td>
</tr>
<tr>
<td>Association</td>
<td>2.4</td>
<td>1.6</td>
<td>2.5</td>
<td>1.5</td>
<td>1.4</td>
<td>2.3</td>
</tr>
<tr>
<td>Sequence</td>
<td>0.58</td>
<td>0.55</td>
<td>0.86</td>
<td>0.35</td>
<td>0.5</td>
<td>0.73</td>
</tr>
<tr>
<td>Discretization</td>
<td>0.87</td>
<td>0.67</td>
<td>1.08</td>
<td>0.55</td>
<td>0.6</td>
<td>0.98</td>
</tr>
<tr>
<td>Similarity</td>
<td>0.35</td>
<td>0.55</td>
<td>0.98</td>
<td>0.11</td>
<td>0.37</td>
<td>0.94</td>
</tr>
</tbody>
</table>
Table 2: Time (in seconds) to Execute Query: 100Mbps Interconnect
<table>
<thead>
<tr>
<th>Application</th>
<th>Client (143)</th>
<th>Client (270)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>CSC</td>
<td>SSRC</td>
</tr>
<tr>
<td>Association</td>
<td>2.4</td>
<td>4.05</td>
</tr>
<tr>
<td>Sequence</td>
<td>0.58</td>
<td>0.85</td>
</tr>
<tr>
<td>Discretization</td>
<td>0.87</td>
<td>1.35</td>
</tr>
<tr>
<td>Similarity</td>
<td>0.35</td>
<td>1.5</td>
</tr>
</tbody>
</table>
Table 3: Time (in seconds) to Execute Query: 10Mbps Interconnect
The results in Table 2 and Table 3 show that client-side caching is beneficial for all but a few of the cases. In particular, the following trends are observed. Client-side caching is more beneficial under the following scenarios: the network bandwidth is low (speedups from client-side caching under the 10Mbps configuration are larger (1.5 to 23) than the 100Mbps numbers (0.6 to 9)), the server is loaded (comparing the L-SSRC column (speedups of 1.1 to 9) with the SSRC column (speedups of 0.6 to 3.5) with a 100 Mbps network), the client is a fast machine (comparing the columns involving the 270Mhz client versus the slower clients), or the time to execute the query is low (comparing the row involving similarity discovery with the row involving association mining). In other words, as expected, the benefits from client-side caching are a function of the computation/communication ratio. The lower the ratio, the greater the gain from client-side caching.
These results are presented just to illustrate the fact that InterAct enabling such caching is very useful for such applications especially when deployed on the Internet. The results from this experiment underscore two key aspects. First, *it is possible* to design useful summary structures that summarize the dataset effectively for mining purposes. Such summary structures can be accessed efficiently to answer a set of useful queries rapidly and efficiently and are significantly smaller than the original datasets they summarize. Second, shipping the summary structure to the client offloads much of the computational work from the server and accelerates the query processing by eliminating the client-server network delay.
6.3 Coherence Model Evaluation
In this section, we evaluate the benefits of using relaxed coherence models. In our experiments, the clients map the shared summary structure, perform iterative requests simulating a realistic data mining interaction, and synchronize with the server periodically. The server concurrently updates the shared data structure, reflecting changes to the actual data. Figure 5 reports the average synchronization time (time for a read acquire_lock, defined in Section 4.1, and used to bring the complex-object up-to-date according to the desired coherence model) for each of the applications under different coherence models. In these experiments, all clients use the same coherence model. We measured the synchronization time over a window of several (35 to be precise \(^8\)) synchronizations and averaged this time. This average synchronization time in seconds is represented on the Y axis. The X axis corresponds to the number of clients in the experiment.
Tables 4 through 7 present a breakdown of the total number of requests made by clients, and the total amount of data communicated under each of these coherence models for each of the applications. The first column represents the number of clients in the system. The subsequent columns represent the cumulative sum of the data sent out by the server to all the clients and the total number of requests made by all the clients, with each client performing 35 synchronization operations, for each of the coherence models evaluated for the application.
The average synchronization time can be broken down into two components, the communication overhead and the time spent waiting at the server. Due to limited resources, we could evaluate our work only on up to eight clients. Since the server is multi-threaded and has up to eight processors, we see very little increase in server load overheads with an increase in the number of clients. However, as the number of clients serviced by the server increases, the average synchronization times increase due to contention for network resources, as well as due to the fact that the server modification window is also consequently higher. This underscores the need to reduce
\(^8\)Going to larger window sizes did not affect the average synchronization times for our workloads.
communication and server load.
In order to evaluate the effect of the coherence model on performance, we begin by evaluating the effectiveness of using diffs (using \textbf{Polled Coherence}) as opposed to resending the entire complex-object (using \textbf{One-Time Coherence}), the strawman approach taken by most existing commercial object-oriented systems \footnote{Object techniques involving re-executing methods on all cached copies are not possible on data mining applications, since updates use large amounts of I/O, with the data residing only on the server. Hence, these approaches are not suitable for such applications.}. We found that sending diffs could be 10-30 times faster than resending the entire complex-object for reasonable-sized (10\% of nodes) changes made by the server. The size of the messages used to update the clients is much smaller, resulting in reduced communication overhead. The gains due to reduction in communication cost also reflect the reduction in overhead from client-server flow control due to finite buffer sizes.
We next evaluate the impact of having the flexibility of using different client-
<table>
<thead>
<tr>
<th>#C</th>
<th>Polled</th>
<th>Immediate</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Total Data</td>
<td># Requests</td>
</tr>
<tr>
<td>8</td>
<td>145306×32</td>
<td>280</td>
</tr>
<tr>
<td>4</td>
<td>74552×32</td>
<td>140</td>
</tr>
<tr>
<td>2</td>
<td>37276×32</td>
<td>70</td>
</tr>
<tr>
<td>1</td>
<td>18638×32</td>
<td>35</td>
</tr>
</tbody>
</table>
Table 4: Association Performance Breakdown
<table>
<thead>
<tr>
<th>#C</th>
<th>Polled</th>
<th>Immediate</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Total Data</td>
<td># Requests</td>
</tr>
<tr>
<td>8</td>
<td>85440×40</td>
<td>280</td>
</tr>
<tr>
<td>4</td>
<td>43402×40</td>
<td>140</td>
</tr>
<tr>
<td>2</td>
<td>20410×40</td>
<td>70</td>
</tr>
<tr>
<td>1</td>
<td>9744×40</td>
<td>35</td>
</tr>
</tbody>
</table>
Table 5: Sequence Mining Performance Breakdown
<table>
<thead>
<tr>
<th>#C</th>
<th>Polled</th>
<th>Diff(15)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Total Data</td>
<td># Requests</td>
</tr>
<tr>
<td>8</td>
<td>2013×24</td>
<td>280</td>
</tr>
<tr>
<td>4</td>
<td>973×24</td>
<td>140</td>
</tr>
<tr>
<td>2</td>
<td>393×24</td>
<td>70</td>
</tr>
<tr>
<td>1</td>
<td>207×24</td>
<td>35</td>
</tr>
</tbody>
</table>
Table 6: Discretization Performance Breakdown
controlled coherence models. For both association mining and sequence mining, we evaluated polled coherence and immediate coherence. Immediate coherence performs several factors better than polled coherence for these two applications. Polled coherence results in the client sending a request to the server at every synchronization point. Immediate coherence dictates that the server send a notification message to the client. On seeing the notification message at a synchronization point, the client polls the server for the update.
For association mining, the data communicated in both the immediate and polled cases is the same (Table 4). The synchronization rate is a function of the query processing time and the synchronization time. In this application, the query processing time dominates, resulting in the server modification window (the time between requests for updates) being roughly the same under both protocols. Additionally, the server updates in this application primarily involve adding and deleting nodes (see Table 1), explaining the total size of the changes being the same. However, there is a 75% decrease in the number of messages sent out under the former model. The synchronization rate is higher than the rate at which the server modifies data, resulting in unnecessary requests when using polled coherence. This results in a 3-fold performance improvement.
Sequence mining also sees a 3-fold improvement in synchronization time when using immediate coherence as opposed to polled coherence. There is a reduction not only in the number of requests but also in the total data communicated. In this
application, the query processing time is small. Hence, when synchronization time is reduced, the server modification window is also smaller. In addition, this application primarily modifies existing nodes (see Table 1). These factors combine to reduce the amount of data. The synchronization rate in this application is fairly close to the rate at which the server modifies data. Hence, due to timing variations in receiving notifications with immediate coherence, some of the synchronization operations remain local and do not request updates, resulting in a 2-fold reduction in the number of requests.
6.3.1 Diff-based and Delta Coherence Model Evaluation
While association mining and sequence mining benefit from sending updates rather than the entire complex-object, they both require the client to have the latest copy of the shared data. However, discretization and similarity discovery can tolerate some staleness in the interaction structure without losing much accuracy.
Discretization can make use of the diff-based coherence model since we know that the quality of discretization is not affected by small changes in the shared data (we quantify this in the next paragraph). Similarity discovery does not benefit as much from diff-based coherence since every server update is likely to modify roughly 10% of one of the summary structures, or 1600 nodes (see Table 1), which far exceeds the diff parameter that we use. The number in brackets for diff-based coherence in Figures 5 and 7 is the diff parameter, or the number of nodes that must be modified to trigger an update to the client (set to 15).
However, similarity discovery benefits more from the delta coherence model due to the fact that the result quality is affected more by the magnitude of the change in data than by the amount of data that has changed. The magnitude of change per server update is small, while the number of nodes changed is about 10%. The number in brackets for delta coherence is the maximum number of server updates (or versions; corresponding to releasing a write lock) between updates to the client. For these applications, we compare the average synchronization times with polled
coherence (object resends are always going to be worse than polled coherence).
Referring to Figure 5 for discretization, we find that diff-based coherence, when using a diff parameter of 15, was on average twice as efficient as polled coherence. This difference increases as the diff parameter is increased. For a diff parameter of 100 we found that the average synchronization time is 15-20 fold better. Delta coherence is particularly effective for similarity discovery, outperforming polled coherence by three orders of magnitude at low server load.
In both of these applications (referring to Tables 6 and 7) there is a reduction not only in the number of requests but also in the total data communicated. While part of the reason for this behavior is the same as discussed earlier for association and sequence mining, the main cause for this reduction is the applications’ tolerance for staleness as specified by the relaxed coherence models.
6.4 Client-Controlled Coherence
An important contribution of our system is the fact that different clients may map the same shared structure using different coherence models. As an example, a client interested in similarity discovery involving a particular database could map the association lattice (as described in Section 5) of the database using the delta coherence model. The same lattice may be mapped by another client for the purpose of association
mining using the polled coherence model.
In this experiment, we considered the following configurations. In the polled configuration, all eight of our clients used polled coherence. In the delta configuration, all eight used delta coherence. In the mixed configuration, four used delta coherence and four used polled coherence.
We found the average synchronization time of clients under polled coherence in the Mixed configuration to be slightly lower due to reduced traffic, and that for clients using delta coherence to be slightly higher due to the extra traffic from the clients using polled coherence. The average synchronization times of clients under delta coherence in the Mixed experiment were two orders of magnitude lower than those for when all the clients mapped the data using polled coherence. If client-controlled coherence were not used, the server would have to adhere to the strictest coherence model for correctness, in this case, polled coherence, resulting in much reduced performance. Thus, by using the coherence model required by each client, the server is able to improve overall performance.
6.5 Interaction Quality
The above results indicate that encoding knowledge about application behavior by choosing the appropriate coherence model can improve performance. This improved performance comes about due to reduced resource consumption (server processing time, low network utilization). However, to better understand the implications of lower resource usage one must also evaluate the corresponding loss in result quality for the application when using more relaxed coherence models. Such resource-aware computing issues have been studied in the context of other domains such as mobile-computing[43] and multimedia-computing[31, 32] and we apply a similar analysis below for discretization and similarity discovery.
For each of these two applications, we plotted the result quality under the different coherence protocols over a certain period of time (demarcated by server updates). Figure 7 presents these results. For discretization, the result quality is represented by
the classification error — the fraction of points in the space that are mis-classified. The plot for polled coherence represents the best achievable classification error for the algorithm. The plot for diff-based coherence (with a diff parameter of 100 as opposed to 15) is the error obtained when using a relaxed coherence model. Clearly, for this application the loss in quality is not significant. In fact, it is off by less than 1% of the exact error at all instances in time even for such a high diff parameter. For similarity discovery, the result quality is represented by the similarity value, which represents the distance between two datasets. The similarity value using delta coherence is no worse than 2% off the value obtained using polled coherence at all instances in time. For more details on the network-aware adaptive nature of these two application, readers are referred to a recent paper[34].
6.6 Effect of Modification Rate
In order to evaluate the impact of the server modification rate on our choice of coherence model, we modified the similarity discovery experiment described in the previous sections in the following ways. Two of the four lattices that we map have server update characteristics as described in Table 1, Similarity (1). For the other two lattices, we used the server update characteristics described under Similarity(3), where each server update modifies less that 0.1% of the data structure. Each lattice is maintained by a separate server process running on our 8-processor server.
We then evaluated the average synchronization time for one client in the system.
Figure 8: Effect of Transaction Rate on Similarity Performance
while varying the server updates per second. We varied \textit{diff}, the diff parameter or the number of nodes that differ before an update is sent to the client, from 10 to 100 for diff-based coherence (see Figure 8). We also varied \textit{delta}, the number of virtual time intervals between successive updates to the client, from 10 to 100 for delta coherence. The larger the diff/delta values, the lower the average synchronization time. The delta-based approach still does better for this application at a low server update rate since it minimizes the communication with the client. However, at larger update rates (crossover point 230 ups), diff-based coherence (\textit{diff\_num} = 100) begins to perform better than delta coherence. The reason for this is that at higher update rates, updates to the client are sent too frequently (in other words, a \textit{delta\_num} of 100 is too low) for all the complex-objects. However, since only two of the four lattices have a large percentage modified per update, for a \textit{diff} value of 100, only these two lattices will cause updates to be sent to the client. The other two lattices are not modified at the same rate, resulting in lower average synchronization times when using diff-based coherence with a \textit{diff} value of 100.
This experiment highlights the influence of server update properties on the choice of a coherence model, as well as the importance of being able to dynamically change coherence requirements as the application behavior changes. Choosing among relaxed coherence models is not only a function of what the application can tolerate in terms of data staleness, but also a function of how much and how often changes are made to the shared summary structure, in order to be effective.
6.7 Locality Enhancements
Locality enhancing memory placement is especially useful when the client uses a predefined traversal of the shared summary structure. We illustrate its benefits using association mining, where we found that for different queries, a different mapping of the data structure presented the best results. For example, when computing the most frequent associations (sometimes referred to as quantified associations) a breadth first representation of the lattice is most often desired since the more frequent an association is the closer it is likely to be to the root of the lattice. One can be more exact using the user-defined memory placement for this query. When computing inclusive associations whereby one desires to find all associations involving a particular item then the traversal is typically a depth-first traversal. In such cases one may want to use a depth first memory placement of the lattice. These different association queries are commonly used in online association mining [1, 33]. For these queries, we found up to a 20% improvement in execution times by remapping the data structure according to the best mapping strategy.
7 Conclusions and Future Directions
We have described a general runtime framework that supports efficient data structure sharing among distributed and interactive components of client-server applications. While the system is general enough to support a wide range of application domains, in this paper we have demonstrated the utility of the system for, and evaluated its performance on, a suite of interactive data mining applications. The runtime interface enables clients to cache relevant shared data locally, resulting in faster (up to an order of magnitude) response times to interactive queries. In the event that this shared data is modified, the complexity of determining exactly what data to communicate among clients and servers, as well as when that data must be communicated, is encapsulated within the runtime system. Each process has the ability to use the dynamically modifiable relaxed coherence mechanisms to encode application-specific knowledge about sharing behavior and requirements on a per data structure basis.
This information can then be used by the runtime to further reduce communication time potentially by several orders of magnitude. For those applications in our test suite that can take advantage of the more relaxed coherence protocols, we have also shown that the degradation in result quality is less than 2%. In addition, the anytime update and client-controlled memory placement features made possible by the address-independent virtual memory-based design of the runtime system help improve the performance of several data mining applications.
Further refinement of the system involves improved support for heterogeneous platforms as well as integration with tightly-coupled software shared memory systems [10, 42]. The latter integration will provide the ability for remote satellites to interact with computationally intensive components that require tightly-coupled parallel processing. The resulting system, called InterWeave [9], is on-going work and represents a merger and extension of our previous Cashmere [49] and InterAct systems, combining hardware coherence within small multiprocessors, Cashmere-style lazy release consistency within tightly coupled clusters, and InterAct-style version-based coherence for distributed shared segments.
**Acknowledgements:** Thanks to the anonymous reviewers for their useful feedback, which enabled us to improve the quality of this article.
References
[10] D. Chen, S. Dwarkadas, S. Parthasarathy, E. Pinheiro, and M. L. Scott. Inter-
Weave: A Middleware System for Distributed Shared State. In Fifth Workshop
on Languages, Compilers, and Runtime Systems (LCR) 2000, Rochester, NY,
May 2000.
probes. In Proceedings of the 4th Symposium on Knowledge Discovery and Data-
Mining, 1998.
[14] P. Dewan and J. Riedl. Towards computer-supported concurrent software engi-
worlds. In European Conference on Computer Supported Collaborative Work,
1995.
Memory consistency and event ordering in scalable shared-memory multiproces-
programming environment for cooperative engineering design. In *AI in Engin-
Parthasarathy, and M. Scott. Cashmere-2L: Software Coherent Shared Mem-
ory on a Clustered Remote-Write Network In *Symposium on Operating Systems
In *Proceedings of Workshop on Distributed Data Mining, alongwith KDD98*, Aug
1998.
Hauser. Managing update conflicts in bayou, a weakly connected replicated
[53] M. vanSteen, P. Homburg, and A.S. Tanenbaum. The architectural design of
[54] P. R. Wilson. Pointer Swizzling at Page Fault Time: Efficiently and Compat-
ibly Supporting Huge Address Spaces on Standard Hardware. In *International
distributed shared memory. In *Proceedings of the First USENIX Symposium on
A Footnotes
* This is an expanded version of our conference paper in the First SIAM International Conference on Data Mining [36]. This work was supported in part by NSF grants CDA–9401142, EIA–9972881, CCR–9702466, CCR–9988361, and CCR–9705594; and an external research grant from Compaq.
1. Note that our implementation of a write lock is relaxed, in the sense that readers are permitted during a lock held in write mode.
2. Each complex-object is mapped to a disjoint set of pages, which enables our system to transparently detect changes to objects using virtual memory hooks. Since we are dealing with applications where the complex-objects are reasonably large relative to the size of a page, this does not result in memory wastage.
3. Note that since complex-objects can dynamically change in size, all the pages for a complex-object need not be contiguous, so a slightly modified form of array indexing is needed.
4. In order to guarantee an atomic update, the data cannot be sent in an as is condition, as partial changes to the object may have occurred concurrently.
5. Clients need to execute this only once. Subsequent updates from the server are automatically handled correctly by our system’s address translation mechanisms.
6. Support is the number of times the pattern occurs in the dataset.
7. The datasets used are described in [41].
8. Going to larger window sizes did not affect the average synchronization times for our workloads.
9. Object techniques involving re-executing methods on all cached copies are not possible on data mining applications, since updates use large amounts of I/O, with the data residing only on the server. Hence, these approaches are not suitable for such applications.
B Figure Captions
- Figure 1: Interactive Client-Server Mining
- Figure 2: Server-Side Pseudo Code: InterAct method-calls are shown in **bold**
- Figure 3: Client-Side Pseudo Code: InterAct method-calls are shown in **bold**
- Figure 4: Efficient Shared Data Updates
- Table 1: Server Update Properties
- Table 2: Time (in seconds) to Execute Query: 100Mbps Interconnect
- Table 3: Time (in seconds) to Execute Query: 10Mbps Interconnect
- Figure 5: Coherence Model Evaluation
- Table 4: Association Performance Breakdown
- Table 5: Sequence Mining Performance Breakdown
- Table 6: Discretization Performance Breakdown
- Table 7: Similarity Performance Breakdown
- Figure 6: Effect of Client Controlled Coherence on Similarity Performance
- Figure 7: Result Quality
- Figure 8: Effect of Transaction Rate on Similarity Performance
|
{"Source-Url": "http://web.cse.ohio-state.edu/dmrl/papers/dapd.pdf", "len_cl100k_base": 15226, "olmocr-version": "0.1.50", "pdf-total-pages": 43, "total-fallback-pages": 0, "total-input-tokens": 159097, "total-output-tokens": 19911, "length": "2e13", "weborganizer": {"__label__adult": 0.0003113746643066406, "__label__art_design": 0.00035309791564941406, "__label__crime_law": 0.0003428459167480469, "__label__education_jobs": 0.0010852813720703125, "__label__entertainment": 9.810924530029296e-05, "__label__fashion_beauty": 0.0001595020294189453, "__label__finance_business": 0.0003135204315185547, "__label__food_dining": 0.0003323554992675781, "__label__games": 0.0010404586791992188, "__label__hardware": 0.0018215179443359375, "__label__health": 0.0004897117614746094, "__label__history": 0.0003972053527832031, "__label__home_hobbies": 0.00011390447616577148, "__label__industrial": 0.0006222724914550781, "__label__literature": 0.00030517578125, "__label__politics": 0.0002536773681640625, "__label__religion": 0.0005726814270019531, "__label__science_tech": 0.12152099609375, "__label__social_life": 8.380413055419922e-05, "__label__software": 0.02178955078125, "__label__software_dev": 0.84716796875, "__label__sports_fitness": 0.0002524852752685547, "__label__transportation": 0.00046944618225097656, "__label__travel": 0.00022494792938232425}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 81659, 0.03728]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 81659, 0.38959]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 81659, 0.89]], "google_gemma-3-12b-it_contains_pii": [[0, 2521, false], [2521, 4757, null], [4757, 7167, null], [7167, 9413, null], [9413, 11659, null], [11659, 13777, null], [13777, 16225, null], [16225, 17343, null], [17343, 19388, null], [19388, 22013, null], [22013, 24356, null], [24356, 26757, null], [26757, 29007, null], [29007, 30463, null], [30463, 32616, null], [32616, 34895, null], [34895, 37015, null], [37015, 39518, null], [39518, 41916, null], [41916, 44035, null], [44035, 45925, null], [45925, 47957, null], [47957, 50146, null], [50146, 52455, null], [52455, 53596, null], [53596, 54751, null], [54751, 56376, null], [56376, 58558, null], [58558, 59966, null], [59966, 62073, null], [62073, 63683, null], [63683, 65521, null], [65521, 67726, null], [67726, 69122, null], [69122, 70729, null], [70729, 72333, null], [72333, 74144, null], [74144, 75787, null], [75787, 77524, null], [77524, 79102, null], [79102, 80562, null], [80562, 80828, null], [80828, 81659, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2521, true], [2521, 4757, null], [4757, 7167, null], [7167, 9413, null], [9413, 11659, null], [11659, 13777, null], [13777, 16225, null], [16225, 17343, null], [17343, 19388, null], [19388, 22013, null], [22013, 24356, null], [24356, 26757, null], [26757, 29007, null], [29007, 30463, null], [30463, 32616, null], [32616, 34895, null], [34895, 37015, null], [37015, 39518, null], [39518, 41916, null], [41916, 44035, null], [44035, 45925, null], [45925, 47957, null], [47957, 50146, null], [50146, 52455, null], [52455, 53596, null], [53596, 54751, null], [54751, 56376, null], [56376, 58558, null], [58558, 59966, null], [59966, 62073, null], [62073, 63683, null], [63683, 65521, null], [65521, 67726, null], [67726, 69122, null], [69122, 70729, null], [70729, 72333, null], [72333, 74144, null], [74144, 75787, null], [75787, 77524, null], [77524, 79102, null], [79102, 80562, null], [80562, 80828, null], [80828, 81659, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 81659, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 81659, null]], "pdf_page_numbers": [[0, 2521, 1], [2521, 4757, 2], [4757, 7167, 3], [7167, 9413, 4], [9413, 11659, 5], [11659, 13777, 6], [13777, 16225, 7], [16225, 17343, 8], [17343, 19388, 9], [19388, 22013, 10], [22013, 24356, 11], [24356, 26757, 12], [26757, 29007, 13], [29007, 30463, 14], [30463, 32616, 15], [32616, 34895, 16], [34895, 37015, 17], [37015, 39518, 18], [39518, 41916, 19], [41916, 44035, 20], [44035, 45925, 21], [45925, 47957, 22], [47957, 50146, 23], [50146, 52455, 24], [52455, 53596, 25], [53596, 54751, 26], [54751, 56376, 27], [56376, 58558, 28], [58558, 59966, 29], [59966, 62073, 30], [62073, 63683, 31], [63683, 65521, 32], [65521, 67726, 33], [67726, 69122, 34], [69122, 70729, 35], [70729, 72333, 36], [72333, 74144, 37], [74144, 75787, 38], [75787, 77524, 39], [77524, 79102, 40], [79102, 80562, 41], [80562, 80828, 42], [80828, 81659, 43]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 81659, 0.08936]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
d87b8007cb740d53ff2a0a7ee6b57fefeedb0846
|
A Hybrid Communications Network Simulation-Independent Toolkit
David M. Dines
Follow this and additional works at: https://scholar.afit.edu/etd
Part of the Computer Sciences Commons
Recommended Citation
https://scholar.afit.edu/etd/2749
This Thesis is brought to you for free and open access by the Student Graduate Works at AFIT Scholar. It has been accepted for inclusion in Theses and Dissertations by an authorized administrator of AFIT Scholar. For more information, please contact richard.mansfield@afit.edu.
A HYBRID COMMUNICATIONS NETWORK SIMULATION-INDEPENDENT TOOLKIT
THESIS
David M. Dines, BA
Major, USAF
AFIT/GCS/ENG/08-08
DEPARTMENT OF THE AIR FORCE
AIR UNIVERSITY
AIR FORCE INSTITUTE OF TECHNOLOGY
Wright-Patterson Air Force Base, Ohio
APPROVED FOR PUBLIC RELEASE; DISTRIBUTION UNLIMITED
The views expressed in this thesis are those of the author and do not reflect the official policy or position of the United States Air Force, Department of Defense, or the U.S. Government.
A HYBRID COMMUNICATIONS NETWORK SIMULATION-INDEPENDENT TOOLKIT
THESIS
Presented to the Faculty
Department of Electrical and Computer Engineering
Graduate School of Engineering and Management
Air Force Institute of Technology
Air University
Air Education and Training Command
In Partial Fulfillment of the Requirements for the
Degree of Master of Science (Computer Science)
David M. Dines, BA
Major, USAF
March 2008
APPROVED FOR PUBLIC RELEASE; DISTRIBUTION UNLIMITED
A HYBRID COMMUNICATIONS NETWORK SIMULATION-INDEPENDENT TOOLKIT
David M. Dines, BA
Major, USAF
Approved:
/Signed/ 6 Mar 08
Kenneth M. Hopkinson, PhD (Chairman) Date
/Signed/ 6 Mar 08
Jeffrey T. “Todd” McDonald, PhD (Member)
Lieutenant Colonel, USAF Date
/Signed/ 6 Mar 08
Stuart H. Kurkowski, PhD (Member)
Lieutenant Colonel, USAF Date
Abstract
Net-centric warfare requires information superiority to enable decision superiority, culminating in insurmountable combat power against our enemies on the battlefield. Information superiority must be attained and retained for success in today’s joint/coalition battlespace. To accomplish this goal, our combat networks must reliably, expediently and completely deliver over a wide range of mobile and fixed assets. Furthermore, each asset must be given special consideration for the sensitivity, priority and volume of information required by the mission. Evolving a grand design of the enabling network will require a flexible evaluation platform to try and select the right combination of network strategies and protocols in the realms of topology control and routing. This research will result in a toolkit for ns2 that will enable rapid interfacing and evaluation of new networking algorithms and/or protocols. The toolkit will be the springboard for development of an optimal, multi-dimensional and flexible network for linking combat entities in the battlespace.
Acknowledgments
I would like to thank my Advisor, Dr Kenneth Hopkinson, for his generosity in time, talent and spirit.
I owe special thanks to my wife and our three beautiful children for their love and patience during my effort to complete this document and the degree program.
David Dines
Table of Contents
Abstract................................................................................................................................v
Acknowledgments.............................................................................................................. vi
Table of Contents.............................................................................................................. vii
List of Figures ................................................................................................................... ix
List of Tables ..................................................................................................................... x
I. Introduction .....................................................................................................................1
II. Literature Review ...........................................................................................................3
Chapter Overview.........................................................................................................3
Relevant Research ........................................................................................................3
synTraff .................................................................................................................. 3
SyncML Development Toolkit ............................................................................ 4
WiDS implements Distributed Systems (WiDS) .................................................... 6
MarNET ............................................................................................................... 8
Electric Power and Communication Synchronizing Simulator (EPOCHS) ....... 9
Software Engineering Principles ................................................................................11
Software Toolkits ..................................................................................................... 11
Design Patterns ..................................................................................................... 13
III. Methodology ...............................................................................................................18
Introduction ..............................................................................................................18
Existing Architecture and Design ..........................................................................18
Ns2 Architecture ................................................................................................. 18
Routing and Topology Control Algorithms ..................................................... 20
Fault-Tolerant Routing Algorithm ................................................................. 22
List of Figures
Figure 1. GUI for SynTraff Suite of Toolkits ................................................................. 4
Figure 2. Functional Architecture of the SyncML agent toolkit ...................................... 6
Figure 3. The WiDS architecture .................................................................................. 7
Figure 4. The MarNET Toolkit daemon ........................................................................ 8
Figure 5. EPOCHS Component Relationships .............................................................. 10
Figure 6. The split architecture of ns2 ....................................................................... 19
Figure 7. Class model for Garner’s routing and topology control algorithm ............... 21
Figure 8. Class model for Llewellyn’s fault-tolerant routing algorithm in ns2 ........... 23
Figure 9. HCNeT Use Case Model ............................................................................. 25
Figure 10. HCNeT Phased, Iterative Development Plan ............................................... 26
Figure 11. HCNeT Architectural Overview ................................................................. 28
Figure 12. HCNeT Sequence Overview ..................................................................... 29
Figure 13. Class model for HCNeT network toolkit ................................................... 31
List of Tables
Table 1. Relationships between Metrics and Quality Model Attributes............................. 40
Table 2. Maintainability Measurements, HCNeT vs AgentHQ............................................. 41
A HYBRID COMMUNICATIONS NETWORK SIMULATION-INDEPENDENT TOOLKIT
I. Introduction
As the military moves towards a more information-rich environment on the battlefield, network protocol developers need a mobile networking toolkit that allows rapid prototyping and experimentation of the components needed to make Net-centric Warfare a reality. Existing AFIT research in dynamic topology control [15] and fault-tolerant routing [9] algorithms build individual components for testing on a static network simulation. However, designing mobile networking platforms that effectively combine these components together is extremely difficult. Protocol developers need a simulation toolkit that breaks the mobile networking problem down into a series of modularized components for use in a well-known simulation platform like ns2. This toolkit will enable rapid prototyping of protocol combinations, thereby allowing developers to evaluate which combinations make the most sense for military communication systems of the future.
The project goal is to produce an extensible toolkit for use in modeling and evaluating the intersection of new distributed hybrid network algorithms in the ns2 simulation environment while remaining extendable to other network simulation applications. The design effort will apply well-known concepts in object-oriented software engineering patterns [7][8][12][16] and modular networking architectures [2][10][13][17] along with knowledge of the ns2 platform architecture [6][5] to implement a specialized network toolkit for use in ns2. Existing routing and topology algorithms
will be carefully studied and redesigned to meet the programming interface of the toolkit.
Future protocol developers will use the API, allowing immediate hot-swappable
integration of algorithmic components within the simulation.
I organize this document as follows. Chapter 2 provides a background of software
ing engineering principles and existing source code. Chapter 3 describes in detail the toolkit
design decisions. Chapter 4 describes the toolkit implementation and structural metrics.
Chapter 5 summarizes the research contributions and suggestions for future work.
II. Literature Review
Chapter Overview
The purpose of this chapter is to introduce the reader to several relevant software development projects that utilized the toolkit concept to implement networking simulations. Previous research is examined to expose design considerations and to demonstrate the usefulness of developing toolkits for network simulations. Next, an exploration of the definition of a software toolkit reveals a general direction for the design process. Finally, a brief review of software design patterns is presented as they are the basis of maintainable and extensible programs and present excellent opportunities for toolkit implementation.
Relevant Research
Software research and development efforts focus on building and using toolkits in distributed communications systems. From these sources, one can gain an understanding of this development domain and garner ideas for implementing a successful toolkit.
synTraff
Balakrishnan and Williamson [1] present a suite of toolkits for analysis, modeling and generation of long-range dependent network traffic called synTraff. Each toolkit in the suite provides a common Tcl/Tk interface to a set of related C/C++ programs for traffic generation and analysis. This GUI approach allows a user to select from a wide range of network settings to generate a specific model of network traffic. Figure 1 depicts the GUI set for synTraff.
A key advantage for SynTraff is its approachability by users who are not well versed in software implementation. A protocol developer can use the toolkit to implement the affects of new protocol on network traffic and present that protocol as a network setting for the GUI. A researcher may then apply the protocol easily by turning it on or off, or swapping it out for another related protocol. Together with other system parameters, the researcher can compare network traffic metrics and draw conclusions without knowledge of the detailed system implementation.
**SyncML Development Toolkit**
Tong [17] produced a toolkit for the development of the SyncML (a universal data synchronization format based on XML) device management protocol. The purpose
of a device manager is to register, configure and implement independent services on a particular device, such as a cell phones and personal data assistants. A service should come packaged with a management agent to allow the service to operate on the device.
The toolkit automates the design and implementation of a device specific SyncML agent. The target usage is to input the device management tree specification and to output a generic agent skeleton requiring minimal modification for a specific device customization. Thus, a device-specific agent can be obtained by starting with an empty agent skeleton and extending it with a complete device management tree specification.
The SyncML Development Toolkit is essentially a framework builder that issues a base type of device management agent that may be customized through extension to accommodate a particular device. Figure 2 depicts the framework and the extension points for the device manager developer.
**WiDS implements Distributed Systems (WiDS)**
Shiding Lin, Aiman Pan and Zheng Zhang[13] of Microsoft Research Asia, along with partners from universities at Beijing and Tsinghua, devised a toolkit to optimize the process of developing and testing distributed systems algorithms. The WiDS toolkit adopts an object-oriented and event-driven programming model and provides a small and straightforward set of APIs to support message exchanges and timers. The APIs isolate a WiDS-programmed protocol from any particular runtime that users want to employ. A WiDS object represents a protocol instance or a service. WiDS objects exchange asynchronous messages to each other. Each message is dispatched to the target object’s
corresponding handler through the use of an event wheel. In this way, the WiDS architecture allows different runtimes to be shaped by integrating some of the four modules: topology model, networking, system timer and event wheel. Figure 3 presents a model of this architecture.
The WiDS design offers modularity in a powerful way. The four modules can be independently extended and assembled to address the requirements of a new protocol. If extended polymorphically, the architecture can maintain protocol compatibility. For example, a single Topology model could work with a new protocol while remaining compatible with any other protocol previously developed.
![Figure 3. The WiDS architecture [13]](image)
WiDS presents a closed simulation environment where different protocols may be evaluated [13]. However, this implementation does not allow a researcher to investigate
protocol performance across any other established simulation platforms such as ns2 or OPNET.
**MarNET**
Battenfield [2] presents a modular routing architecture in a single concise interface which facilitates the construction of routing modules that can be used in a particular mobile ad hoc network emulation system MarNET and on any computer system running Linux. The constructed routing modules may be run within the emulator or ported to operational hardware without changing program code or recompiling.
Figure 4. The MarNET Toolkit daemon [2]. MarNET provides the application developer with ready to deploy routing modules. The algorithm developer implements the MarNET routing API along with configuring the routing daemon.
MarNET offers a hierarchical and modular approach for developing and implementing dynamic routing applications as depicted in Figure 4. Further, MarNET offers a portable framework for implementation and evaluation on multiple hardware platforms. However, MarNET does not offer an API explicitly for topology control and can not be used for rapid prototyping of new routing and topology control algorithms. A routing algorithm developer must configure the routing daemon behind the Routing API to ensure operability. As with other simulation toolkits, MarNET employs its own emulator so testing and verification rely on one simulation environment.
*Electric Power and Communication Synchronizing Simulator (EPOCHS)*
Hopkinson, Wang, et al. [10] present a toolkit called EPOCHS that integrates research and COTS software to provide users a way to evaluate new communications protocols as they relate to electric power control scenarios. EPOCHS smartly links varying existing simulation engines using only their built-in APIs. Further, the system is agent-based which hides the complexity of the combined system, making it easy for users to design new power scenarios involving communication. The system is based on a publish/subscribe mechanism, where any simulation entity subscribing to another will receive all of its updated information, whether or not it is needed.
In EPOCHS, users interact with the system through the use of agents. In this context, agents are autonomous, interactive computer programs which may exhibit mobility, intelligence, adaptability, and communication. Agents conform to an API that hides the differences between the various simulators and essentially makes it easier for users to implement EPOCHS. The team developed AgentHQ to act as a proxy between agents to facilitate agent interaction.
A runtime infrastructure (RTI) routes all messages between simulation components and ensures the simulation time is synchronized across all components. Figure 5 presents the EPOCHS component relationships, note that NS2, PSLF and PSCAD/EMTD are the existing simulators that EPOCHS combines.

The RTI presents a single view of a generic simulation engine. This is a powerful concept that allows the development of networking protocols without knowledge of a specific simulation environment. Furthermore, any protocol developed to the RTI may be implemented in any simulation environment that has a custom module developed for it. In EPOCHS, an expert in one simulation environment can develop a custom module for the RTI independent of any specific protocol written to the RTI.
While EPOCHS was developed for electric power control applications, the simulator independent nature of the implementation as enabled by the RTI proves an interesting model for a network simulation-independent toolkit.
**Software Engineering Principles**
Development of a network simulation toolkit relies heavily on a clear definition of what a software toolkit should be and a solid understanding of flexible and extensible implementation techniques collectively known as design patterns.
**Software Toolkits**
**tool** (ˈtül, noun): 1a. a handheld device that aids in accomplishing a task.
2a. an instrument or apparatus used in performing an operation or necessary in the practice of a vocation or profession. 2b. an element of a computer program that activates and controls a particular function. [4]
Tools allow people to quickly and easily perform a task that would otherwise be time consuming, laborious or impossible to perform. Tools in software development are useful to abstract specific functions, allowing the user to focus on the interface and results of a software component rather than consume time and effort on understanding its design details. The user of a tool needs only the knowledge of when or how to use the tool. A particularly effective tool accomplishes a specific task, is easy to implement and easy to validate. Furthermore, a software tool may need to accept adjustments as with a torque wrench, to meet unique and specific requirements. For example, a software tool
for implementing a graphical window may have many parameters to aid in adjustment of shape, size, color and contents.
A toolkit is a collection of tools that work in concert to perform a range of tasks within a specific field of endeavor. For example, a dental hygienist’s toolkit would contain a variety of medical instruments needed to maintain healthy teeth and gums. However, if the concept of a toolkit is scoped too large, such as “medical toolkit”, the toolkit could never be assembled in a useful way since the whole medical field is as wide as it is deep.
Likewise, a toolkit in software is a set of general, yet related functions that can be called in some combination to implement a specific software function. For example, a GUI toolkit provides a set of general graphical elements for an application designer to draw from. The graphical elements, such as buttons or scroll bars, are available as objects that may be adjusted and extended to meet the specific needs of the designer. A toolkit enables sound implementation by leading the developer toward code reuse [12].
There is no standard way to implement a toolkit in software. A toolkit could be a single class that provides instances of a related set of objects. Alternatively, Booch [3] states that a software toolkit is a general purpose library of predefined classes that may be instantiated or extended in user-defined combinations to serve a specific requirement. A toolkit is useful in a particular application domain; however a good toolkit will not impose a particular design on the user.
One example from Booch’s definition is the Java collections library [16]. This library offers a base class called Collection that defines the abstraction of a collection of
objects. Other classes provide a variety of specific collection types that may be implemented in general ways by a programmer.
Further, toolkits can be geared toward use within development frameworks. A framework is an architectural pattern that provides an extensible template for applications within a domain [3]. For example, a framework can be geared toward providing an interactive animation for first-person video games. Many unique video games could implement the framework since each game would customize the graphics, interactions and game rules. A framework could be provided as an architectural foundation designed to use a toolkit for customization. To do this, the framework would encapsulate the skeleton of the overall application design and the toolkit would offer a variety of ways to customize, control and implement the framework. This framework-centered toolkit is obviously limited in its applicability to the framework itself, but can still empower its user within the application domain.
A toolkit for network protocol simulation development will provide the components of a network object model offering a variety of ways to define the network and its protocols. A simulation framework must be provided to ensure consistent transition of the simulation through user-defined and framework-provided events.
*Design Patterns*
Software design patterns have emerged as crucial tools for developing maintainable software. Design patterns reinforce object-oriented design principles, offer a standard for communicating architectural solutions and provide implementation strategies for common software design problems [16].
HCNeT design relies on several design patterns as described by Gamma, Helm, Johnson and Vlissides [8], collectively known as the “Gang of Four”. The following paragraphs provide definitions and summaries of the design patterns that will be referred to by name throughout this paper.
Decorator
The intent of the decorator pattern is to add additional state and behaviors to an object at runtime. This allows an application to handle new responsibilities as they arise. Likewise, with the decorator pattern, an object can shed or ignore particular state and behaviors whenever necessary. In this sense, thedecorator is also known as a “wrapper” that can be applied and removed from the object depending on which decoration is required during runtime.
The decorator pattern should be useful for a toolkit that must offer a flexible and dynamically changing definition of a particular object’s state.
Visitor
The visitor pattern offers a way to traverse an object structure while performing operations along the way. Each object in the structure must accept the visitor, and then in turn pass its reference back to the visitor. A traversal happens when one upper-level object accepts the visitor, and then forwards the visit request to the next object in the structure. This behavior is repeated until all objects in the structure are visited.
Applied correctly, the visitor pattern decouples the object structure from an object that must operate on the structure in unexpected ways. Furthermore, the visitor pattern increases cohesiveness of the members of the object structure, by allowing other objects
to handle distinct yet unrelated operations. Finally, visitor provides a class design that is smartly built for frequent extension.
Extensibility is a desirable feature for a software toolkit. Furthermore, The visitor pattern could work well with a network structure composed of interlinking nodes and with object decorators. Recall, the decorator pattern represents a layering of wrappers in a hierarchical composite object structure.
Strategy
The intent of the strategy pattern is to make interchangeable the variations within a family of algorithms. That is, if an object has a particular job to do and many different methods to do that job, then encapsulate each method while hiding how the job gets done.
The strategy pattern makes sense for network nodes that are responsible for routing and the way the routing is performed may be switched out dynamically in response to environmental conditions. This also makes sense for a network that must implement various ways of performing topology control.
Bridge
The bridge pattern decouples an abstract structure from its implementation. This decoupling allows independent variation of the implementation.
This pattern should be useful to define how a network model interacts with various different simulation frameworks. Once the interaction between a network structure and a simulator is defined, a developer could use a bridge to implement those interactions for a particular simulator.
Abstract Singleton
The abstract singleton pattern is not a name found in textbooks, but it is a combination of the abstract factory, factory method and singleton found in [8]. This pattern presents an abstract interface to a singleton object whose specific implementation is determined by the environment, but unknown to the requester. To implement this pattern, a scaled down Abstract Factory class has a Factory Method called getInstance(). The method getInstance() will check a system variable to determine which implementation of the singleton to return. This pattern isn’t necessarily a factory since the varying instantiations of the abstract interface are created at software load time and registered within the abstract factory.
Abstract singleton is a pattern that could be used to create the bridge object reviewed in this chapter. In this way a protocol application will run with any pre-defined simulation framework without need for modification.
Observer
The intent of the observer pattern is to notify many objects when a particular object has changed. The observer pattern also limits coupling by allowing one or more widely different objects to gain access to another object without containing the target object.
An observer pattern may benefit a toolkit that must remain flexible. For example, if a bridge is used to decouple the toolkit from its platform, an observer could decouple the toolkit from the bridge. Furthermore, an observer could be used to help synchronize
the actions between network topology and routing, without the two algorithms accounting
for which specific strategies are being applied.
III. Methodology
Introduction
Before undertaking a significant software design and refactoring project, a developer must review sound software engineering principles that may contribute to the project. Further, the existing code base must be analyzed to identify requirements and opportunities for code refactoring.
Existing Architecture and Design
The primary purpose for HCNeT is to allow user-defined combinations of existing network algorithms within the Ns2 environment. Therefore, this development effort requires an understanding of how to extend Ns2. In addition, previous work in routing and topology control were selected by the customer for refactoring into HCNeT with the expressed purpose of mixing and matching these works.
Ns2 Architecture
The network simulator NS is a discrete event network simulator developed at UC Berkeley that focuses on the simulation of IP networks on the packet level [6]. Ns2 is a framework for demonstrating network protocols; the design of Ns2 drives the implementation of any protocol. In this context, a protocol developer must expend considerable effort to learn the framework before implementing the protocol within it. While Ns2 is extensible, it is not effective as a toolkit in itself.
To use NS for setting up and running a network simulation, a user writes a simulation program in OTCL script language. Such an OTCL script initiates an event scheduler, sets up the network topology and tells traffic sources when to start and stop
transmitting packets through the event scheduler. The prevalence of OTCL within Ns2 reveals that, first and foremost, Ns2 is a split framework. All objects in Ns2 have an implementation in both OTCL and C++ as shown in Figure 6. This split framework is meant to offer simplicity of OTCL for frequently changing functionality and the efficiency of C++ for static, time-intensive functions [11].
Figure 6. The split architecture of ns2 [6]
The requirements leading to a split framework in Ns2 work against the needs of AFIT protocol developers since they develop protocols to resolve NP-Complete and NP-Hard classes of problems. These protocols are very time-intensive, yet need to be
interchanged and reconfigured often. So, AFIT requirements drive for one environment to handle functions that are both time-intensive and frequently changing.
Another consequence of the split design is the need to create and correctly bind a mirror class for every class a user develops in either side of the framework. As a result, a user intending to implement a protocol must spend time “housekeeping” within the simulation framework before testing the protocol.
Ns2’s complexity is further exacerbated by the “openness” of the project. Ns2 has a large community of users with a variety of networking interests and requirements. Some of the existing Ns2 code contains comments alluding to the expeditious workarounds and hacks.
Routing and Topology Control Algorithms
The HCNeT development effort must include a refactoring of existing heuristically driven routing and topology control algorithms. In particular, Garner [9] implemented a purely C++ application for solving the multi-commodity network flow problem allowing user-selected forms of the Pre-flow Push and Edmonds Karp algorithms, both with an alternate version of the Knapsack search algorithm.
In the class design depicted in Figure 7, Garner defined a network model consisting of nodes and edges, but created many interdependencies between the KnapsackOps and EdmundsKarp algorithms and the elements of the network: Commodity, Node and Edge. Additionally, the Network object is contained by each
Figure 7. Class model for Garner’s routing and topology control algorithm. This model is not easily extendable due to high coupling.
algorithm, whereas this research requires a network model that can switch between multiple algorithms without knowing how the algorithms work.
Since Garner’s application does not interface in any way with a simulation engine, it presents an ideal case for refactoring into the HCNeT domain to validate the toolkit design and implementation.
**Fault-Tolerant Routing Algorithm**
HCNeT must also include the fault-tolerant routing algorithm as designed by Lewellyn [6]. Lewellyn researched topology control and routing in clustered networks. His primary interest was developing an efficient way for network clusters to identify network faults locally, then automatically reroute affected communication links within the cluster.
Llewellyn’s implementation is particularly interesting since it utilizes a concept from Hopkinson’s agent-based simulation [5] to interface with ns2. Figure 8 illustrates the architecture of Llewellyn’s implementation. Note how the RoutingTopologyControl class contains the network model, much like Garner’s KnapsackOps and EdmundsKarpOps classes. Again, this design puts emphasis on one particular algorithm which prohibits introduction of new, complementary algorithms.
Note also how the AgentHQAgent class contains the algorithmic class along with a reference to the user-defined model class RTNode. This containment shows how the ns2 agent is highly coupled to the user-defined network model. A developer could leverage the Ns2 implementation of AgentHQAgent to develop a bridge between the network model and the Ns2 simulation environment.
Figure 8. Class model for Llewellyn’s fault-tolerant routing algorithm in ns2. AgentHQAgent provides the single interface to the ns2 simulation. This model is not easily extendable due to high coupling and low cohesion.
Hybrid Communications Network Toolkit (HCNET)
Requirements
To begin requirements analysis, the software developer must be familiar with who the customer is. For HCNeT, the customer is the AFIT Hybrid Communications Research Group (HCRG). In this group, students develop new networking protocols based on extensive research. Much of the research is presented at a theoretical level. This leaves a significant implementation gap that must be crossed before evaluating the theory. In many cases protocol developers must devote the majority of their time understanding and extending the simulation framework in which they will evaluate their protocol.
Not only is it difficult for HCRG members to get their protocol off the ground, it is even more difficult to match and compare protocols between members. As revealed in paragraph 2, the software designs are algorithm-centric and not ready for compatible interfacing with other complementary protocols.
AFIT protocol developers call for a toolkit that will allow them to concentrate on the complexity of their algorithms and not on the complexity of implementation within the ns2 simulation framework.
The toolkit needs to provide all the elements of a basic network definition (nodes and edges), plus the ability to extend and add state to the network as required by a particular protocol. Some users may want an abstract, graph-oriented model for high-level protocol implementation. Other users will need node-level extensions to realize their protocol.
The toolkit also requires a simple interface that users will extend to implement the logic of their protocol. In particular, the user requires a routing module and a topology control module that will each operate on the network model.
Figure 9 highlights the use cases that summarize HCNeT requirements. Use case scenarios are documented in Appendix A.
![Figure 9. HCNeT Use Case Model. Protocol developers need to implement a protocol that will be hot-swappable and compatible to other complimentary protocols. Implementation and testing of the protocol model should be independent of the simulation framework (in this case ns2). Only the installation and evaluation of protocols will necessitate use of the simulation framework.]
**Phased, Iterative Development**
Once the developer understands the use cases for HCNeT, a development plan can emerge. A plan is necessary to meet the needs of the HCRG by a preset deadline. A
phased development plan is selected where completion of each phase represents a milestone for the customer. For HCNeT, a milestone represents the completion, at least in part, of one use case scenario. The product of each milestone will be well-documented, working software. Figure 10 illustrates the project development plan.
Within each phase, development will occur iteratively. In this way, a preliminary design is coded, the code is unit tested then refinements of the design are considered. The design/code/test iterations will occur until all requirements in the use case are met or until the end of the phase is reached. Each phase will last 2-3 weeks. If a milestone is not fully realized, the subsequent phases will be adjusted to incorporate the remaining requirements.
Figure 10. HCNeT Phased, Iterative Development Plan. Phase I is expanded out to demonstrate the activities for each phase. Design, Code and Unit Test activities occur in gradient parallel, where Design is the primary activity earlier and Unit Test is primary activity later. Each phase will last 2-3 weeks.
The advantage of the phased approach is concentration on producing a useful software package, even if it does not realize all the requirements. Additionally, by developing iteratively in each phase, the developer is not constrained to one design, but is able to evolve the design as fine-grained coding reveals challenges and opportunities.
The short development cycles are designed to avoid spending long periods of time coding an end-to-end design only to find the design must be reworked or discarded.
Phase I Design
To begin design on HCNeT, the high-value and high-risk requirements should be scrutinized first. Through use-case analysis, two requirements emerge that will help define the overall design of the system.
The designer is encouraged by the work of Battenfield [2] who developed a modular, hot-swappable routing framework for imbedded mobile systems. In [2] routing protocols were encapsulated into modules, then switched out as needed by the user or the application. HCNeT requirements add significant complexity to this concept since at least two protocols, routing and topology control, must switch out in almost any combination while still working in tandem. The design for HCNeT proceeds independently of Battenfield.
Firstly, of high risk and high value is providing an interface into Ns2 for the toolkit. As stated previously, Ns2 is a complex framework that is not easily abstracted. Conceptually, a protocol developer will build a network model with sufficient state for the operation of their protocol. Then, the developer will implement the protocol algorithm. When the algorithm is called, the network state will presumably change. This change must then be injected into the simulation automatically, without any explicit knowledge of Ns2. To encapsulate and hide the knowledge of Ns2, a general interface must exist to represent the operations expected for any simulation software. From that interface, a specific implementation will interact with Ns2. This line of reasoning points to the use of a bridge. The bridge public interface will emerge with the implementation
of the toolkit, then the Ns2 bridge class will adapt to Ns2 specifically. The bridge concept for HCNeT is illustrated in Figure 11.
Figure 11. HCNeT Architectural Overview. Multiple user-defined protocol strategies operate on the user-defined network model. The user writes a TCL script that populates the model and controls the Ns2 simulation. The simulation passes HCNeT messages via the agent through the bridge. The model returns state to the agent through the bridge.
With a general architecture under consideration, the software developer must put thought into how the model to simulation communication process will take place. If a desired process can be modeled using the selected architecture, then the architecture should be considered a feasible approach by the developer. HCNeT general communication flow is modeled by the sequence diagram in Figure 12 and indicates a feasible architecture.
Figure 12. HCNeT Sequence Overview. A conceptual ordering of events in an HCNeT run-time scenario. Through process modeling, an order of creation emerges. The general order of message calls for event handling is also established.
With one risky design consideration thought through, the toolkit designer must address another potentially risky and high value feature. From the requirements analysis, the designer knows the toolkit must be flexible enough to be extended in different ways to support specific protocols. The decorator software design pattern seems to be able to support dynamically selectable views of an object. Since the decorator realizes a composite structure, each protocol can traverse the model structure and select which view it requires through the visitor pattern.
Finally, the HCNeT designer considers the need for hot-swappable protocol implementations within a family of protocols. For example, PPRP routing could be
switched in favor of CBRP. This requirement exemplifies the intended use of the strategy design pattern.
Phase I Implementation
As previously stated, the implementation phase will most likely face the most significant challenge interfacing the network toolkit with Ns2. Like [15], the ns2 Agent class will serve as the access point to the ns2 framework. The agent should be reached through a bridge class. The agent is a shell Ns2 protocol representing HCNeT as in Figure 8 and Appendix B that will allow interception and manipulation of simulation events during run-time. As per [5], notice the need to create special TCL binding classes in Ns2 to ensure correct interaction within the split framework. Additionally, the coder modified four other Ns2 configuration files to successfully introduce the protocol.
The toolkit designer began implementation of the HCNeT model design decisions as seen in Figure 13. NetworkComponent, BasicNetwork and NetworkExtension comprise the decorator pattern. New decorations, here called network extensions, implement NetworkExtension. With an eye toward integrating Llewellyn’s protocol, the coder implemented the ClusteredExtension class that will hold all the state and methods required by a topographically clustered network. Notice how clustered network state such as cluster heads and gateway nodes may be implemented using the basic elements of the toolkit, such as the HNode class. Because the design calls for a visitor interface, the coder created the NetworkComponentVisitor class and added the accept() method to the NetworkComponent class. Source code for Hcnet is included in Appendix B.
The implementation will evolve as each design decision is considered for coding and the legacy protocol code is integrated. Work must be completed to implement the
bridge class and layer in references to the simulation bridge within the
NetworkComponent public interface. Ideally, the observer pattern will be used to
decouple the Ns2 based bridge from the toolkit.
Figure 13. Class model for HCNeT network toolkit. This model is extensible and
configurable, relying mainly on the Decorator pattern and the Strategy pattern.
IV. Results
Architecture
Network Model
The network model contains a strategy interface for routing and a strategy interface for topology control as planned. Metadata and method calls required for new protocols will be placed in user-defined strategy implementations. The key feature of the strategies is they may be switched out independently and dynamically to accommodate research requirements.
The network topology model was implemented per the original design decision and is depicted in Figure 14. The decorator pattern implementation allows for user-defined network structures to be dynamically applied and removed as required by any particular routing or topology control protocol. This implementation ensures correct interoperability of various protocols throughout the execution time of the simulation.
Figure 14. HCNet Toolkit Network Model. The decorator pattern (wrapper) is applied to the network container class, meaning HcnetNetwork may be wrapped by FlowNetwork and/or ClusteredNetwork at any time during execution.
Builder
The builder consolidates the construction of the network model. For implementation of Llewellyn’s protocol, the builder depicted in Figure 15 currently reads a formatted TCL script much like an XML file. This was done for convenience since much of the work to populate the network model was already implemented in various portions of the legacy code.
Figure 15. HcnetBuilder Class.
**Bridge**
The bridge depicted in **Figure 16** evolved to be a two-way bridge since the toolkit side contains a reference to the toolkit and the Ns2 side contains a reference to the agent hq. Therefore, the bridge is actually more of a logical mediator.
The bridge always has the same interface to the toolkit model and is to be treated as a proxy for the simulation engine when viewed by the toolkit model. As a singleton, the Bridge is observed globally and allows for protocol updates to the simulator on demand. For ns2 the updates are performed through the Tcl instance by sending commands.
On the simulator side, the bridge contains a set of observers that are updated with each clock cycle, so each clock cycle the toolkit has an opportunity to change the state of the network. Most notably in this implementation, the network nodes are registered observers and thus are updated each simulation second.
The Bridge may be implemented for any simulation engine such as ns2 or OPNeT. The simulator bridge was implemented as an abstract singleton as designed, therefore the bridge contains a registry of specific implementations. The specific implementation is selected through a system environment variable at load time.
For the ns2 implementation, the EPOCHS AgentHQ was used as a starting point. Ultimately the AgentHQAgent class was refactored to communicate with the bridge. Additionally, AgentHQAgent served as a proxy to the network model for the SrcDestFidHashClassifier Class. SrcDestFidHashClassifier serves as a representative for each toolkit node within Ns2. Only these two Ns2 classes have any knowledge of the toolkit within the simulator. Through access to a TCL instance, the AgentHQAgent and SrcDestFidHashClassifier are able to transmit commands required by the toolkit to the Ns2 environment.

Figure 16. HCNeT Bridge Interfaces HCNeT Network Model with Ns2 Agent. Use of Abstract Singleton pattern ensures network model is unaware of which simulation application is being used.
**Routing and Topology Control Implementation**
To demonstrate utility of HCNeT, the developer embarked on a project to refactor the routing topology control protocol implemented by Llewellyn [15]. Convincing progress illustrates that only four toolkit classes need to be extended to exhibit the
protocol. The node, edge, and commodity classes required extension to hold the state required by Llewellyn’s algorithm. Of course, the TopologyStrategy class required extension to contain the logic of the protocol. Figure 17 depicts the four new classes.
Figure 17. Class Definitions for New Protocol Developed in HCNeT. Llewellyn’s routing and topology control algorithm is implemented in HCNeT by extending four toolkit classes.
Maintainability
One of the important goals of software development is to produce software that is not resistant to change.[3] Object Oriented (OO) design principles enforce the encapsulation and cohesiveness of software modules. By applying these principles in a disciplined manner, such as emulating software design patterns, understandability and changeability of the software increases. HCNeT was designed using well known OO design patterns[8] and implemented using object features of the C++ programming language. Code analysis reveals key OO indicators and complexity factors support the claim of HCNeT maintainability.
A description of some measures of maintainability follows and Table 1 summarizes these measures as indicators of maintenance qualities. Lastly, an analysis of HCNeT as compared to a previous network protocol project in ns2 using these measurements.
Coupling
Coupling describes the direct dependency between software objects. When one object contains a reference to another object, this is an instance of coupling. High coupling refers to objects that exhibit this containment property in excess. Excessive coupling can be an indication of poor encapsulation; the result of which are objects that depend highly on other objects and thus, increasing the effect of change on one object to others. High coupling leads to poor maintainability.
**Number of Children**
Number of children refers to size of the first level of the inheritance tree of some super class. A large number of children for a given super class can indicate the loss of specialization or inappropriate abstraction in the design[14]. However, in some cases, such as application of the observer pattern[8], a large number of children may not indicate a maintainability problem.
**Depth of Inheritance Tree**
The depth of a class’ inheritance tree is a consideration for maintainability. On one hand, a particularly long path of inheritance could lead to understandability difficulty as a software specialist attempts to comprehend the gap between the top and the bottom of the tree. On the other hand, a long path of inheritance exhibits great potential for reuse of ancestor classes. The key for this metric is to analyse the intent of large inheritance trees to determine if the appropriate balance of understandability and reuse has been made.[14]
**Composite Information Flow**
Composite information flow is a function of the fan-in and fan-out of a software module. Fan-in refers to the number of other modules which change the state or invoke operations on a particular module. Fan-out refers to the number of modules that read the reference modules state combined with the number of modules the reference module operates on. [14]
A module with a high composite information flow implies the need to recompile client modules if supplier modules are changed.[14]
**Cyclomatic Complexity**
McCabe’s cyclomatic number can be viewed as a direct measure of the number of independent paths through the procedural logic of a subprogram, but it is more commonly viewed as an indirect measure of maintainability, and particularly of testability. The McCabe cyclomatic number also has a particularly direct relationship to the testability of a component. [14]
**Table 1. Relationships between Metrics and Quality Model Attributes.[14]**
<table>
<thead>
<tr>
<th></th>
<th>self-containedn</th>
<th>self-descriptiveness</th>
<th>structuredness</th>
<th>conciseness</th>
<th>legibility</th>
<th>augmentability</th>
<th>abstractness</th>
<th>reusability</th>
<th>buildability</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td>CBO</td>
<td>X</td>
<td>X</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Coupling Between Objects</td>
</tr>
<tr>
<td>NOC</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>X</td>
<td>Number of Children</td>
</tr>
<tr>
<td>DIT</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>X</td>
<td>Depth of Inheritance Tree</td>
</tr>
<tr>
<td>IF4</td>
<td>X</td>
<td></td>
<td>X</td>
<td>X</td>
<td>X</td>
<td></td>
<td></td>
<td></td>
<td>X</td>
<td>Composite Information Flow</td>
</tr>
<tr>
<td>MVG</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>X</td>
<td>X</td>
<td>X</td>
<td>McCabe’s Cyclomatic Complexity</td>
</tr>
</tbody>
</table>
**Maintainability of HCNeT**
When Littlefair’s metrics and 3-tier evaluation [14] are applied to HCNeT as seen in Table 2, all but the coupling metric reveal a maintainable profile. The coupling metric is found suspicious in two classes, Network and Node. However, on inspection, in the network object model, the network container and the node are central elements and
coupling was designed for ease of access to these core classes. Even though there are only two classes with suspicious coupling, one may consider refactoring in this case.
AgentHQ, the ns2 interface structure utilized in [10] and [15] are provided in Table 2 for comparison.
<table>
<thead>
<tr>
<th>Key</th>
<th>AgentHQ</th>
<th>HCNeT</th>
</tr>
</thead>
<tbody>
<tr>
<td>Maintainable</td>
<td>All < 11</td>
<td>Network 16, Node 17, Others < 7</td>
</tr>
<tr>
<td>Suspicious</td>
<td>All < 2</td>
<td>All < 2</td>
</tr>
<tr>
<td>Design Flaw</td>
<td>All < 4</td>
<td>All < 3</td>
</tr>
<tr>
<td>Coupling Between Objects (CBO)</td>
<td>All < 64</td>
<td>All < 9</td>
</tr>
<tr>
<td>Number of Children (NOC)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Depth of Inheritance Tree (DIT)</td>
<td>All < 4</td>
<td>All < 3</td>
</tr>
<tr>
<td>Composite Information Flow (IF4)</td>
<td>All < 64</td>
<td>All < 9</td>
</tr>
<tr>
<td>McCabe’s Cyclomatic Complexity (MVG)</td>
<td>637</td>
<td>75</td>
</tr>
</tbody>
</table>
V. Conclusion
HCNeT provides an extensible toolkit for quickly implementing and testing a combination of network protocols at a more theoretical level. Once implemented, the toolkit will be able to demonstrate the combined performance of two topology control and routing algorithms in a clustered network. Immediately thereafter, the HCRG can utilize the toolkit to rapidly prototype other network protocols.
Contributions
1. Requirements analysis led to an overall architectural design approach for a general purpose network simulation toolkit for use in network protocol development research.
2. Laid the groundwork for a simulation toolkit providing course-grained rapid prototyping along side with fine grained protocol implementation.
3. Implemented a bridging construct to abstract away specific network simulation application to allow for “plug and play” testing of new protocols.
4. Agile implementation process fleshed out a robust OO design and provided a maintainable code base available for future toolkit developers. OO-driven self-documenting code provides intuitive code refactoring.
Future Work
A completed refactoring of Llewellyn’s and Garner’s protocol is necessary to demonstrate and analyze the performance of the various algorithms working in concert.
New work must be completed to build bridge plugins that will allow HCNeT to be adapted to a variety of network simulation frameworks, in particular OPNET.
The toolkit developer will proceed with Phases II-IV of the project, making HCNeT more user-friendly. A unit testing suite must be developed to provide assurance to protocol developers of correct toolkit implementation. Ultimately, a GUI like the one for SynTraff [1] should be provided to allow for easy install, build and execution of user-selected routing and topology control protocols, and simulation engines.
Appendix A: HCNeT Use Cases
Global Requirements:
System
HCNeT requires the use of ns2. See ns2 for more details on platform requirements and installation.
Experience/Knowledge
User:
A user of HCNeT is familiar with the ns2 framework in general and, in particular, TCL programming language which is used as a front-end to build network architectures and simulation parameters.
Developer:
A developer of HCNeT has the same characteristics of a user and additionally is experienced in OO programming with C++.
Use Case: H_UC01 Implement a New Network Protocol
CHARACTERISTIC INFORMATION
Goal in Context: A protocol developer codes the protocol using HCNeT
Scope: C++ development environment
Level: Primary
Preconditions: C++ compiler is installed, HCNeT header and source files are installed within the programming scope.
Success End Condition: Protocol developer instantiated classes or user-extended classes from within HCNeT to fully express the protocol logic.
Failed End Condition: Protocol developer could not fully express the protocol logic by instantiating or simply extending HCNeT
Primary Actor: Protocol developer
Trigger: Protocol developer completes conceptual design and is ready to implement
MAIN SUCCESS SCENARIO
1. User selects an HCNeT generic protocol class or interface and programs his/her particular protocol logic in compliance with the generic interface.
2. User successfully compiles their new protocol source code
EXTENSIONS
1a. An appropriate generic protocol does not exist in HCNeT
1a.1. User creates an appropriate generic protocol
1a.2. User creates an appropriate extension to the network model to support the generic protocol
2a. Source code will not compile
2a.1. Go to use case Test HCNeT
---------------------
SUB-VARIATIONS
----------------------
1. Default generic protocols are Routing, TopologyControl and Buffering
-------------
RELATED INFORMATION
Priority: 1
Performance Target: <the amount of time this use case should take>
Frequency: Frequent
Superordinate Use Case: <optional, name of use case that includes this one>
Subordinate Use Cases: Test HCNeT
-------------
OPEN ISSUES
-------------
SCHEDULE
Due Date: TBD
Use Case: H_UC02 Test HCNeT
CHARACTERISTIC INFORMATION
Goal in Context: A protocol developer tests their implementation
Scope: unit testing
Level: Subfunction
Preconditions: Use Case Implement a Network Protocol
Success End Condition: Protocol developer knows their protocol implementation is compatible with the HCNeT model or knows why it is not compatible
Failed End Condition: Protocol developer does not know if their protocol is not compatible with the HCNeT model
Primary Actor: Protocol Developer
Trigger: Protocol developer wishes to unit test HCNeT
MAIN SUCCESS SCENARIO
1. User selects to unit test HCNeT
2. HCNeT informs user that all unit tests passed successfully
EXTENSIONS
2a. HCNeT informs user that one or more of the unit tests have failed and why
2a.1. Go to use case Implement a New Network Protocol.
SUB-VARIATIONS
(No known sub-variations)
----------------------
RELATED INFORMATION (optional)
Priority: 2
Performance Target:
Frequency: Frequent
Superordinate Use Case: Implement a New Network Protocol
Subordinate Use Cases: none
----------------------
OPEN ISSUES
----------------------
SCHEDULE
Due Date: TBD
Use Case: H_UC03 Install HCNeT
CHARACTERISTIC INFORMATION
Goal in Context: User installs HCNeT and/or new user protocols into the ns2 framework
Scope: Compiler
Level: Primary Task
Preconditions: Test HCNeT main success scenario
Success End Condition: HCNeT and ns2 compile together
Failed End Condition: compiler errors
Primary Actor: Protocol developer
Trigger: Protocol developer ready to run simulation
MAIN SUCCESS SCENARIO
1. User runs “make all” in the ns2 top directory
2. Compiler informs user of successful install
EXTENSIONS
2a. Compiler informs user of error(s)
2a1. User writes new unit test
2a2. Use Case Test HCNeT
2a3. If all else fails, get help from AFIT staff
SUB-VARIATIONS
(no known sub-variations)
----------------------
RELATED INFORMATION
Priority: 1
Frequency: Frequent
Superordinate Use Case: none
Subordinate Use Cases: none
----------------------
OPEN ISSUES
----------------------
SCHEDULE
Due Date: TBD
Use Case: H_UC04 Evaluate Protocol(s)
CHARACTERISTIC INFORMATION
Goal in Context: In the course of defining a network simulation, a user declares a topology control protocol to override the default or previously declared protocol.
Scope: TCL scripting
Level: Primary
Preconditions: HCNeT is installed, a text editor is open and a shell tcl script is written.
Success End Condition: ns2 will simulate network operation based on the user defined protocol. Successful completion will result in a success message in the simulation trace file and a graphical indication in the nam viewer.
Failed End Condition: The previously declared protocol will continue. Failed completion will result in a failure message in the simulation trace file and a graphical indication in the nam viewer.
Primary Actor: user
Trigger: user decides when to declare the protocol
MAIN SUCCESS SCENARIO
Step 1: User types the HCNeT protocol declaration into the tcl script
Step 2: User saves the script and executes the script with ns2
Step 3: User executes the nam file with nam
Step 4: User observes effects of the protocol, with a visual indication of when the protocol is active.
EXTENSIONS
Step 4: Protocol fails: User observe exception message and begins troubleshooting
-------------------
SUB-VARIATIONS
Step 1: user may select a specific topology control or routing protocol
Step 3a: nam is not used, user examines trace file
Step 3b: this step may be programmed into the TCL script
-------------------
RELATED INFORMATION (optional)
Priority: 1
Performance Target: <the amount of time this use case should take>
Frequency: Most Frequent
Channel to primary actor: installed HCNeT used through text editor of choice
-------------------
OPEN ISSUES
Is this use case sufficient for the vision of HCNeT?
-------------------
SCHEDULE
Due Date: TBD
Bibliography
A Hybrid Communications Network Simulation-Independent Toolkit
Dines, David, M., Major, USAF
Air Force Institute of Technology
Graduate School of Engineering and Management (AFIT/EN)
2950 Hobson Way, Building 640
WPAFB OH 45433-8865
AFIT/GCS/ENG/08-08
Net-centric warfare requires information superiority to enable decision superiority, culminating in insurmountable combat power against our enemies on the battlefield. Information superiority must be attained and retained for success in today’s joint/coalition battlespace. To accomplish this goal, our combat networks must reliably, expediently and completely deliver over a wide range of mobile and fixed assets. Furthermore, each asset must be given special consideration for the sensitivity, priority and volume of information required by the mission. Evolving a grand design of the enabling network will require a flexible evaluation platform to try and select the right combination of network strategies and protocols in the realms of topology control and routing. This research will result in a toolkit for ns2 that will enable rapid interfacing and evaluation of new networking algorithms and/or protocols. The toolkit will be the springboard for development of an optimal, multi-dimensional and flexible network for linking combat entities in the battlespace.
|
{"Source-Url": "https://scholar.afit.edu/cgi/viewcontent.cgi?article=3750&context=etd", "len_cl100k_base": 12015, "olmocr-version": "0.1.53", "pdf-total-pages": 67, "total-fallback-pages": 0, "total-input-tokens": 101910, "total-output-tokens": 15124, "length": "2e13", "weborganizer": {"__label__adult": 0.00040340423583984375, "__label__art_design": 0.0003821849822998047, "__label__crime_law": 0.00031447410583496094, "__label__education_jobs": 0.002254486083984375, "__label__entertainment": 0.00011372566223144533, "__label__fashion_beauty": 0.0002092123031616211, "__label__finance_business": 0.0003786087036132813, "__label__food_dining": 0.00036406517028808594, "__label__games": 0.0012025833129882812, "__label__hardware": 0.002788543701171875, "__label__health": 0.0004467964172363281, "__label__history": 0.0004973411560058594, "__label__home_hobbies": 0.00011092424392700197, "__label__industrial": 0.0006890296936035156, "__label__literature": 0.00030541419982910156, "__label__politics": 0.0003509521484375, "__label__religion": 0.0004260540008544922, "__label__science_tech": 0.08905029296875, "__label__social_life": 0.00011146068572998048, "__label__software": 0.00885009765625, "__label__software_dev": 0.88916015625, "__label__sports_fitness": 0.0004227161407470703, "__label__transportation": 0.00102996826171875, "__label__travel": 0.00023293495178222656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65601, 0.01359]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65601, 0.47186]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65601, 0.86713]], "google_gemma-3-12b-it_contains_pii": [[0, 642, false], [642, 936, null], [936, 1125, null], [1125, 1597, null], [1597, 1940, null], [1940, 3019, null], [3019, 3313, null], [3313, 6176, null], [6176, 6176, null], [6176, 7581, null], [7581, 7802, null], [7802, 9402, null], [9402, 9980, null], [9980, 11387, null], [11387, 12142, null], [12142, 13109, null], [13109, 13830, null], [13830, 14710, null], [14710, 15443, null], [15443, 17268, null], [17268, 18097, null], [18097, 19601, null], [19601, 21343, null], [21343, 22987, null], [22987, 24595, null], [24595, 26057, null], [26057, 27551, null], [27551, 27688, null], [27688, 29179, null], [29179, 29864, null], [29864, 31333, null], [31333, 31610, null], [31610, 33042, null], [33042, 33262, null], [33262, 34770, null], [34770, 35701, null], [35701, 37133, null], [37133, 38897, null], [38897, 39803, null], [39803, 40749, null], [40749, 42556, null], [42556, 42918, null], [42918, 43734, null], [43734, 44315, null], [44315, 45577, null], [45577, 46671, null], [46671, 46926, null], [46926, 47102, null], [47102, 48471, null], [48471, 49969, null], [49969, 52101, null], [52101, 53634, null], [53634, 55072, null], [55072, 55487, null], [55487, 56002, null], [56002, 57070, null], [57070, 57678, null], [57678, 58531, null], [58531, 58841, null], [58841, 59552, null], [59552, 59802, null], [59802, 60970, null], [60970, 61656, null], [61656, 63466, null], [63466, 64276, null], [64276, 65601, null], [65601, 65601, null]], "google_gemma-3-12b-it_is_public_document": [[0, 642, true], [642, 936, null], [936, 1125, null], [1125, 1597, null], [1597, 1940, null], [1940, 3019, null], [3019, 3313, null], [3313, 6176, null], [6176, 6176, null], [6176, 7581, null], [7581, 7802, null], [7802, 9402, null], [9402, 9980, null], [9980, 11387, null], [11387, 12142, null], [12142, 13109, null], [13109, 13830, null], [13830, 14710, null], [14710, 15443, null], [15443, 17268, null], [17268, 18097, null], [18097, 19601, null], [19601, 21343, null], [21343, 22987, null], [22987, 24595, null], [24595, 26057, null], [26057, 27551, null], [27551, 27688, null], [27688, 29179, null], [29179, 29864, null], [29864, 31333, null], [31333, 31610, null], [31610, 33042, null], [33042, 33262, null], [33262, 34770, null], [34770, 35701, null], [35701, 37133, null], [37133, 38897, null], [38897, 39803, null], [39803, 40749, null], [40749, 42556, null], [42556, 42918, null], [42918, 43734, null], [43734, 44315, null], [44315, 45577, null], [45577, 46671, null], [46671, 46926, null], [46926, 47102, null], [47102, 48471, null], [48471, 49969, null], [49969, 52101, null], [52101, 53634, null], [53634, 55072, null], [55072, 55487, null], [55487, 56002, null], [56002, 57070, null], [57070, 57678, null], [57678, 58531, null], [58531, 58841, null], [58841, 59552, null], [59552, 59802, null], [59802, 60970, null], [60970, 61656, null], [61656, 63466, null], [63466, 64276, null], [64276, 65601, null], [65601, 65601, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65601, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65601, null]], "pdf_page_numbers": [[0, 642, 1], [642, 936, 2], [936, 1125, 3], [1125, 1597, 4], [1597, 1940, 5], [1940, 3019, 6], [3019, 3313, 7], [3313, 6176, 8], [6176, 6176, 9], [6176, 7581, 10], [7581, 7802, 11], [7802, 9402, 12], [9402, 9980, 13], [9980, 11387, 14], [11387, 12142, 15], [12142, 13109, 16], [13109, 13830, 17], [13830, 14710, 18], [14710, 15443, 19], [15443, 17268, 20], [17268, 18097, 21], [18097, 19601, 22], [19601, 21343, 23], [21343, 22987, 24], [22987, 24595, 25], [24595, 26057, 26], [26057, 27551, 27], [27551, 27688, 28], [27688, 29179, 29], [29179, 29864, 30], [29864, 31333, 31], [31333, 31610, 32], [31610, 33042, 33], [33042, 33262, 34], [33262, 34770, 35], [34770, 35701, 36], [35701, 37133, 37], [37133, 38897, 38], [38897, 39803, 39], [39803, 40749, 40], [40749, 42556, 41], [42556, 42918, 42], [42918, 43734, 43], [43734, 44315, 44], [44315, 45577, 45], [45577, 46671, 46], [46671, 46926, 47], [46926, 47102, 48], [47102, 48471, 49], [48471, 49969, 50], [49969, 52101, 51], [52101, 53634, 52], [53634, 55072, 53], [55072, 55487, 54], [55487, 56002, 55], [56002, 57070, 56], [57070, 57678, 57], [57678, 58531, 58], [58531, 58841, 59], [58841, 59552, 60], [59552, 59802, 61], [59802, 60970, 62], [60970, 61656, 63], [61656, 63466, 64], [63466, 64276, 65], [64276, 65601, 66], [65601, 65601, 67]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65601, 0.0364]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
03ac8a4fd0b5b4e32d458a7edd00325526be0a50
|
Evaluation of formal IDEs for human-machine interface design and analysis: the case of CIRCUS and PVSio-web
Camille Fayollas¹ Célia Martinie¹ Philippe Palanque¹ Paolo Masci² Michael D. Harrison²,³ José C. Campos² Saulo Rodrigues e Silva²
¹ICS-IRIT, University of Toulouse, Toulouse, France {fayollas,martinie,palanque}@irit.fr
²HASLab/INESC TEC and Universidade do Minho, Braga, Portugal {paolo.masci,jose.c.campos,saulo.r.silva}@inesctec.pt
³Newcastle University, Newcastle upon Tyne, United Kingdom michael.harrison@newcastle.ac.uk
Critical human-machine interfaces are present in many systems including avionics systems and medical devices. Use error is a concern in these systems both in terms of hardware panels and input devices, and the software that drives the interfaces. Guaranteeing safe usability, in terms of buttons, knobs and displays is now a key element in the overall safety of the system. New integrated development environments (IDEs) based on formal methods technologies have been developed by the research community to support the design and analysis of high-confidence human-machine interfaces. To date, little work has focused on the comparison of these particular types of formal IDEs. This paper compares and evaluates two state-of-the-art toolkits: CIRCUS, a model-based development and analysis tool based on Petri net extensions, and PVSio-web, a prototyping toolkit based on the PVS theorem proving system.
1 Introduction
Use error is a major concern in critical interactive systems. Consider, for example, a pilot calibrating flight instruments before take-off. When calibrating the barometer used to measure the aircraft’s altitude, a consistency check should be performed automatically by the cockpit software to help guard against use errors, such as mistyping a value or selecting the wrong units.
New IDEs based on formal methods have been developed by the research community to support the design and analysis of high-confidence human-machine interfaces. Each IDE supports different types of analysis, ranging from functional correctness (e.g., absence of deadlocks and coding errors such as division by zero) to compliance with usability and safety requirements (e.g., assessing the response to user tasks, or the visibility of critical device modes). Choosing the right tool is important to ensure efficiency of the analysis and that the analysis addresses the appropriate safety concerns relating to use. To date, little work has been done to compare and evaluate different formal IDEs for human-machine interface design and analysis, and little or no guidance is available for developers to understand which IDE can be used most effectively for which kind of analysis. This paper describes a first step towards addressing this gap.
Contribution. We compare and evaluate two state-of-the-art formal verification technologies for the analysis of human-machine interfaces: CIRCUS [9], a model-based development and analysis tool that uses Petri net extensions; and PVSio-web [19], a prototyping toolkit based on the PVS theorem prover.
The aim of this work is to provide guidance to developers to understand which tool can be used most effectively for which kind of analysis of interactive systems. Both tools have their foundations in existing formal technologies, but are focused towards particular issues relating to the user interface. The capabilities of the two tools are demonstrated in the paper through a common case study based on a critical subsystem in the cockpit of a large civil aircraft. A taxonomy is developed as a result of the comparison that can be used to describe the characteristics of other similar tools.
Organisation. The remainder of the paper is organised as follows. Section 2 illustrates typical features of formal IDEs for the design and analysis of human-machine interfaces, and presents a detailed description of CIRCUS and PVSio-web. Section 3 introduces the common example for comparison of the selected tools, as well as the developed models. Section 4 presents the metrics for comparing the IDEs, and then uses the metrics as a basis for the comparison. Section 5 concludes the paper and presents future directions in which the tools may evolve.
2 The formal modelling and analysis of user interfaces
Formal tools for the modelling and analysis of human-machine interfaces are designed to support multidisciplinary teams of designers from different engineering disciplines, including human factors engineering (to establish usability requirements, run user studies and interpret compliance), formal methods (to verify compliance of a system design with design requirements), and software engineering (to develop prototypes and software code, e.g., using model-based development methods). Although several tools provide graphical model editors and automated functions for modelling and analysis of interactive elements of a system, different tools are usually complementary, as they support different levels of description, and different types of analysis, ranging from micro-level aspects of human-machine interaction, e.g., aspect and behaviour of user interface widgets, to the analysis of the wider socio-technical system within which the interactive system is used.
In the present work, we compare two state-of-the-art formal tools developed by two different research teams: CIRCUS [9], a toolkit for model-based development of interactive systems; and PVSio-web [19], a toolkit for model-based development of user interface software. Both build on tools that have been developed more generally for model based design and software engineering, extending them with features that are particularly useful when considering the human-machine interface or the wider socio-technical system.
Other formal tools that could be used (and in some cases have been used) for the analysis of human-machine interfaces exist. They offer functionalities that complement those of CIRCUS and PVSio-web. The evaluation of these other tools is not within the scope of this paper, although a brief overview can be found in Section 2.3.
2.1 CIRCUS
CIRCUS, which stands for Computer-aided-design of Interactive, Resilient, Critical and Usable Systems, is an IDE for the formal verification of the system’s behaviour as well as the analysis of compatibility between the user’s task and the system’s behaviour. CIRCUS includes three tools:
- **HAMSTERS** (Human-centred Assessment and Modelling to Support Task Engineering for Resilient Systems) is a tool for editing and simulating task models. The tool can be used to ensure consistency, coherence, and conformity between assumed or prescribed user tasks and the sequence of actions necessary to operate interactive systems [3]. The notation used in the tool makes it possible to structure
users’ goals and sub-goals into hierarchical task trees. Qualitative temporal relationships among tasks are described by operators. Various notational elements support modelling of specialised task types, explicit representations of data and knowledge, device descriptions, genotypes and phenotypes of errors, and collaborative tasks.
- **PetShop** (Petri Net workshop) is a tool for creating, editing, simulating and analysing system models using the ICO (Interactive Cooperative Objects) notation [23, 17]. The ICO notation allows developers to specify the behaviour of interactive systems. The notation uses Petri Nets for describing dynamic behaviours, and uses object-oriented concepts (including dynamic instantiation, classification, encapsulation, inheritance and client/server relationships) to describe structural or static aspects of the system.
- **SWAN** (Synergistic Workshop for Articulating Notations) is a tool for the co-execution of PetShop models and HAMSTERS models [3]. The tool allows developers to establish correspondences between system behaviours and tasks, and perform automated system testing by means of co-execution [5].
2.2 **PVSio-web**
PVSio-web is a toolkit for model-based development of user interface software. The toolkit is based on and extends an established theorem prover, PVS [24], providing a graphical environment for constructing, visualising and analysing formal models of user interface software. PVSio-web has three main components:
- **Prototype Builder and Simulator**. This tool allows developers to create device prototypes based on formal models, and run them within a Web browser. The visual aspect of the prototype uses an interactive picture of the device. Developers create programmable areas over the picture to identify input widgets (e.g., buttons) and output widgets (e.g., displays, LEDs). The tool automatically translates user actions over input widgets (e.g., button presses) into PVS expressions that can be evaluated within PVSio [22], the native PVS component for animating executable PVS models. The Simulator tool executes PVSio in the background, and the effects of the execution are automatically rendered using the output widgets of the prototype to closely resemble the visual appearance of the real system in the corresponding states.
- **Emucharts Editor**. This tool facilitates the creation of formal models using visual diagrams known as Emucharts. These diagrams are based on Statecharts [14]. The tool allows developers to define the following design elements: states, representing the different modes of the system; state variables, representing the characteristics of the system state; and transitions, representing events that change the system state. The tool incorporates a model generator that translates the Emucharts diagram into executable PVS models automatically. The model generator also supports the generation of other different formal modelling languages for interactive systems, including VDM [18], MAL [6], and PIM [4], as well as executable code (MISRA-C).
- **The PVS back-end**. This includes the PVS theorem prover and the PVSio environment for model animation. The back-end is used for formal analysis of usability-related properties of the human-machine interface model, such as consistency of response to user actions and reversibility of user actions.
2.3 Other tools
MathWorks Simulink [20] is a commercial tool for model-based design and analysis of dynamic systems. It provides a graphical model editor based on Statecharts, and functions for rapid generation of realistic prototypes. SCR [13] is a toolset for formal analysis of system requirements and specifications. Using SCR, it is possible to specify the behaviour of a system formally, use visual front-ends to demonstrate the system behaviour based on the specifications, and use a set of formal methods tools for the analysis of system properties. SCADE and IBM’s Rational Statemate are two commercial tool sets for model-based development of interactive systems. The tool sets provide, among other features, rapid prototyping, co-simulation, and automated testing. Formal verification is supported by these tools, but is limited to the analysis of coding errors such as division-by-zero. Use-related requirements and tasks can be analysed only using simulation and testing. IVY [7] is a workbench for formal modelling and verification of interactive systems. The tool provides developers with standard property templates that capture usability concerns in human-machine interfaces. The core of the IVY verification engine is the NuSMV model checker. A graphical environment isolates developers from the details of the underlying verification tool, thereby lowering the knowledge barriers for using the tool. The particular tools that are of interest in the design and analysis of interactive systems enable the analysis of user activities, with a focus on what users do in terms of what they perceive about the systems and the actions they perform. Furthermore an important requirement for such tools is that the means of analysis and their results should be accessible to team members without a background in formal techniques, or even software development techniques.
3 Case study and IDE showcase
The case study for comparing the selected tools is based on a subsystem of the Flight Control Unit (FCU) of the Airbus A380. It is an interactive hardware panel with several different buttons, knobs, and displays. The FCU has two main components: the Electronic Flight Information System Control Panel (EFIS CP), for configuring the piloting and navigation displays; and the Auto Flight System Control Panel (AFS CP), for setting the autopilot state and parameters.
In future cockpits, the interactive hardware elements of the FCU panel might be replaced by an interactive graphical application rendered on displays. This graphical software (hereafter, referred to as FCU Software) will provide the same functionalities as the corresponding hardware elements. This graphical software will be displayed on one of the screens in the cockpit. Pilots will interact with the FCU Software via the Keyboard and Cursor Control Unit (KCCU) that integrates keyboard and track-ball (see Figure 1).
The present paper illustrates how CIRCUS and PVSio-web can be used to create models and prototypes of the FCU Software. Developers can explore design options and analyse requirements for these future generation FCUs using these formal IDEs for model-based development of human-machine interfaces. To keep the example simple, we focus further and analyse the EFIS CP. This component includes most of the fundamental interactive elements of the FCU.
3.1 Description of the system and its use
A close up view of the EFIS CP is shown in the rightmost picture of Figure 1. The left panel of the EFIS CP window is dedicated to the configuration of the barometer settings (upper part) and of the Primary Flight Display (lower part). The right panel is dedicated to the configuration of the Navigation Display. The top part provides buttons for displaying navigation information on the cockpit displays.
The ComboBoxes at the bottom allow the pilot to choose display modes and scale.
In this work, we focus more particularly on the configuration of the barometric settings (upper part of the left panel). This panel is composed of several widgets: two CheckButtons enable pilots to select either Standard (STD) or Regional Pressure Settings (QNH) mode. When in QNH mode, a number entry widget (EditBoxNumeric) enables pilots to set the barometric reference. Finally, a button (PushButton) enables pilots to switch the barometer units between inches of mercury (inHg) and hectopascal (hPa). When switching from one unit to the other, a unit conversion is triggered, and the barometer settings value on the display is updated accordingly. When the barometer unit is inHg, the valid range of values is [22, 32.48]. When the unit is hPa, the valid range is [745, 1100]. If the entered value exceeds the valid value range limits, the software automatically adjusts the value to the minimum (when over-shooting the minimum valid value) or the maximum (when overshooting the maximum valid value).
When starting the descent (before landing), pilots may be asked to configure the barometric pressure to the one reported by the airport. The barometric pressure is used by the altimeter as an atmospheric pressure reference in order to process correctly the plane altitude. To change the barometric pressure, pilots select QNH mode, then select the pressure unit (which depends on the airport), and then edit the pressure value in the EditBoxNumeric.
### 3.2 Modelling and analysis using CIRCUS
A prototype user interface was developed in CIRCUS that captures the functionalities of the FCU Software. The workflow for the modelling and analysis of this interactive system includes six main steps that are briefly detailed below.
**Step 1: Task analysis and modelling.** This step describes user activities. It identifies goals, tasks, and activities that are intended to be performed by the operator. For example, the task “Perform descent preparation”, is decomposed into several HAMSTERS models represented as subroutines, components and instances of components \[10\]. Due to space constraints, we only describe an extract of the model in Figure[2]
A simplified version of the task model is described as the abstract task “Perform descent preparation” in the first row of Figure 2. The second row refines this task into several abstract sub-tasks (e.g., “Obtain weather and landing information”). Each one of these abstract tasks corresponds to a step of the operational procedure that is intended to be performed by the flight crew when preparing the descent phase [1].
In the present paper, we focus on the “Set barometric reference” abstract task, refined in the third row. The task is decomposed as follows: the pilot receives the new barometric target (“Receive barometric target” abstract task) and remembers the corresponding information (“Barometric pressure target”). The pilot then needs to gather information about the current barometer settings (“Gather information about current barometric settings”), thus remembering a new piece of information (“Current barometric pressure”). The pilot then needs to compare the two values that have been received in the previous two steps (“Interpret and analyse barometric pressure” cognitive analysis task) creating the “Current pressure == Targeted pressure” information. If the targeted pressure is different from its current value the pilot decides to change the pressure (“Decide to change barometric pressure” cognitive decision task) and change it (“Change barometric pressure” abstract task).
The fourth row of Figure 2 refines the “Change barometric pressure” abstract task as follows: the pilot must first check the pressure mode (“Check pressure mode” abstract task), switch to QNH mode if the current mode is STD (“Change pressure mode to QNH” abstract task), check the unit and change it if needed (“Check barometric pressure unit” and “Change pressure unit” abstract tasks) and finally set the new pressure value (“Set target pressure value” abstract task).
Finally, the fifth row refines the “Change pressure mode to QNH” abstract task. This task is performed by the pilot if the current mode is STD. In this task, the pilot first reaches the QNH checkButton (“Reach QNH CheckButton” abstract task). Then s/he clicks on it (“Click on QNH CheckButton” interactive input task). The system then changes the mode and displays the new state (“Change mode” system task and “Display QNH mode” interactive output task). The pilot can then check that the new pressure...
Figure 3: ICO model of the barometer settings behaviour.
mode is the good one ("Check pressure mode" abstract task and "Decide that barometric pressure mode is OK" cognitive decision task). It is important to note that this task model is detailed both in terms of user task refinement (e.g., cognitive task analysis) to allow the analysis of workload and performance (see Step 3 below); and in terms of interactive task refinement (see, for instance, the refinement of the "Change pressure mode to QNH" abstract task which includes the "Click on QNH Checkbutton" interactive input task) to allow the compatibility assessment between the task model and the behavioural model of the system (see Step 6 below).
Step 2: Workload and performance analysis. As presented in Figure 2, the HAMSTERS notation and tool enable human task refinement. It makes it possible to differentiate between cognitive, motor, and perception tasks as well as representing the knowledge and information needed by the user to perform a task. The refinement allows the qualitative analysis of user tasks, workload and performance. For example, the number of cognitive tasks and information that pilots need to remember may be effective indicators for assessing user workload [9]. This kind of analysis can be used to reason about automation design [16].
Step 3: User interface look and feel prototyping. This step aims at developing the user interface look and feel. A result of this step is described in the screen-shot of the EFIS CP presented in Figure 1. The widgets are organised in a style that is compatible with the library defined by the ARINC 661 standard [2].
Step 4: User interface formal modelling. The behaviour of the user interface is specified using ICO models. The behaviour of the barometer settings part of the EFIS CP user interface is represented by the ICO model presented in Figure 3. The left part of this model (that has been enlarged) is dedicated to the pressure mode. As described in Section 3.1, the pressure mode can be in two different mutually exclusive states: STD and QNH. The user can switch from one mode to the other one by clicking either STD or QNH CheckButton (clicking on a CheckButton while already in the corresponding mode is also possible but will have no impact on the pressure mode). This behaviour is defined by the enlarged part of the ICO model presented in Figure 3. The state of the pressure mode is represented by the presence of a token within "QNH" or "STD" places (in Figure 3, place "STD" holds a token meaning that the current pressure mode is STD). Transitions "changePressureMode_1" and "changePressureMode_2" (resp. "changePressureMode_3" and "changePressureMode_4") correspond to the availability of the "qnhClick" (resp. "stdClick") event: when one of these two transitions is enabled, the "qnhClick" event is available (thus enabling the QNH CheckButton). The "changePressureMode_1" transition therefore makes it possible to switch from STD pressure mode to QNH pressure mode as a result of clicking on
the QNH CheckButton. The “changePressureMode_2” transition allows the user to click on the QNH CheckButton while in QNH pressure mode without any impact on the pressure mode. The right part of the ICO model presented in Figure 3 (behind the enlarged part of the model) allows pressure to be changed. While we only present here a part of the ICO model describing the behaviour of the EFIS user interface, it is important to note that the ICO notation has also been used to describe the behaviour of the widgets and the window manager. The ICO models can be validated using the simulation feature.
**Step 5: Formal analysis.** The PetShop tool provides the means to analyse ICO models by the underlying Petri net model [26] using static analysis techniques as supported by the Petri net theory [25]. The ICO approach is based on high level Petri nets. As a result the analysis approach builds on and extends these static analysis techniques. Analysis results must be carefully taken into account by the analyst as the underlying Petri net model can be quite different from the ICO model. Such analysis has been included in CIRCUS and can be interleaved with the editing and simulation of the model, thus helping to correct it in a style that is similar to that provided by spell checkers in modern text editors [8]). It is thus possible to check well-formedness properties of the ICO model, such as absence of deadlocks, as well as user interface properties, either internal properties (e.g., reinitialiability) or external properties (e.g., availability of widgets). Note that it is not possible to express these user interface properties explicitly — the analyst needs to express these properties as structural and behavioural Petri net properties that can be then analysed automatically in PetShop.
The analysis of the enlarged part of the ICO model presented in Figure 3 allows developers to check that, whatever action is taken, the pair of places “STD” and “QNH” will always hold one (and only one) token, exhibiting the mutual exclusion of the two states. Transitions connected to these places correspond to the availability of two events “qnhClick” and “stdClick”, and therefore it can be demonstrated that these events will remain available whatever action is triggered. Lastly, there are two transitions in the model that correspond to the event “qnhClick” (transitions “changePressureMode_1” and “changePressureMode_2”). This could potentially lead to non-determinism in the model. However, as “changePressureMode_1” has place “STD” as input place and “changePressureMode_2” has “QNH” place as input place, non-determinism is avoided due to the mutual exclusive marking of these places.
**Step 6: Compatibility assessment between task models and user interface models.** This step aims at guaranteeing that the task model and the formal model of the user interface behaviour are complete and consistent together (thus helping to guarantee that procedures followed by the operators are correctly supported by the system). A correspondence editing panel is used to establish the matching between interactive input tasks (from the task model) with system inputs (from the system model) and between system outputs (from the system model) with interactive output tasks (from the task model). The co-execution part of the SWAN tool provides support for validation as it makes it possible to find inconsistencies between the two models, e.g., sequences of user actions allowed by the system model and forbidden by the task model, or sequences of user actions that should be available but are not because of inadequate system design. The SWAN tool also provides support for automated scenario-based testing of an interactive application [5].
### 3.3 Modelling and analysis using PVSio-web
The focus of the PVSio-web analysis is the interaction logic of the EFIS data entry software. Here, we describe the modelling and analysis workflow supported by the tool, and highlight the main characteristics of the developed models (the full description is included as an example application in the PVSio-web tool distribution [19]).
Step 1: Define the visual appearance of the prototype. The visual aspect of the prototype is based on a picture of the EFIS panel. The PVSio-web Prototype Builder is used to create the visual appearance of the prototype and is defined using the Prototype Builder. A picture of the EFIS panel and KCCU are loaded in the tool, and interactive areas are created over relevant buttons and display elements (see Figure 4). Fifteen input areas were created over the picture of the Keyboard and Cursor Control Unit, to capture user actions over the number pad keys, as well as over other data entry keys (ENT, CLR, ESC, and the units conversion button). Four display elements were created for rendering relevant status variables of the PVS model: a touchscreen display element handles user input on the EditBoxNumeric for entering the barometer pressure value; two display elements render the STD and QNH CheckButtons; an additional display element renders the pressure units.
Step 2: Define the behaviour of the prototype. The prototype is driven by a PVS model that includes an accurate description of the following features of the system: the modal behaviour of the data entry system; the numeric algorithm for units conversion; the logic for interactive data entry; and the data types used for computation (double, integer, Boolean). Modelling patterns were used to guide the development of the models (some of these patterns are described in [11]). The model was developed using, in combination, the PVSio-web Emucharts Editor and the Emacs-based model editor of PVS. The Emucharts editor allowed us to create a statechart-based diagram that can be automatically translated into PVS models. The Emacs-based model editor was used to build a library function linked to the Emucharts diagram to improve modelling efficiency. The developed Emucharts (shown in Figure 5) includes the following elements: 3 states (STD, QNH, and EDIT PRESSURE) representing three different modes of operation; 25 transitions, representing the effect of user actions on the Keyboard and Cursor Control Unit when adjusting the barometer settings, and internal timers handling timeouts due to inactivity during interactive
data entry; and 9 status variables, representing the state of the system (units, display value, programmed value, etc.). The library function, ProcessKey, is used within the Emucharts diagrams to define the effect on state variables of transitions associated with key presses.
**Step 3: Model validation.** This analysis ensures internal consistency of the model, as well as checking accuracy with respect to the real system. Internal consistency is assessed by discharging proof obligations (called type-check-conditions) automatically generated by the PVS theorem prover. These proof obligations check coverage of conditions, disjointness of conditions, and correct use of data types. For the developed Emucharts model, PVS generated 22 proof obligations, all of which were discharged automatically by the PVS theorem prover. Accuracy of the model is assessed by using the prototype to engage with Airbus cockpit experts. Experts can press buttons of the prototype, and watch the effect of interactions on the prototype displays. By this means it is possible to check that the prototype behaviour resembles that of the real system.
**Step 4: Formal analysis.** The prototype and the PVS theorem prover are used in combination to analyse the model. The prototype is used to perform a lightweight formal analysis suitable to establish a common understanding within a multidisciplinary team of the correct interpretation of safety requirements and usability properties. This analysis consists in the execution of sample input key sequences demonstrating scenarios where a given requirement is either satisfied or fails. This initial lightweight analysis based on test cases is extended to a full formal analysis using the PVS theorem prover, to check that requirements and properties of the model are satisfied for all input key sequences in all reachable model states. To perform this full analysis, PVS theorems need to be defined that capture the requirements and properties. They are expressed using structural induction and a set of templates described in [12]. An example
property that can be analysed is consistency of device response to user actions. The consistency property is motivated by the fact that users quickly develop a mental model that embodies their expectations of how to interact with a user interface. Because of this, the overall structure of a user interface should be consistent in its layout, screen structure, navigation, terminology, and control elements. Example consistency properties are: a designated set of function buttons always change the mode; a further set of keys, for example concerned with number entry, will always change the barometric variable relevant to the mode but do not change the mode; an enter key always changes the relevant parameter when in the relevant mode; an escape key ensures that the value set in the mode is discarded and the barometric value reverts to the value it had when it entered the mode.
In PVS, the consistency template is formulated as a property of a group of actions $A_c \subseteq \wp(S \rightarrow S)$, or it may be the same action under different modes, requiring that all actions in the group have similar effects on specific state variables selected using a filter. The relation $\text{consistent} : C \times C \rightarrow T$ connects a filtered state, before an action occurs (captured by $\text{filter\_pre} : S \times MS \rightarrow C$), with a filtered state after the action (captured by $\text{filter\_post} : S \times MS \rightarrow C$). The description of the filters and the $\text{consistent}$ relation specify the consistency across states and across actions. Here $MS$ is defined to be a set of modes. Two modes are relevant here. A set of modes not defined includes the mode that allows the entry of the barometer value. Within the barometer entry mode are two modes that relate to the different units that can be used to enter the barometric values, defined as: inHg and hPa. A general notion of consistency assumes that the property is restricted to a set of states focused by a guard: $\text{guard} : S \times MS \rightarrow T$. This guard may itself be limited by a mode. The general consistency template can therefore be expressed as:
<table>
<thead>
<tr>
<th>Consistency</th>
</tr>
</thead>
<tbody>
<tr>
<td>$\forall a \in A_c \subseteq \wp(S \rightarrow S), s \in S, m \in MS: \text{guard}(s, m) \land \text{consistent}(\text{filter_pre}(s, m), \text{filter_post}(a(s), m))$</td>
</tr>
</tbody>
</table>
Two examples are now used to illustrate the use of the consistency template. The first is that a set of actions never change the barometric entry mode. The $\text{pre\_filter}$ and $\text{post\_filter}$ both extract the barometric entry mode, and are of the form $\text{filter\_baro}(st: \text{state}): \text{UnitsType} = \text{Units}(st)$. This property relates directly to modes and therefore the mode parameter can be omitted in the filter definition. The set of actions determined by $\text{state\_transitions\_actions}$ which encompasses the set of transitions as determined by the enabled actions in the barometric mode. In summary, the $\text{consistent}$ relation in this case is equality and the theorem that instantiates the consistency template is:
$\text{modeinvariant: THEOREM FORALL (pre, post: state):}$
$\text{state\_transitions\_actions}(pre, post) \Rightarrow (\text{filter\_baro}(pre) = \text{filter\_baro}(post))$
On the other hand the action $\text{click\_hPa}$ always changes the entry mode. So here $\text{consistent}$ is inequality.
$\text{alwayschgmode: THEOREM FORALL (pre, post: state):}$
$\text{(post = click\_hPa(pre) AND guard\_baro(pre))}$
$\Rightarrow \text{filter\_baro}(pre) \neq \text{filter\_baro}(post)$
### 4 Tool comparison
In this section, we first present the criteria that were identified to compare the characteristics and functionalities of the two tools. These criteria form a basis for the comparison of these two tools.
4.1 Comparison criteria
We identified 22 criteria suitable to compare the characteristics and functionalities of the two tools. These criteria are general, and can be used as a reference to define a taxonomy suitable to classify and compare other similar formal IDEs for user interface modelling and analysis. These criteria are divided in four categories:
- General aspects of the tools
1. Scope/purpose of the tool within the development process, e.g., requirements analysis, prototyping, verification.
2. Tool features, e.g., modelling of user tasks and goals, analysis of usability properties, simulation of user tasks.
3. Tool extensibility, e.g., to model systems from different application domains, or to perform a different type of analysis.
4. Prerequisites and background knowledge, e.g., distributed systems, object oriented languages, Petri Nets, task modelling, PVS.
5. IDE instance and principle, e.g., Eclipse plugin, Web, Netbeans API.
6. IDE availability, e.g., snapshot, demo, downloadable, open source.
- Modelling features
7. Notation names, e.g., ICO, HAMSTERS, EmuCharts, PVS.
8. Notation instance, e.g., Petri Net, state machines, higher-order logic.
9. Notation paradigm, e.g., event-based, state-based, declarative.
10. Structuring models, e.g., object-oriented, functional, component-based.
11. Model editing features, e.g., textual, visual, autocompletion support.
12. Suggestions for model improvements, e.g., strengthening of pre-conditions.
- Prototyping features
13. Support for prototype building, e.g., visual editor, library of widgets.
14. Execution environment of the prototype, e.g., Java virtual machine, Javascript execution environment.
15. User interface testing, e.g., automatic generation of input test cases.
16. Human-machine interaction techniques, e.g., Pre-WIMP (input dissociated from output), WIMP, post-WIMP, tangible, multimodal.
- Analysis of human-machine interaction
18. Verification type, e.g., functional verification, performance analysis, hierarchical task analysis.
19. Verification technology, e.g., theorem proving, static analysis.
20. Scalability of the analysis, e.g., illustrative examples, industrial size.
22. Related development process, e.g., user centered design, waterfall development process, agile development.
4.2 CIRCUS and PVSio-web comparison
In this section, we discuss, following the four categories of criteria identified above, the comparison of CIRCUS and PVSio-web. A detailed assessment of all the criteria presented above is presented in tabular form in the Appendix.
General aspects of the tools. From a high-level perspective, the scope of CIRCUS and PVSio-web is the formal development of user interfaces. Both tools support modelling and analysis of the interaction logic of the user interface software. However, the two tools offer different modelling and analysis technologies that are tailored to support two different (and complementary) styles of assessment of user interfaces. CIRCUS supports explicit modelling of user tasks and goals, allowing developers to simulate user tasks and check their compatibility with the interactive behaviour of the system. PVSio-web, on the other hand, supports explicit modelling of general usability and safety properties, facilitating the assessment of compliance of a user interface design with design guidelines and best design practices (e.g., according to standards or regulatory frameworks). Whilst a certain level of background knowledge is needed to use the tools effectively, basic knowledge about Petri nets and task models (for CIRCUS) and state machines and state charts (for PVSio-web) is already sufficient to get started with illustrative examples. This is extremely useful to reduce the typical knowledge barriers faced by novice users. The two IDEs are developed using standard technologies supported by multiple platforms (Netbeans Visual API for CIRCUS, Web technologies for PVSio-web), and can be executed on any standard desktop/laptop computer.
Modelling features. Both tools provide powerful graphical IDEs designed to assist developers in the creation of formal models. CIRCUS uses specialised graphical notations and diagrams: the ICO notation is used for building system models; the HAMSTERS notation is used for describing user tasks. ICOs are based on object-oriented extensions to Petri nets, and support both event-based and state-based modelling. HAMSTERS is a procedural notation. The complexity of models is handled using information hiding (as in object-oriented programming languages), and component-based model structures. This facilitates the creation of complex models, as well as the implementation of editing features that are important for developers, such as auto-completion of models and support for parametric models. The use of specific notations, however, limits the ability of developers to import external models created with other tools, or export CIRCUS models to other tools. PVSio-web, on the other hand, uses modelling patterns to support the modelling process. Developers can use either a graphical notation (Emucharts diagrams, or a textual notation (PVS higher-order logic), or a combination of both, to specify the system model. This has many benefits: software developers that are familiar with Statecharts can build models using a language that is familiar for them, and gradually learn PVS modelling by examples, checking how the Emucharts model translates into PVS; Emucharts models can be translated into popular formal modelling languages different than PVS (e.g., VDM); expert PVS users can still develop entire models using PVS higher-order logic only, and software developers can import these PVS models as libraries, thus facilitating model re-use. The main drawback is that the current implementation of Emucharts lacks mechanisms for model optimisation (e.g., a battery of similar PVS functions is generated instead of a single function with a parameter), and technical skills are necessary to understand model improvements suggested by the tool (through the PVS type-checker).
Prototyping features. Both IDEs provide a visual editor for rapid generation of prototypes supporting a range of interaction styles, including: graphical user interfaces with windows, icons, menus, and pointer (WIMP); user interfaces with physical buttons (pre-WIMP); touchscreen-based user interfaces (post-WIMP); and multi-modal user interfaces (e.g., providing both visual and auditory feedback). Both tools promote the use of the Model-View-Controller (MVC) paradigm, with a clear separation between
the visual appearance of the prototype and the logic behaviour. Whilst prototypes developed with the
two IDEs share these similarities, prototype building and implementation is substantially different in the
two IDEs. CIRCUS prototypes are developed in Java (for their visual appearance) and in ICO models
(for their behaviour). Developers can define their own widgets library. For example, for the case study
presented in Section 3 we created a library of widgets whose visual aspect and behaviour is compatible
with that described in the ARINC 661 standard. PVSio-web prototypes are developed in JavaScript, and
their behaviour is defined by a PVS executable model. Rapid prototyping is enabled by a lightweight
building process where the visual aspect of the prototype is defined by a picture of the real device,
virtually reducing to zero the time and effort necessary to define the visual appearance of the prototype.
Initial support for code generation is also available for MISRA-C, for behavioural models developed
using Emucharts [21]. A specialised tool (Prototype Builder) is provided with the IDE, to facilitate the
identification of interactive areas over the picture, and to link these areas to the PVS model. The current
implementation of the Prototype Builder supports only the definition of push buttons and digital display
elements, and developers need to edit a JavaScript template manually to introduce more sophisticated
widgets (e.g., knobs, graphical displays, etc.). Integration of these more sophisticated widgets in the
Prototype Builder is currently under development.
Analysis of human-machine interaction. Multiple verification technologies are used in the two IDEs
to enable the efficient analysis of human-machine interaction. Both tools build on established formal
methods technologies, and enable lightweight formal analysis based on simulation and testing. CIR-
cUS implements static analysis techniques from Petri nets theory to perform automatic analysis of well-
formedness properties of the model (absence of deadlocks, token conservation), and of basic aspects of
the interactive system design (e.g., reinitiability of the user interface and availability of widgets). Simu-
lation is used for functional analysis and quantitative assessment of the system. Either direct interaction
with the prototype and automated execution of task models can be used during simulations. Properties
verified by this means include: compliance with task models; statistics about the total number of user
tasks, and estimation of the cognitive workload of the user based on the types of human-machine inter-
actions necessary to operate the system. PVSio-web uses the standard PVS theorem proving system to
analyse well-formedness properties of the model (coverage of conditions, disjointness of conditions, and
correct use of data types). Usability and safety requirements can be verified using both lightweight for-
mal verification and full formal verification. Lightweight verification is based on interactive simulations
with the prototypes. User interactions can be recorded and used later as a basis for automated testing
in a way similar to the way task models are used in CIRCUS. Full formal verification is carried out in
the PVS theorem prover, and is partially supported by property templates capturing common usability
and safety requirements described in the ANSI/AAMI/IEC HF75 usability standard. Although the full
formal analysis is in general not fully automatic, the combined use of property templates and modelling
patterns usually leads to proof attempts where minimal human intervention is necessary to guide the
theorem prover (typically, for case-splitting and instantiation of symbolic identifiers). Proof tactics for
full automatic verification of a standard battery of property templates are currently under development.
Dedicated front-ends presenting verification results in a form accessible to human factors specialists are
also being investigated.
5 Conclusion and perspectives
In this paper, we presented a first step towards providing guidance to developers to understand which
formal tool can be used most effectively for which kind of analysis of interactive systems. This is
achieved through the identification of 22 criteria enabling the characterisation of IDEs for interactive systems formal prototyping and development. These criteria have been used to compare two state-of-the-art formal tools developed by two different research teams: CIRCUS, a toolkit for model-based development of interactive systems; and PVSio-web, a toolkit for model-based development of user interface software based on the PVS theorem proving system. In order to assess all the criteria, we modelled and analysed a case study from the avionics domain using these two tools. The result of this comparison led to the conclusion that the two studied tools are complementary rather than competitive tools. Whilst they have roughly the same scope (formal development of user interfaces), these two tools enable different kinds of modelling and analysis. For instance, CIRCUS supports explicit modelling of user tasks and goals, allowing developers to simulate user tasks and check their compatibility with the interactive behaviour of the system while PVSio-web supports explicit modelling of general usability and safety properties, facilitating the assessment of compliance of a user interface design with design guidelines and best design practices. These two analysis styles are complementary, and both provide important insights about how to develop high-confidence user interfaces. Based on this understanding, we are now developing means to integrate the two IDEs, to enable new powerful analysis features, such as automated scenario-based testing of user interfaces [5]. The envisioned integration is introduced at two levels: at the modelling level, developing PVSio-web extensions for importing/translating HAMSTERS task models into PVS models and properties; and at the simulation level, building CIRCUS extensions for co-execution of task models and PVSio-web prototypes. Additional extensions under development for the two toolkits include: modelling patterns for describing human-machine function allocation; proof tactics and complementary use of different verification technologies for improved automation of usability and safety properties; innovative front-ends for inspecting formal proofs supporting safety and usability claims of user interfaces; and widgets libraries for different application domains.
Acknowledgment. This work is partially supported by: Project NORTE-01-0145-FEDER-000016, financed by the North Portugal Regional Operational Programme (NORTE 2020), under the PORTUGAL 2020 Partnership Agreement, and through the European Regional Development Fund (ERDF); Conselho Nacional de Desenvolvimento Científico e Tecnológico (CNPq) PhD scholarship.
References
Evaluation of formal IDEs for human-machine interface design and analysis
### Appendix
<table>
<thead>
<tr>
<th><strong>Formal IDE</strong></th>
<th><strong>CIRCUS</strong></th>
<th><strong>PVSio-web</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>1. Scope/purpose</strong></td>
<td>Interactive system prototyping, development, and analysis.</td>
<td>User interface software prototyping and analysis.</td>
</tr>
<tr>
<td><strong>2. Tool features</strong></td>
<td>User task and goals description, interaction logic (dialog) and interaction techniques modelling, interactive system prototyping, support for verification of properties, assessment of compatibility between user tasks and interactive system prototype.</td>
<td>Interaction logic modelling, rapid prototyping of user interface software, verification of safety requirements and usability properties, code generation and documentation.</td>
</tr>
<tr>
<td><strong>3. Tool extensibility</strong></td>
<td>Each tool within CIRCUS offers an API supporting connection to other computing systems. For instance, connecting PetShop execution engine to cockpit software simulators or connecting Petri net analysis tools to PetShop analysis module.</td>
<td>PVSio-web has a plug-in based architecture that enables the rapid introduction of new modelling, prototyping, and analysis tools; support for new widgets types and widgets libraries can be introduced in Prototype Builder; Emucharts Editor can be extended with new model generators and code generators.</td>
</tr>
<tr>
<td><strong>4. Background knowledge</strong></td>
<td>Object-Oriented Petri Nets (for Petshop), Java programming, distributed systems, hierarchical task modelling.</td>
<td>State machines, PVS higher order logic and PVS theorem proving (only required for full formal verification).</td>
</tr>
<tr>
<td><strong>5. IDE principles</strong></td>
<td>Netbeans Visual API</td>
<td>Web</td>
</tr>
<tr>
<td><strong>6. IDE availability</strong></td>
<td>Available upon request for collaborations only.</td>
<td>Open source, downloadable at <a href="http://www.pvsioweb.org">http://www.pvsioweb.org</a></td>
</tr>
<tr>
<td><strong>7. Notation names</strong></td>
<td>ICO, HAMSTERS.</td>
<td>Emucharts, PVS.</td>
</tr>
<tr>
<td><strong>8. Notation instance</strong></td>
<td>Petri Net, task models.</td>
<td>Statecharts, higher-order logic.</td>
</tr>
<tr>
<td><strong>10. Structuring models</strong></td>
<td>Object-oriented, component-based.</td>
<td>Module-based.</td>
</tr>
<tr>
<td><strong>11. Model editing features</strong></td>
<td>Graphical editing of task models, ICO models and their correspondences, auto-completion features of models, visual representation of properties on models, simulation of models at editing time.</td>
<td>Graphical and textual editing of models, automatic generation of PVS models.</td>
</tr>
<tr>
<td><strong>12. Suggestions for model improvement</strong></td>
<td>Suggestions for model correction by real time analysis of models and continuous visualization of analysis results.</td>
<td>Strengthening of pre- and post- conditions of transition functions (based on proof obligations generated by PVS).</td>
</tr>
</tbody>
</table>
*continues on next page...*
<table>
<thead>
<tr>
<th>Formal IDE</th>
<th>CIRCUS</th>
<th>PVSio-web</th>
</tr>
</thead>
<tbody>
<tr>
<td>13. Prototype building</td>
<td>Use of graphical user interface editor of NetBeans for standard interactions (e.g. WIMP), possible to create interactive components and assemble them for non standard interactions (e.g. multitouch).</td>
<td>Visual editing, based on a picture of the real system.</td>
</tr>
<tr>
<td>15. User interface testing</td>
<td>Automatic execution of test sequences based on a task model</td>
<td>Automated execution of input test sequences recorded during interactions with the prototype.</td>
</tr>
<tr>
<td>16. Human-machine interaction techniques</td>
<td>Pre-WIMP, WIMP, post-WIMP, multimodal, multi-touch. Run-time re-configuration of interaction techniques.</td>
<td>Pre-WIMP, WIMP, post-WIMP, multimodal.</td>
</tr>
<tr>
<td>17. Code generation</td>
<td>Run-time execution of ICO models (to support prototyping and co-execution of task and system models).</td>
<td>Run-time execution of PVS executable models through the PVS ground evaluator (to support rapid prototyping), and automatic generation of production code compliant to MISRA-C (only for formal models developed using Emucharts diagrams).</td>
</tr>
<tr>
<td>18. Verification types</td>
<td>Well-formedness of the model: absence of deadlocks, token conservation. Functional analysis: reinitiability; availability of widgets; compliance with task models. Quantitative analysis: statistics about the total number of user tasks; estimation of the cognitive workload of the user based on the types of human-machine interactions necessary to operate the system. Simulation-based analysis through model animation.</td>
<td>Functional analysis, including: coverage of conditions, disjointness of conditions, correct use of data types, compliance with design requirements. Simulation-based analysis through model animation.</td>
</tr>
<tr>
<td>19. Technology</td>
<td>Static analysis of Petri Nets; interactive simulation of task and system models. Proofs and properties verification left to the analyst.</td>
<td>Theorem proving; interactive simulations.</td>
</tr>
<tr>
<td>21. Analysis of the wider socio-technical system</td>
<td>Modelling of integrated views of the three elements of socio-technical systems (organization, human and interactive systems); however, FRAM-based description of organization and variability of performance has only be addressed at model level and not a tool level.</td>
<td>Modelling patterns based on distributed cognition theory have been explored in PVS but are not currently integrated in the IDE.</td>
</tr>
<tr>
<td>22. Related development process</td>
<td>User centered design (task-based design), iterative development, model-based engineering.</td>
<td>User centered design, agile development, model-based engineering.</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://haslab.uminho.pt/saulosilva/files/f-ide2016-camera-ready.pdf", "len_cl100k_base": 10979, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 43774, "total-output-tokens": 14108, "length": "2e13", "weborganizer": {"__label__adult": 0.00038743019104003906, "__label__art_design": 0.001255035400390625, "__label__crime_law": 0.0002815723419189453, "__label__education_jobs": 0.00188446044921875, "__label__entertainment": 0.0001055002212524414, "__label__fashion_beauty": 0.00019657611846923828, "__label__finance_business": 0.0002582073211669922, "__label__food_dining": 0.00038504600524902344, "__label__games": 0.00087738037109375, "__label__hardware": 0.0018711090087890625, "__label__health": 0.0005164146423339844, "__label__history": 0.0004668235778808594, "__label__home_hobbies": 0.00014209747314453125, "__label__industrial": 0.0006451606750488281, "__label__literature": 0.0003237724304199219, "__label__politics": 0.00022101402282714844, "__label__religion": 0.0004973411560058594, "__label__science_tech": 0.08367919921875, "__label__social_life": 0.00010895729064941406, "__label__software": 0.01523590087890625, "__label__software_dev": 0.88916015625, "__label__sports_fitness": 0.0003025531768798828, "__label__transportation": 0.0011968612670898438, "__label__travel": 0.00025582313537597656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61109, 0.02121]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61109, 0.38756]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61109, 0.86646]], "google_gemma-3-12b-it_contains_pii": [[0, 3090, false], [3090, 6819, null], [6819, 10186, null], [10186, 13987, null], [13987, 16229, null], [16229, 18611, null], [18611, 21655, null], [21655, 25786, null], [25786, 27982, null], [27982, 30061, null], [30061, 33900, null], [33900, 36341, null], [36341, 40642, null], [40642, 44876, null], [44876, 48761, null], [48761, 53301, null], [53301, 54830, null], [54830, 57531, null], [57531, 61109, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3090, true], [3090, 6819, null], [6819, 10186, null], [10186, 13987, null], [13987, 16229, null], [16229, 18611, null], [18611, 21655, null], [21655, 25786, null], [25786, 27982, null], [27982, 30061, null], [30061, 33900, null], [33900, 36341, null], [36341, 40642, null], [40642, 44876, null], [44876, 48761, null], [48761, 53301, null], [53301, 54830, null], [54830, 57531, null], [57531, 61109, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61109, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61109, null]], "pdf_page_numbers": [[0, 3090, 1], [3090, 6819, 2], [6819, 10186, 3], [10186, 13987, 4], [13987, 16229, 5], [16229, 18611, 6], [18611, 21655, 7], [21655, 25786, 8], [25786, 27982, 9], [27982, 30061, 10], [30061, 33900, 11], [33900, 36341, 12], [36341, 40642, 13], [40642, 44876, 14], [44876, 48761, 15], [48761, 53301, 16], [53301, 54830, 17], [54830, 57531, 18], [57531, 61109, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61109, 0.13876]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
faceb6fd0ee3409d2b54612b186ac5fdc254622c
|
On position restricted substring searching in succinct space
Wing-Kai Hon a, Rahul Shah b, Sharma V. Thankachan b,∗, Jeffrey Scott Vitter c
a Department of Computer Science, National Tsing Hua University, Hsinchu, Taiwan
b Department of Computer Science, Louisiana State University, Baton Rouge, LA, USA
c Department of Electrical Engineering and Computer Science, University of Kansas, USA
ARTICLE INFO
Article history:
Received 25 June 2012
Received in revised form 27 September 2012
Accepted 27 September 2012
Available online 2 October 2012
Keywords:
Succinct data structures
Pattern matching
Range searching
ABSTRACT
We study the position restricted substring searching (PRSS) problem, where the task is to index a text \(T[0 \ldots n-1]\) of \(n\) characters over an alphabet set \(\Sigma\) of size \(\sigma\), in order to answer the following: given a query pattern \(P\) (of length \(p\)) and two indices \(\ell\) and \(r\), report all \(\text{occ}_{\ell,r}\) occurrences of \(P\) in \(T[\ell \ldots r]\). Known indexes take \(O(n \log n)\) bits or \(O(n \log^{\frac{1}{2}} n)\) bits space, and answer this query in \(O(p + \log n + \text{occ}_{\ell,r}, \log n)\) time or in optimal \(O(p + \text{occ}_{\ell,r})\) time respectively, where \(\epsilon\) is any positive constant. The main drawback of these indexes is their space requirement of \(\Omega(n \log n)\) bits, which can be much more than the optimal \(n \log \sigma\) bits to store the text \(T\). This paper addresses an open question asked by Mäkinen and Navarro [LATIN, 2006], which is whether it is possible to design a succinct index answering PRSS queries efficiently. We first study the hardness of this problem and prove the following result: a succinct (or a compact) index cannot answer PRSS queries efficiently in the pointer machine model, and also not in the RAM model unless bounds on the well-researched orthogonal range query problem improve. However, for the special case of sufficiently long query patterns, that is for \(p = \Omega(\log^{\frac{1}{2}} n)\), we derive an \(|\text{CSAf}\| + |\text{CSAr}\| + o(n)\) bits index with optimal query time, where \(|\text{CSAf}\|\) and \(|\text{CSAr}\|\) are the space (in bits) of the compressed suffix arrays (with \(O(p)\) time for pattern search) of \(T\) and \(\overline{T}\) (the reverse of \(T\)) respectively. The space can be reduced further to \(|\text{CSAf}\| + o(n)\) bits with a resulting query time will be \(O(p + \text{occ}_{\ell,r} + \log^{\frac{3}{2}} n)\). For the general case, where there is no restriction on pattern length, we obtain an \(O(\frac{n}{\log n} \log \sigma)\) bits index with \(O(p + \text{occ}_{\ell,r} + n^\epsilon)\) query time. We use suffix sampling techniques to achieve these space-efficient indexes.
© 2012 Elsevier B.V. All rights reserved.
1. Introduction
Given a text \(T[0 \ldots n-1]\) of size \(n\) over an alphabet set \(\Sigma\) of size \(\sigma\), the fundamental problem in text indexing is to preprocess \(T\) and maintain an index such that whenever a pattern \(P\) (of length \(p\)) comes as a query, all \(\text{occ}\) occurrences of \(P\) in \(T\) can be reported efficiently. Classical indexes such as suffix trees and suffix arrays can answer this query in \(O(p + \text{occ})\) and \(O(p + \log n + \text{occ})\) time respectively [18,17,16]. However, these indexes take \(O(n \log n)\) bits space, which can be much more than the optimal \(n \log \sigma\) bits. For example, in the human genome data (\(\Sigma = \{A, G, C, T\}\)), \(\log \sigma\) is 2 whereas \(\log n\)
✿ Early part of this work appeared in the Proceedings of Data Compression Conference, 2008 [8] (Chien et al., 2008). This work is supported in part by Taiwan NSC Grant 99-2221-E-007-123-MY3 (Wing-Kai Hon), and by US NSF Grant CCF-1017623 (Rahul Shah).
∗ Corresponding author. Postal address: 291 Coates Hall, LSU Computer Science, Baton Rouge, LA 70803, USA. Tel.: +1 225 578 4355; fax: +1 225 578 1465.
E-mail addresses: wkhon@cs.nthu.edu.tw (W.-K. Hon), rahul@csc.lsu.edu (R. Shah), thanks@csc.lsu.edu (S.V. Thankachan), jsv@ku.edu (J.S. Vitter).
1570-8667/© 2012 Elsevier B.V. All rights reserved.
http://dx.doi.org/10.1016/j.jda.2012.09.002
is around 30. This gives a clear motivation to design succinct\(^1\) or compressed indexes, as such indexes may fit in faster but space-limited main memory. This long standing problem was positively answered via the compressed suffix array by Grossi and Vitter [10] and the FM-index by Ferragina and Manzini [8] (see [15] for an excellent survey). While these indexes handle general pattern matching queries efficiently in compressed space, our focus is on designing space efficient indexes for a special problem called Position-restricted substring searching (PRSS) defined as follows:
The query input consists of a pattern \( P \) (of length \( p \)) and two indices \( \ell \) and \( r \), and the task is to report all \( \text{occ}_{\ell,r} \) occurrences of \( P \) in \( T[\ell \ldots r] \).
PRSS queries are fundamental in many text searching applications, where the objective is to search only a part of the text collection. Examples include restricting the search to a subset of dynamically chosen documents in a document database, restricting the search to only parts of a long DNA sequence, etc. [14]. This problem also finds applications in information retrieval.
### 1. Related work
The PRSS problem was introduced by Mäkinen and Navarro [14]. They proposed an \( O(n \log n) \) bits index with a query time of \( O(p + \log n + \text{occ}_{\ell,r} \cdot \log n) \), where \( \text{occ}_{\ell,r} \) is the number of occurrences of \( P \) in \( T[\ell \ldots r] \). Similar work has been done by Hon et al. [12]. Mäkinen and Navarro [14] proposed an \( O(n \log^{1+\epsilon} n) \) bits index as well (where \( \epsilon \) is any positive constant) with a near optimal query time of \( O(p + \log n + \text{occ}_{\ell,r}) \), which was improved to \( O(p + \log \log n + \text{occ}_{\ell,r}) \) by Kopelowitz et al. [13] and further to optimal \( O(p + \text{occ}_{\ell,r}) \) by Bille and Gørtz [3]. Another optimal query time solution is by Crochemore et al. [7], however its space requirement is \( O(n^{1+\epsilon}) \) bits.
The counting version of PRSS is also a well studied problem. The \( O(n \log n) \) bits index by Mäkinen and Navarro [14] can count the number of occurrences \( \text{occ}_{\ell,r} \) in \( O(p + \log n) \) time. A solution by Bille and Gørtz [3] takes the space of \( O(n \log^2 n / \log \log n) \) bits and can answer queries in \( O(p + \log \log n) \) time. Another solution by Kopelowitz et al. [13] slightly improves this query time to \( O(p + \log \log \log n) \), while maintaining the same space bounds. Recently, Gagie and Gawrychowski proposed an \( O(n \log n) \) bits solution with \( (p + \log \log n) \) query time, which can be improved to optimal \( O(p) \) if \( \sigma = \log^{O(1)} n \) [9].
### 1.2. Our contributions
In this paper, we investigate the possibility of deriving space efficient indexes (i.e., taking \( O(n \log \sigma) \) bits space instead of \( \Omega(n \log n) \) bits) for the PRSS problem. The following are our main results:
- **Designing an** \( O(n \log \sigma) \) **bits index which can answer PRSS queries in poly-logarithmic time is at least as hard as designing a linear space structure performing 3-dimensional orthogonal range reporting in poly-logarithmic time.**
- **On a pointer machine, we derive a lower bound of** \( \Omega(n \log^2 n / \log \log n) \) **bits of space for any index with** \( O(p \log^{O(1)} n + \text{occ}_{\ell,r}) \) **query time.**
- **For the special case when** \( p = \Omega(\log^3 n) \), **we develop an** \(|\text{CSA}_T| + |\text{CSA}_r| + o(n)\) **bits index with optimal** \( O(p + \text{occ}_{\ell,r}) \) **query time, where** \(|\text{CSA}_T|\) **and** \(|\text{CSA}_r|\) **are the space (in bits) of the compressed suffix arrays (with O(p) time for pattern search) of** \( T \) **and** \( \bar{T} \) **(the reverse of** \( T \) **respectively and** \( \epsilon \) **is any positive constant. The index space can be further reduced to** \(|\text{CSA}_T| + o(n)\) **bits, with a resulting query time of** \( O(p + \text{occ}_{\ell,r} + \log^{3+\epsilon} n)\).**
- **We develop an** \( O(\frac{1}{\epsilon^3} n \log \sigma) \) **bits index that can answer PRSS queries in** \( O(p + \text{occ}_{\ell,r} + n^\epsilon) \) **time without any restriction on pattern length.**
### 1.3. Organization of the paper
Section 2 is dedicated to preliminaries. In Section 3, we prove the hardness of the PRSS problem and also derive a space lower bound in the pointer machine model for any index with query time \( O(p \log^{O(1)} + \text{occ}_{\ell,r}) \). In Section 4, we derive our compressed index with optimal query time for the special case when the query pattern is sufficiently long. Finally, in Section 5, we introduce a succinct (compact) index which does not have any restriction on pattern length. However, in this case, the query time is sub-linear rather than poly-logarithmic.
---
\(^1\) In this paper, we use the terms succinct and compact interchangeably to mean \( O(n \log \sigma) \) bit index. The term compressed refers to entropy based compression.
2. Preliminaries
2.1. Suffix arrays and compressed suffix arrays
For the text $T[0 \ldots n-1]$ to be indexed, each substring $T[i \ldots n-1]$, with $i \in [0, n-1]$, is called a suffix of $T$. The suffix array $SA[0 \ldots n-1]$ is an array of length $n$, where $SA[i]$ is the starting position (in $T$) of the $i$th lexicographically smallest suffix of $T$ [16]. An important property of $SA$ is that the starting positions of all suffixes with the same prefix are always stored in a contiguous region in $SA$. Based on this property, we define the suffix range of a pattern $P$ to be the maximal range $[a, b]$ in $SA$, such that for all $j \in [a, b]$, $SA[j]$ is the starting point of a suffix of $T$ with $P$ as a prefix. The suffix array along with a data structure called the longest common prefix (LCP) array takes $O(n \log n)$ bits space and can find the suffix range of a pattern $P$ in $O(p + \log n)$ time.
The compressed suffix array (CSA) is a space-efficient version of the suffix array which takes space close to the size of the text [10,8,1,15]. For our purpose, we shall use the $nH_k + O(n) + o(n \log \sigma)$-bits CSA by Belazzougui and Navarro [1], which can find the locus of $P$ in $O(p)$ time, even when the alphabet size is large. Here $H_k$ represents the $k$th order empirical entropy of the text. Using backward search, the suffix ranges of all suffixes of the pattern $P$ can be computed in $O(p)$ time.
2.2. Orthogonal range reporting in 3-D (RR3D)
Let $S$ be a given set of $n$ points of the form $(x_i, y_i, z_i)$ in a $[0, n-1] \times [0, n-1] \times [0, n-1]$ grid. An orthogonal range reporting query consists of three input ranges $((x', x''), (y', y''), (z', z''))$ and the task is to output all those points $(x_j, y_j, z_j)$ such that $x' \leq x_j \leq x''$, $y' \leq y_j \leq y''$ and $z' \leq z_j \leq z''$. The best known data structure for this problem in the RAM model is by Chan et al. [4], having a space requirement of $O(n \log^{2+\epsilon} n)$ bits and query time of $O((\log \log n + |\text{output}|)$, where $|\text{output}|$ is the output size.
3. Hardness of PRSS problem
In this section, we first prove the hardness of the PRSS problem.
Theorem 1. Designing a succinct (compact) index answering PRSS queries in poly-logarithmic time is at least as hard as designing a linear space data structure performing 3-dimensional orthogonal range reporting in poly-logarithmic time.
Assuming a poly-logarithmic query time structure for PRSS in succinct space, we shall show how 3-dimensional range searching can be made poly-logarithmic in linear space.
Let $S$ be a set of $n$ points of the form $(x_i, y_i, z_i)$ for $i = 0, 1, 2, \ldots, n-1$ in a $[0, n-1] \times [0, n-1] \times [0, n-1]$ grid, such that $z_i \leq z_{i+1}$. Note that each point in $S$ can be represented using $O(\log n)$ bits. Let $\langle s \rangle$ denote the binary string representing an integer $s \in [0, n-1]$ and let $\langle s \rangle^\dagger$ denote the reverse of $\langle s \rangle$. Now we construct the following string $T'$, which consists of $O(n \log n)$ characters taken from an alphabet set $\Sigma = \{0, 1, \#, \star\}$ and is formed by concatenating the following:
$$T' = \langle y_1 \rangle \# \langle x_1 \rangle \star \langle y_2 \rangle \# \langle x_2 \rangle \star \cdots \star \langle y_n \rangle \# \langle x_n \rangle \star$$
Assume there exists a succinct (or a compact) data structure answering PRSS queries in poly-logarithmic time. Then, we first index $T'$ (having constant alphabet size) in $O((|T'|)/\log n)$ bits space. Now consider a 3-dimensional range reporting query (RR3D) on $S$, where we need to output all the points within the query box $[x', x''] \times [y', y''] \times [z', z'']$. We prove that this RR3D on $S$ can be reduced to $O(\log^2 n)$ PRSS queries on $T'$. The following lemma shows how to generate patterns corresponding to RRSS queries.
Lemma 1. A given range $[a, b]$, where $0 \leq a < b \leq n-1$ can be represented by a set $S' = \{s_1, s_2, \ldots, s_k\}$ of $k \leq 2 \log n$ binary strings. None of these strings is a prefix of another. For any integer $j$, $j \in [a, b]$ if and only if there exists $s_i \in S'$ such that $s_i$ is a prefix of $(j)$.
Proof. Let $A$ be a trie of binary representations of all integers $\in [0, n-1]$, such that the $i$th leftmost leaf represents integer $i-1$. Now any range $[a, b]$ on leaves in $A$ can be split into $k \leq 2 \log n$ non-overlapping sub-ranges such that each of these sub-range represents the complete sub-tree of a unique node $u$ in $A$. Then $S'$ is the set of paths($u$)'s of all such nodes, where path($u$) is the concatenation of edge labels (0 or 1) in the path from root to $u$. $\square$
Let $S_x'$ and $S_y'$ represent the set of binary strings (constructed using Lemma 1) corresponding to the intervals $[x', x'']$ and $[y', y'']$ respectively. Then, we generate a set $S_p'$ of binary strings as follows: $S_p' = \{S_x' \# s_x \mid s_x \in S_x', s_y \in S_y'\}$. Note that we can have $O(\log^2 n)$ combinations of $s_x$ and $s_y$, hence $S_p'$ consists of $O(\log^2 n)$ distinct binary strings of length $O(\log n)$.
Lemma 2. If an occurrence of a string $P \in S_p'$ overlaps with the $i$th # symbol in $T'$, then $x' \leq x_i \leq x''$ and $y' \leq y_i \leq y''$.
Theorem 2. Let \( P = S_x \# s_y \) where \( s_x \in S_X \) and \( s_y \in S_Y \). Then \( s_x \) is a prefix of \( \langle x_i \rangle \) and \( s_y \) is a prefix of \( \langle y_i \rangle \). Hence the result follows from Lemma 1. \( \square \)
Lemma 3. Putting all space terms together, we have the following lemma.
Proof. Let \( \ell \) and \( r \) be such that \( z_{\ell} < z' \leq z_{\ell+1} \leq z'_r \leq z_{r+1} \). In order to report the points within \( [x'.x'' \times [y'.y''] \times [z'.z''] \), it is enough to find those occurrences of \( P \in S_p \) within \( T'[\ell', r'] \), where \( \ell' \) is the starting location of the \( \ell \)th * in \( T' \) and \( r' \) is the starting location of the \( r \)th * in \( T' \) (proof follows from the definition of \( T' \) and Lemma 2). Thus we have a total of \( O(n \log^2 n) \) PRSS queries with patterns of length \( O(\log n) \). Therefore, if there exists an \( O(n \log \sigma) \) bits index with \( O(p \log^2 n + |\text{output}| \log^2 n) \) query time for PRSS queries, then there exists an \( O(n \log n) \) bits data structure performing RR3D in \( O(\log^{c+3} n + |\text{output}| \log^d n) \) time, where \( c \) and \( d \) are any constants. This completes the proof of Theorem 1.
Theorem 2. Any data structure supporting PRSS queries in \( O(p \log^{O(1)} n + \text{occ}_{\ell,r}) \) time in pointer machine model has to use \( \Omega(n \log^2 n / \log^2 \log n) \) bits space.
Proof. Assume that there exists an \( o(n \log^2 n / \log^2 \log n) \) bits index answering PRSS queries in \( O(p \log^2 n + \text{occ}_{\ell,r}) \) time. Then we can construct an \( o(n \log^2 n / \log^2 \log n) \) words data structure supporting RR3D queries in time \( O(\log^{c+3} n + |\text{output}|) \) (follows from the proof of Theorem 1). In the pointer machine model, this contradicts the following lower bound by Chazelle: any data structure supporting RR3D queries in \( O(\log^{O(1)} n + |\text{output}|) \) has to use at least \( \Omega(n \log^2 n / \log^2 \log n) \) words space [5]. \( \square \)
4. Optimal-time compressed index for long patterns
In this section, we prove the following.
Theorem 3. There exists an \( |\text{CSA}_f| + |\text{CSA}_r| + o(n) \) bits index supporting PRSS queries in optimal \( O(p + \text{occ}_{\ell,r}) \) time for \( p = \Omega(\log^{2+\epsilon} n) \).
Let \( \alpha = \Theta(\log^{2+\epsilon}/2) \) be a sampling factor. We introduce the following definitions:
- **\( \alpha \)-sampled suffix:** \( T[x..n-1] \) is an \( \alpha \)-sampled suffix if \( x \equiv 0 \mod \alpha \).
- **\( \alpha \)-sampled prefix:** \( T[0..x-1] \) is an \( \alpha \)-sampled prefix if \( x \equiv 0 \mod \alpha \).
- **Offset-\( t \) occurrence:** An occurrence of \( P \) at position \( i \) in \( T \) (i.e., \( P = T[i..i+p-1] \)) is an offset-\( t \) occurrence, if \( i \equiv t \mod \alpha \).
Therefore, an offset-0 occurrence of \( P \) is always a prefix of an \( \alpha \)-sampled suffix of \( T \). The following is true for an offset-\( t \) occurrence with \( 1 \leq t < p \) (hence it is true for \( p > \alpha \) as \( \alpha > t \)): the prefix \( P[0..t-1] \) of \( P \) (of length \( t \)) is a suffix of an \( \alpha \)-sampled prefix \( T[0..x-1] \) and the suffix \( P[t..p-1] \) of \( P \) (of length \( p-t \)) is a prefix of an \( \alpha \)-sampled suffix \( T[x..n-1] \).
4.1. Our index
The construction of our index is based on the assumption that \( p \geq \alpha \). It consists of the following components:
- **CSA\(_f\):** compressed suffix array of \( T \).
- **CSA\(_r\):** compressed suffix array of \( \overline{T} \), where \( \overline{T} \) is the reverse of \( T \) (i.e., \( \overline{T}[i] = T[n-1-i] \)).
- **RR3D Structure:** For each \( \alpha \)-sampled suffix \( T[x..n-1] \), we define a triplet \( (x, y, z) \) such that \( y \) is the lexicographic rank of \( T[x..n-1] \) among all suffixes of \( T \) and \( z \) be the lexicographic rank of \( T[0..x-1] \) among the reverse of all prefixes of \( T \). Therefore, the \( y \)th leftmost entry (i.e., corresponding to the \( y \)th leftmost leaf in its suffix tree) in \( \text{CSA}_f \) corresponds to \( T[x..n-1] \) and the \( z \)th leftmost entry in \( \text{CSA}_r \) corresponds to \( T[0..x-1] \). Since we have \( \Theta(n/\alpha) \) \( \alpha \)-sampled suffixes, the number of triplets is bounded by \( O(n/\alpha) \). The size of an RR3D structure [4] maintained over these triplets can be bounded by \( O((n/\alpha) \log^{2+\epsilon} n) = o(n) \) bits (assume \( \epsilon' < \epsilon/2 \)).
Putting all space terms together, we have the following lemma.
Lemma 3. The total space of our index is \( |\text{CSA}_f| + |\text{CSA}_r| + o(n) \) bits.
4.2. Query answering
Let \( [L'_f, R'_f] \) be the suffix range of \( P[t..p-1] \) in \( \text{CSA}_f \). Using backward search on \( \text{CSA}_f \), \( [L'_f, R'_f] \) for \( t = 0, 1, 2, \ldots, p-1 \) can be computed in \( O(p) \) time. Similarly, let \( [L'_r, R'_r] \) be the suffix range of \( P[0..t-1] \) (where \( t \geq 1 \)) in \( \text{CSA}_r \). Then, \( [L'_r, R'_r] \)
for \( t = 1, 2, \ldots, \alpha - 1 \) can be computed using backward search on \( \text{CSAr} \) in \( O(\alpha) \) time. Our query answering algorithm consists of \( \alpha \) steps and in the \( \alpha \)th step for \( t = 0, 1, 2, \ldots, \alpha - 1 \), we retrieve all offset-\( t \) occurrences of \( P \) in \( T[\ell, r] \).
First, we show how to retrieve all offset-0 occurrences. That is, we show how to find all \( \alpha \) sampled suffixes \( T[x \ldots x + \alpha - 1] \) satisfying the conditions \( x \equiv 0 \pmod{\alpha} \), \( T[x \ldots x + \alpha - 1] = P[0 \ldots \alpha - 1] \) and \( \ell \leq x \leq r \). As we have defined a tuple \((x, y, z)\) for each \( \alpha \) sampled suffix, the above PRSS query can be reduced to the following geometric range searching problem: report all those tuples \((x, y, z)\) such that \( \ell \leq x \leq r \) and \( L_\| x \| y \| z \| \leq y \leq R_\| x \| y \| z \| \). This query can be answered in \( O(\log \log n + occt) \) time using the RR3D structure, where \( occt \) is the number of offset-0 occurrences. Let \((x, y, z)\) be a reported point, then \( x \) is an answer to PRSS query. Now, we generalize this to finding offset-\( t \) occurrences. Finding all offset-\( t \) occurrences for \( 1 \leq t \leq \alpha - 1 \) can be reduced to the following geometric problem: report all those tuples \((x, y, z)\) such that \( \ell + t \leq x \leq r + t \), \( L_\| x \| y \| z \| \leq y \leq R_\| x \| y \| z \| \). This query can be answered in \( O(\log \log n + occt) \) time using the RR3D structure, where \( occt \) is the number of offset-\( t \) occurrences. Let \((x, y, z)\) be a reported point, then \( x - t \) is an answer to PRSS query. That is, \( T[x - t \ldots x - t + \alpha - 1] = P \) and \( \ell \leq x - t \leq r \).
**Lemma 4.** For \( p = \Omega(\log^{2+\epsilon} n) \), the PRSS query can be answered in optimal \( O(p + occt) \) time, where \( occt \) is the number of occurrences of \( P \) in \( T[\ell \ldots r] \).
**Proof.** The total time for computing the suffix ranges in \( \text{CSAr} \) is \( O(p) \) and the time for finding the suffix ranges of \( \alpha - 1 \) prefixes of \( P \) in \( \text{CSAr} \) is \( O(\alpha) \). The RR3D structure takes \( O(\log \log n + occt) \) time for reporting all offset-\( t \) occurrences within \( T[\ell, r] \). Therefore the total time is \( O(p + \alpha + \sum_{t=0}^{\alpha - 1} (\log \log n + occt)) = O(p + \log^{2+\epsilon} n \log \log n + occt) \). Note that \( p = \Omega(\log^{2+\epsilon} n) \). \( \square \)
By combining Lemmas 3 and 4, we have Theorem 3.
The index space can be further reduced and the following is our result.
**Theorem 4.** There exists an \( |\text{CSAr}| + o(n) \) bits index supporting PRSS queries in \( O(p + occt + \log^{3+\epsilon} n) \) time, for \( p = \Omega(\log^{2+\epsilon} n) \).
**Proof.** Hon et al. [11] showed that \( \text{CSAr} \) can be maintained as a sparse suffix tree taking \( O(n \log n / \beta) \) bits in addition to \( \text{CSAr} \) with an \( O(\beta) \) slow down in pattern search. Therefore \( \text{CSAr} \) can be replaced by an \( o(n) \) bits sparse suffix tree by choosing \( \beta = \Theta(\log^{1+\epsilon/2} n) \). The resulting query time will be \( O(p + occt + \alpha \beta) \). \( \square \)
5. A compact index for all patterns
In this section, we introduce a compact index for PRSS queries which works without any restriction on the length of the query pattern. This can be seen as an extension of the 2-D technique by Grossi and Vitter [10] to 3 dimensions. The main result is captured in the following theorem.
**Theorem 5.** There exists an \( O(\frac{1}{\epsilon^2} n \log \sigma) \) bits space and \( O(p + \log \log n + n^\epsilon) \) query time index for the PRSS problem.
Firstly, we introduce a new sampling factor \( \alpha' = \epsilon \log \omega \), where \( 0 < \epsilon < 1/2 \). Then, an occurrence of \( P \) at position \( i \) in \( T \) is an offset-\( t \) occurrence for some \( t = i \mod (\alpha') \) \( \in [0, \alpha' - 1] \). Based on pattern length, we categorize the occurrences into two cases and handle both cases separately.
5.1. Case A: offset-\( t \) occurrences for \( t < p \)
In this case a suffix of \( P \) will be a prefix of some \( \alpha' \)-sampled suffix. Therefore all such occurrences can be reported using a similar data structure described in the previous section. Because of the new sampling factor \( \alpha' \), the number of triplets to be maintained as an RR3D structure is \( O(n/\alpha') \). Note that Chan et al.'s RR3D structure is not affordable in this scenario. In Section 5.1, we will introduce an RR3D structure taking \( O(\frac{1}{\epsilon^2} n \log n) \) bits space which can answer queries in \( O(n^\epsilon + |\text{output}|) \) time, where \( \epsilon \) is any positive constant. By using this data structure, our index space can be bounded by \( O((n/\alpha')^{1/\epsilon^2} \log n) = O(\frac{1}{\epsilon^2} n \log \sigma) \) bits.
5.2. Case B: offset-\( t \) occurrences for \( t \geq p \)
This case is necessary when the pattern size \( p < \alpha' \), the sampling factor. We call a segment \( T[x \ldots x + \alpha' - 1] \) of \( T \) of length \( \alpha' \) a block \( B(x) \) if \( x \mod (\alpha') = 0 \). A block is always a prefix (of length \( \alpha' \)) of an \( \alpha' \)-sampled suffix. The number of blocks of \( T \) is \( \Theta(n/\alpha') = \Theta(n \log \sigma / (\epsilon \log n)) \), whereas the number of distinct blocks is \( \gamma = \sigma^{\alpha'} = O(n^\epsilon) \) and these are represented as \( B_1, B_2, B_3, \ldots, B_\gamma \). Let \( L_i \) be the sorted list of starting locations of the block \( B_i \) in \( T \). That is, it is the sorted list of all \( x \) such that \( B(x) = B_i \). Clearly \( \sum_{i=1}^{\gamma} |L_i| = O(n/\alpha') \) and the total space for maintaining all such \( L_i \)'s is \( O((n/\alpha') \log n) = O(\frac{1}{\epsilon^2} n \log \sigma) \) bits. We may call an occurrence of \( P \) within the block \( B_x \) as a type-\( \lambda \) occurrence.
Now all the answers to a PRSS query, which are of type-λ (for \(1 \leq \lambda \leq \gamma\)) can be retrieved as follows: first search for \(P\) in \(B_1\) and find all its occurrences using any standard string searching algorithm taking \(O(\sigma') = O(\epsilon \log_\sigma n)\) time. If there is an occurrence of \(P\) at position \(j\) in \(B_1[0 \ldots \alpha '-1]\), then \(P\) occurs at positions \(x + j\) for all those \(x\) with \(B(x) = B_j\). Therefore by using the list \(L_i\), all those type-λ occurrences of \(P\) within \(T[\ldots \ell_r]\) can be quickly computed in \(O(\log n + |output|)\) time \(\langle O(\log n)\) is needed for an initial binary search of \(\ell\) in \(L_i\). Repeat this procedure for \(\lambda = 1, 2, 3, \ldots, \gamma\), and the total query time can be bounded by \(O(p + \gamma \log n + occ_{\ell_r}) = O(p + occ_{\ell_r} + n^\epsilon)\) (by adjusting the constants).
5.3. RR3D structure: \(O\left(\frac{1}{\epsilon^2} \log n\right)\) bits space and \(O(n^\epsilon + |output|)\) query time
We note that similar structure also appears in [2], but we describe it here for the sake of completeness.
We first describe a 2-dimensional range reporting structure (RR2D). The idea is to use a B-tree with \(B = \Theta(\epsilon n^\epsilon)\). We may associate each point with a unique leaf node such that, the point with the \(i\)th smallest \(x\)-coordinate value (ties broken arbitrary) is stored in the \(i\)th leftmost leaf. Therefore, at leaf level, the points are maintained in the sorted order of \(x\)-coordinate values. An internal node stores all those points associated with the leaves in its sub-tree, which are maintained in the sorted order of \(y\)-coordinate. Now, any \(x\) range \([x, x']\) can be decomposed into \(O\left(\frac{1}{\epsilon} B\right) = O(n^\epsilon)\) non-overlapping ranges, such that the points within each range are maintained at some internal node in the sorted order of \(y\)-coordinate. Therefore, an RR2D query can now be decomposed into \(O(n^\epsilon)\) RR1D queries on a sorted array. Hence, the time for RR2D can be bounded by \(O(n^\epsilon \log n + |output|)\). The tree height is bounded by \(O(1/\epsilon)\), hence the total space is \(O\left(\frac{1}{\epsilon^2} \log n\right)\) bits.
Using the RR2D structure described above, our RR3D structure can be constructed as follows: maintain a B-tree with \(B = \Theta(\epsilon n^\epsilon)\) and associate each point with a unique leaf node, based on its \(z\)-coordinate value. Hence, at leaf level, all points are in the sorted order of \(z\)-coordinate. At every internal node, we maintain an RR2D structure (on \(x\) and \(y\) coordinates) of all those points associated with the leaves in its sub-tree. Using similar arguments as before, any RR3D query can now be decomposed into \(O(n^\epsilon)\) RR2D queries, taking \(O(n^{\epsilon^2} \log^2 n + |output|)\) time. The index space will be \(O(1/\epsilon)\) times the space of the RR2D structure, i.e., \(O\left(\frac{1}{\epsilon^2} \log n\right)\) bits. The factor of \(n^{\epsilon^2} \log^2 n\) can be made to \(n^\epsilon\) by scaling \(\epsilon\) up by factor of \(3\). This does not affect the space bounds in terms of the big-O factor.
6. Conclusions
We showed that the position restricted substring searching problem is hard if one wants to derive a succinct or compressed index. However, there are special cases when the pattern size is long or when we are allowed an additive \(n^\epsilon\) factor in search times. In these cases it is possible to derive space-efficient indexes. There are other unsolved hard problems like 2-dimensional matching or parameterized matching where no succinct solutions exist. An open question is: Can we achieve similar lower bounds and upper bounds (may be for special cases) for some of these problems?
References
|
{"Source-Url": "http://www.ittc.ku.edu/~jsv/Papers/HST12.PositionRestrictedSubstringSearching.pdf", "len_cl100k_base": 9167, "olmocr-version": "0.1.50", "pdf-total-pages": 6, "total-fallback-pages": 0, "total-input-tokens": 29785, "total-output-tokens": 11008, "length": "2e13", "weborganizer": {"__label__adult": 0.0004336833953857422, "__label__art_design": 0.0004093647003173828, "__label__crime_law": 0.0007724761962890625, "__label__education_jobs": 0.0016765594482421875, "__label__entertainment": 0.00014483928680419922, "__label__fashion_beauty": 0.0002694129943847656, "__label__finance_business": 0.000469207763671875, "__label__food_dining": 0.0005154609680175781, "__label__games": 0.0009245872497558594, "__label__hardware": 0.001944541931152344, "__label__health": 0.0013484954833984375, "__label__history": 0.0005006790161132812, "__label__home_hobbies": 0.0001653432846069336, "__label__industrial": 0.0006618499755859375, "__label__literature": 0.00060272216796875, "__label__politics": 0.00040030479431152344, "__label__religion": 0.0006337165832519531, "__label__science_tech": 0.448486328125, "__label__social_life": 0.00015211105346679688, "__label__software": 0.015960693359375, "__label__software_dev": 0.5224609375, "__label__sports_fitness": 0.0003542900085449219, "__label__transportation": 0.0006809234619140625, "__label__travel": 0.0002598762512207031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32042, 0.04342]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32042, 0.35486]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32042, 0.78148]], "google_gemma-3-12b-it_contains_pii": [[0, 4220, false], [4220, 9319, null], [9319, 14660, null], [14660, 19818, null], [19818, 25949, null], [25949, 32042, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4220, true], [4220, 9319, null], [9319, 14660, null], [14660, 19818, null], [19818, 25949, null], [25949, 32042, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32042, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 32042, null]], "pdf_page_numbers": [[0, 4220, 1], [4220, 9319, 2], [9319, 14660, 3], [14660, 19818, 4], [19818, 25949, 5], [25949, 32042, 6]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32042, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
68ca2bc04f16aed8c2f64f4adc986099f9fd572c
|
CHAPTER TWENTY-ONE
Shortest Paths
EVERY PATH IN a weighted digraph has an associated path weight, the value of which is the sum of the weights of that path’s edges. This essential measure allows us to formulate such problems as “find the lowest-weight path between two given vertices.” These shortest-paths problems are the topic of this chapter. Not only are shortest-paths problems intuitive for many direct applications, but they also take us into a powerful and general realm where we seek efficient algorithms to solve general problems that can encompass a broad variety of specific applications.
Several of the algorithms that we consider in this chapter relate directly to various algorithms that we examined in Chapters 17 through 20. Our basic graph-search paradigm applies immediately, and several of the specific mechanisms that we used in Chapters 17 and 19 to address connectivity in graphs and digraphs provide the basis for us to solve shortest-paths problems.
For economy, we refer to weighted digraphs as networks. Figure 21.1 shows a sample network, with standard representations. We have already developed an ADT interface with adjacency-matrix and adjacency-lists class implementations for networks in Section 20.1—we just pass true as a second parameter when we call the constructor so that the class keeps one representation of each edge, precisely as we did when deriving digraph representations in Chapter 19 from the undirected graph representations in Chapter 17 (see Programs 20.1 through 20.4).
As discussed at length in Chapter 20, we use references to abstract edges for weighted digraphs to broaden the applicability of our
Figure 21.1
Sample network and representations
This network (weighted digraph) is shown in four representations: list of edges, drawing, adjacency matrix, and adjacency lists (left to right). As we did for MST algorithms, we show the weights in matrix entries and in list nodes, but use edge references in our programs. While we often use edge weights that are proportional to their lengths in the drawing (as we did for MST algorithms), we do not insist on this rule because most shortest-paths algorithms handle arbitrary nonnegative weights (negative weights do present special challenges). The adjacency matrix is not symmetric, and the adjacency lists contain one node for each edge (as in unweighted digraphs). Nonexistent edges are represented by null references in the matrix (blank in the figure) and are not present at all in the lists. Self-loops of length 0 are present because they simplify our implementations. This approach has certain implications that are different for digraphs than the ones that we considered for undirected graphs in Section 20.1 and are worth noting. First, since there is only one representation of each edge, we do not need to use the $\text{from}$ method in the edge class (see Program 20.1) when using an iterator: In a digraph, $e.\text{from}(v)$ is true for every edge reference $e$ returned by an iterator for $v$. Second, as we saw in Chapter 19, it is often useful when processing a digraph to be able to work with its reverse graph, but we need a different approach than that taken by Program 19.1, because that implementation creates edges to create the reverse, and we assume that a graph ADT whose clients provide references to edges should not create edges on its own (see Exercise 21.3).
In applications or systems for which we need all types of graphs, it is a textbook exercise in software engineering to define a network ADT from which ADTs for the unweighted undirected graphs of Chapters 17 and 18, the unweighted digraphs of Chapter 19, or the weighted undirected graphs of Chapter 20 can be derived (see Exercise 21.10).
When we work with networks, it is generally convenient to keep self-loops in all the representations. This convention allows algorithms the flexibility to use a sentinel maximum-value weight to indicate that a vertex cannot be reached from itself. In our examples, we use self-loops of weight 0, although positive-weight self-loops certainly make sense in many applications. Many applications also call for parallel edges, perhaps with differing weights. As we mentioned in Section 20.1, various options for ignoring or combining such edges are appropriate in various different applications. In this chapter, for simplicity, none of our examples use parallel edges, and we do not allow parallel edges in the adjacency-matrix representation; we also do not check for parallel edges or remove them in adjacency lists.
All the connectivity properties of digraphs that we considered in Chapter 19 are relevant in networks. In that chapter, we wished to know whether it is possible to get from one vertex to another; in this chapter, we take weights into consideration—we wish to find the best way to get from one vertex to another.
**Definition 21.1** A shortest path between two vertices \( s \) and \( t \) in a network is a directed simple path from \( s \) to \( t \) with the property that no other such path has a lower weight.
This definition is succinct, but its brevity masks points worth examining. First, if \( t \) is not reachable from \( s \), there is no path at all, and therefore there is no shortest path. For convenience, the algorithms that we consider often treat this case as equivalent to one in which there exists an infinite-weight path from \( s \) to \( t \). Second, as we did for MST algorithms, we use networks where edge weights are proportional to edge lengths in examples, but the definition has no such requirement and our algorithms (other than the one in Section 21.5) do not make this assumption. Indeed, shortest-paths algorithms are at their best when they discover counterintuitive shortcuts, such as a path between two vertices that passes through several other vertices but has total weight smaller than that of a direct edge connecting those vertices. Third, there may be multiple paths of the same weight from one vertex to another; we typically are content to find one of them. Figure 21.2 shows an example with general weights that illustrates these points.
The restriction in the definition to simple paths is unnecessary in networks that contain edges that have nonnegative weight, because any cycle in a path in such a network can be removed to give a path that is no longer (and is shorter unless the cycle comprises zero-weight edges). But when we consider networks with edges that could have negative weight, the need for the restriction to simple paths is readily...
apparent: Otherwise, the concept of a shortest path is meaningless if there is a cycle in the network that has negative weight. For example, suppose that the edge 3–5 in the network in Figure 21.1 were to have weight \(-.38\), and edge 5–1 were to have weight \(-.31\). Then, the weight of the cycle 1–4–3–5–1 would be \(.32 + .36 - .38 - .31 = -.01\), and we could spin around that cycle to generate arbitrarily short paths.
Note carefully that, as is true in this example, it is not necessary for all the edges on a negative-weight cycle to be of negative weight; what counts is the sum of the edge weights. For brevity, we use the term negative cycle to refer to directed cycles whose total weight is negative.
In the definition, suppose that some vertex on a path from \(s\) to \(t\) is also on a negative cycle. In this case, the existence of a (nonsimple) shortest path from \(s\) to \(t\) would be a contradiction, because we could use the cycle to construct a path that had a weight lower than any given value. To avoid this contradiction, we restrict to simple paths in the definition so that the concept of a shortest path is well defined in any network. However, we do not consider negative cycles in networks until Section 21.7, because, as we see there, they present a truly fundamental barrier to the solution of shortest-paths problems.
To find shortest paths in a weighted undirected graph, we build a network with the same vertices and with two edges (one in each direction) corresponding to each edge in the graph. There is a one-to-one correspondence between simple paths in the network and simple paths in the graph, and the costs of the paths are the same; so shortest-paths problems are equivalent. Indeed, we build precisely such a network when we build the standard adjacency-lists or adjacency-matrix representation of a weighted undirected graph (see, for example, Figure 20.3). This construction is not helpful if weights can be negative, because it gives negative cycles in the network, and we do not know how to solve shortest-paths problems in networks that have negative cycles (see Section 21.7). Otherwise, the algorithms for networks that we consider in this chapter also work for weighted undirected graphs.
In certain applications, it is convenient to have weights on vertices instead of, or in addition to, weights on edges; and we might also consider more complicated problems where both the number of edges on the path and the overall weight of the path play a role. We can handle such problems by recasting them in terms of edge-weighted
This table gives all the shortest paths in the network of Figure 21.1 and their lengths. This network is strongly connected, so there exist paths connecting each pair of vertices.
The goal of a source-sink shortest-path algorithm is to compute one of the entries in this table; the goal of a single-source shortest-paths algorithm is to compute one of the rows in this table; and the goal of an all-pairs shortest-paths algorithm is to compute the whole table. Generally, we use more compact representations, which contain essentially the same information and allow clients to trace any path in time proportional to its number of edges (see Figure 21.8).
<table>
<thead>
<tr>
<th>Path</th>
<th>Length</th>
</tr>
</thead>
<tbody>
<tr>
<td>0-1</td>
<td>0.41</td>
</tr>
<tr>
<td>1</td>
<td>0.51</td>
</tr>
<tr>
<td>2</td>
<td>0.67</td>
</tr>
<tr>
<td>3</td>
<td>0.91</td>
</tr>
<tr>
<td>4</td>
<td>1.03</td>
</tr>
<tr>
<td>5</td>
<td>0.29</td>
</tr>
<tr>
<td>0-2</td>
<td>0.82</td>
</tr>
<tr>
<td>1-2</td>
<td>0.50</td>
</tr>
<tr>
<td>2-3</td>
<td>0.91</td>
</tr>
<tr>
<td>3-4</td>
<td>0.53</td>
</tr>
<tr>
<td>4-5</td>
<td>0.57</td>
</tr>
<tr>
<td>5-0</td>
<td>0.86</td>
</tr>
<tr>
<td>1-3</td>
<td>0.86</td>
</tr>
<tr>
<td>2-4</td>
<td>0.55</td>
</tr>
<tr>
<td>3-5</td>
<td>0.32</td>
</tr>
</tbody>
</table>
Source–sink shortest path
Given a start vertex \( s \) and a finish vertex \( t \), find a shortest path in the graph from \( s \) to \( t \). We refer to the start vertex as the source and to the finish vertex as the sink, except in contexts where this usage conflicts with the definition of sources (vertices with no incoming edges) and sinks (vertices with no outgoing edges) in digraphs.
Single-source shortest paths
Given a start vertex \( s \), find shortest paths from \( s \) to each other vertex in the graph.
All-pairs shortest paths
Find shortest paths connecting each pair of vertices in the graph. For brevity, we sometimes use the term all shortest paths to refer to this set of \( V^2 \) paths.
If there are multiple shortest paths connecting any given pair of vertices, we are content to find any one of them. Since paths have varying number of edges, our implementations provide methods that allow clients to trace paths in time proportional to the paths’ lengths. Any shortest path also implicitly gives us the shortest-path length, but our implementations explicitly provide lengths. In summary, to be precise, when we say “find a shortest path” in the problem statements just given, we mean “compute the shortest-path length and a way to trace a specific path in time proportional to that path’s length.”
Figure 21.3 illustrates shortest paths for the example network in Figure 21.1. In networks with $V$ vertices, we need to specify $V$ paths to solve the single-source problem and to specify $V^2$ paths to solve the all-pairs problem. In our implementations, we use a representation more compact than these lists of paths; we first noted it in Section 18.7, and we consider it in detail in Section 21.1.
In Java implementations, we build our algorithmic solutions to these problems into ADT implementations that allow us to build efficient client programs that can solve a variety of practical graph-processing problems. For example, as we see in Section 21.3, we implement solutions to the all-pairs shortest-paths classes as constructors within classes that support constant-time shortest-path queries. We also build classes to solve single-source problems so that clients who need to compute shortest paths from a specific vertex (or a small set of them) can avoid the expense of computing shortest paths for other vertices. Careful consideration of such issues and proper use of the algorithms that we examine can mean the difference between an efficient solution to a practical problem and a solution that is so costly that no client could afford to use it.
Shortest-paths problems arise in various guises in numerous applications. Many of the applications appeal immediately to geometric intuition, but many others involve arbitrary cost structures. As we did with minimum spanning trees (MSTs) in Chapter 20, we sometimes take advantage of geometric intuition to help develop an understanding of algorithms that solve the problems but stay cognizant that our algorithms operate properly in more general settings. In Section 21.5, we do consider specialized algorithms for Euclidean networks. More important, in Sections 21.6 and 21.7, we see that the basic algorithms are effective for numerous applications where networks represent an abstract model of the computation.
Road maps Tables that give distances between all pairs of major cities are a prominent feature of many road maps. We presume that the map maker took the trouble to be sure that the distances are the shortest ones, but our assumption is not necessarily always valid (see, for example, Exercise 21.11). Generally, such tables are for undirected graphs that we should treat as networks with edges in both directions corresponding to each road, though we might contemplate handling one-way streets for city maps and some similar applications.
As we see in Section 21.3, it is not difficult to provide other useful information, such as a table that tells how to execute the shortest paths (see Figure 21.4). In modern applications, embedded systems provide this kind of capability in cars and transportation systems. Maps are Euclidean graphs; in Section 21.4, we examine shortest-paths algorithms that take into account the vertex position when they seek shortest paths.
**Airline routes** Route maps and schedules for airlines or other transportation systems can be represented as networks for which various shortest-paths problems are of direct importance. For example, we might wish to minimize the time that it takes to fly between two cities or to minimize the cost of the trip. Costs in such networks might involve functions of time, of money, or of other complicated resources. For example, flights between two cities typically take more time in one direction than the other because of prevailing winds. Air travelers also know that the fare is not necessarily a simple function of the distance between the cities—situations where it is cheaper to use a circuitous route (or endure a stopover) than to take a direct flight are all too common. Such complications can be handled by the basic shortest-paths algorithms that we consider in this chapter; these algorithms are designed to handle any positive costs.
The fundamental shortest-paths computations suggested by these applications only scratch the surface of the applicability of shortest-paths algorithms. In Section 21.6, we consider problems from applications areas that appear unrelated to these natural ones, in the context of a discussion of reduction, a formal mechanism for proving relationships among problems. We solve problems for these applications by transforming them into abstract shortest-paths problems that do not have the intuitive geometric feel of the problems just described. Indeed, some applications lead us to consider shortest-paths problems in networks with negative weights. Such problems can be far more difficult to solve than are problems where negative weights cannot occur. Shortest-paths problems for such applications not only bridge a gap between elementary algorithms and unsolved algorithmic challenges but also lead us to powerful and general problem-solving mechanisms.
As with MST algorithms in Chapter 20, we often mix the weight, cost, and distance metaphors. Again, we normally exploit the natural appeal of geometric intuition even when working in more general
**Figure 21.4**
Distances and paths
Road maps typically contain distance tables like the one in the center for this tiny subset of French cities connected by highways as shown in the graph at the top. Though rarely found in maps, a table like the one at the bottom would also be useful, as it tells what signs to follow to execute the shortest path. For example, to decide how to get from Paris to Nice, we can check the table, which says to begin by following signs to Lyon.
settings with arbitrary edge weights; thus we refer to the “length” of paths and edges when we should say “weight” and to one path as “shorter” than another when we should say that it “has lower weight.” We also might say that \( v \) is “closer” to \( s \) than \( w \) when we should say that “the lowest-weight directed path from \( s \) to \( v \) has weight lower than that of the lowest-weight directed path \( s \) to \( w \),” and so forth. This usage is inherent in the standard use of the term “shortest paths” and is natural even when weights are not related to distances (see Figure 21.2); however, when we expand our algorithms to handle negative weights in Section 21.6, we must abandon such usage.
This chapter is organized as follows: After introducing the basic underlying principles in Section 21.1, we introduce basic algorithms for the single-source and all-pairs shortest-paths problems in Sections 21.2 and 21.3. Then, we consider acyclic networks (or, in a clash of shorthand terms, weighted DAGs) in Section 21.4 and ways of exploiting geometric properties for the source–sink problem in Euclidean graphs in Section 21.5. We then cast off in the other direction to look at more general problems in Sections 21.6 and 21.7, where we explore shortest-paths algorithms, perhaps involving networks with negative weights, as a high-level problem-solving tool.
Exercises
\( \triangleright \) 21.1 Label the following points in the plane 0 through 5, respectively:
\[(1, 3) \quad (2, 1) \quad (6, 5) \quad (3, 4) \quad (3, 7) \quad (5, 3).\]
Taking edge lengths to be weights, consider the network defined by the edges
\[1-0, 3-5, 5-2, 3-4, 5-1, 0-3, 0-4, 4-2, 2-3.\]
Draw the network and give the adjacency-lists structure that is built by Program 20.5.
21.2 Show, in the style of Figure 21.3, all shortest paths in the network defined in Exercise 21.1.
\( \circ \) 21.3 Develop a network class implementation that represents the reverse of the weighted digraph defined by the edges inserted. Include a “reverse copy” constructor that takes a graph as parameter and inserts all that graph’s edges to build its reverse.
\( \circ \) 21.4 Show that shortest-paths computations in networks with nonnegative weights on both vertices and edges (where the weight of a path is defined to be the sum of the weights of the vertices and the edges on the path) can be handled by building a network ADT that has weights on only the edges.
21.5 Find a large network online—perhaps a geographic database with entries for roads that connect cities or an airline or railroad schedule that contains distances or costs.
21.6 Write a random-network generator for sparse networks based on Program 17.12. To assign edge weights, define a random-edge–weight ADT and write two implementations: one that generates uniformly distributed weights, another that generates weights according to a Gaussian distribution. Write client programs to generate sparse random networks for both weight distributions with a well-chosen set of values of $V$ and $E$ so that you can use them to run empirical tests on graphs drawn from various distributions of edge weights.
21.7 Write a random-network generator for dense networks based on Program 17.13 and edge-weight generators as described in Exercise 21.6. Write client programs to generate random networks for both weight distributions with a well-chosen set of values of $V$ and $E$ so that you can use them to run empirical tests on graphs drawn from these models.
21.8 Implement a representation-independent network client that builds a network by taking edges with weights (pairs of integers between 0 and $V - 1$ with weights between 0 and 1) from standard input.
21.9 Write a program that generates $V$ random points in the plane, then builds a network with edges (in both directions) connecting all pairs of points within a given distance $d$ of one another (see Exercise 17.74), setting each edge’s weight to the distance between the two points that that edge connects. Determine how to set $d$ so that the expected number of edges is $E$.
21.10 Write a base class and derived classes that implement ADTs for graphs that maybe undirected or directed graphs, weighted or unweighted, and dense or sparse.
21.11 The following table from a published road map purports to give the length of the shortest routes connecting the cities. It contains an error. Correct the table. Also, add a table that shows how to execute the shortest routes, in the style of Figure 21.4.
<table>
<thead>
<tr>
<th></th>
<th>Providence</th>
<th>Westerly</th>
<th>New London</th>
<th>Norwich</th>
</tr>
</thead>
<tbody>
<tr>
<td>Providence</td>
<td>–</td>
<td>53</td>
<td>54</td>
<td>48</td>
</tr>
<tr>
<td>Westerly</td>
<td>53</td>
<td>–</td>
<td>18</td>
<td>101</td>
</tr>
<tr>
<td>New London</td>
<td>54</td>
<td>18</td>
<td>–</td>
<td>12</td>
</tr>
<tr>
<td>Norwich</td>
<td>48</td>
<td>101</td>
<td>12</td>
<td>–</td>
</tr>
</tbody>
</table>
21.1 Underlying Principles
Our shortest-paths algorithms are based on a simple operation known as relaxation. We start a shortest-paths algorithm knowing only the network’s edges and weights. As we proceed, we gather information
about the shortest paths that connect various pairs of vertices. Our algorithms all update this information incrementally, making new inferences about shortest paths from the knowledge gained so far. At each step, we test whether we can find a path that is shorter than some known path. The term “relaxation” is commonly used to describe this step, which relaxes constraints on the shortest path. We can think of a rubber band stretched tight on a path connecting two vertices: A successful relaxation operation allows us to relax the tension on the rubber band along a shorter path.
Our algorithms are based on applying repeatedly one of two types of relaxation operations:
- **Edge relaxation**: Test whether traveling along a given edge gives a new shortest path to its destination vertex.
- **Path relaxation**: Test whether traveling through a given vertex gives a new shortest path connecting two other given vertices.
Edge relaxation is a special case of path relaxation; we consider the operations separately, however, because we use them separately (the former in single-source algorithms; the latter in all-pairs algorithms).
In both cases, the prime requirement that we impose on the data structures that we use to represent the current state of our knowledge about a network’s shortest paths is that we can update them easily to reflect changes implied by a relaxation operation.
First, we consider edge relaxation, which is illustrated in Figure 21.5. All the single-source shortest-paths algorithms that we consider are based on this step: Does a given edge lead us to consider a shorter path to its destination from the source?
The data structures that we need to support this operation are straightforward. First, we have the basic requirement that we need to compute the shortest-paths lengths from the source to each of the other vertices. Our convention will be to store in a vertex-indexed array \( w_t \) the lengths of the shortest known paths from the source to each vertex. Second, to record the paths themselves as we move from vertex to vertex, our convention will be the same as the one that we used for other graph-search algorithms that we examined in Chapters 18 through 20: We use a vertex-indexed array \( spt \) to record the last edge on a shortest path from the source to the indexed vertex. These edges constitute a tree.
With these data structures, implementing edge relaxation is a straightforward task. In our single-source shortest-paths code, we use the following code to relax along an edge $e$ from $v$ to $w$:
```c
if (wt[w] > wt[v] + e.wt())
{ wt[w] = wt[v] + e.wt(); spt[w] = e; }
```
This code fragment is both simple and descriptive; we include it in this form in our implementations, rather than defining relaxation as a higher-level abstract operation.
**Definition 21.2** Given a network and a designated vertex $s$, a shortest-paths tree (SPT) for $s$ is a subnetwork containing $s$ and all the vertices reachable from $s$ that forms a directed tree rooted at $s$ such that every tree path is a shortest path in the network.
There may be multiple paths of the same length connecting a given pair of nodes, so SPTs are not necessarily unique. In general, as illustrated in Figure 21.2, if we take shortest paths from a vertex $s$ to every vertex reachable from $s$ in a network and from the subnetwork induced by the edges in the paths, we may get a DAG. Different shortest paths connecting pairs of nodes may each appear as a subpath in some longer path containing both nodes. Because of such effects, we generally are content to compute any SPT for a given digraph and start vertex.
Our algorithms generally initialize the entries in the $wt$ array with a sentinel value. That value needs to be sufficiently small that the addition in the relaxation test does not cause overflow and sufficiently large that no simple path has a larger weight. For example, if edge weights are between 0 and 1, we can use the value $V$. Note that we have to take extra care to check our assumptions when using sentinels in networks that could have negative weights. For example, if both vertices have the sentinel value, the relaxation code just given takes no action if $e.wt$ is nonnegative (which is probably what we intend in most implementations), but it will change $wt[w]$ and $spt[w]$ if the weight is negative.
Our code always uses the destination vertex as the index to save the SPT edges ($spt[w].v() == w$). For economy and consistency with Chapters 17 through 19, we use the notation $st[w]$ to refer to the vertex $spt[w].v()$ (in the text and particularly in the figures) to emphasize that the $spt$ array is actually a parent-link representation of the shortest-paths tree, as illustrated in Figure 21.6. We can compute
Section 21.1 Shortest-paths trees
The shortest paths from 0 to the other nodes in this network are 0-1, 0-5-4-2, 0-5-4-3, 0-5-4, and 0-5, respectively. These paths define a spanning tree, which is depicted in three representations (gray edges in the network drawing, oriented tree, and parent links with weights) in the center. Links in the parent-link representation (the one that we typically compute) run in the opposite direction than links in the digraph, so we sometimes work with the reverse digraph. The spanning tree defined by shortest paths from 3 to each of the other nodes in the reverse is depicted on the right. The parent-link representation of this tree gives the shortest paths from each of the other nodes to 2 in the original graph. For example, we can find the shortest path 0-5-4-3 from 0 to 3 by following the links st[0] = 5, st[5] = 4, and st[4] = 3.
The shortest path from s to t by traveling up the tree from t to s; when we do so, we are traversing edges in the direction opposite from their direction in the network and are visiting the vertices on the path in reverse order (t, st[t], st[st[t]], and so forth).
One way to get the edges on the path in order from source to sink from an SPT is to use a stack. For example, the following code prints a path from the source to a given vertex w:
```java
EdgeStack P = new EdgeStack(G.V()); Edge e = st[v];
while (e != null) { P.push(e); e = st[e.()]); }
if (P.empty()) Out.print(P.top().v());
while (!P.empty()) { Out.print("-"); P.top().w()); P.pop(); }
```
In a class implementation, we could use code similar to this to provide clients with an array that contains the edges of the path.
If we simply want to print or otherwise process the edges on the path, going all the way through the path in reverse order to get to the first edge in this way may be undesirable. One approach to get around this difficulty is to work with the reverse network, as illustrated in Figure 21.6. We use reverse order and edge relaxation in single-source problems because the SPT gives a compact representation of the shortest paths from the source to all the other vertices, in an array with just V entries.
Next, we consider path relaxation, which is the basis of some of our all-pairs algorithms: Does going through a given vertex lead us to a shorter path that connects two other given vertices? For example, suppose that, for three vertices s, x, and t, we wish to know whether it is better to go from s to x and then from x to t or to go from s to t without going through x. For straight-line connections in a Euclidean space, the triangle inequality tells us that the route through x cannot
be shorter than the direct route from $s$ to $t$, but for paths in a network, it could be (see Figure 21.7). To determine which, we need to know the lengths of paths from $s$ to $x$, $x$ to $t$, and of those from $s$ to $t$ (that do not include $x$). Then, we simply test whether or not the sum of the first two is less than the third; if it is, we update our records accordingly.
Path relaxation is appropriate for all-pairs solutions where we maintain the lengths of the shortest paths that we have encountered between all pairs of vertices. Specifically, in all-pairs shortest-paths code of this kind, we maintain an array of arrays $d$ such that $d[s][t]$ is the shortest-path length from $s$ to $t$, and we also maintain an array of arrays $p$ such that $p[s][t]$ is the next vertex on a shortest path from $s$ to $t$. We refer to the former as the *distances* matrix and the latter as the *paths* matrix. Figure 21.8 shows the two matrices for our example network. The distances matrix is a prime objective of the computation, and we use the paths matrix because it is clearly more compact than, but carries the same information as, the full list of paths that is illustrated in Figure 21.3.
In terms of these data structures, path relaxation amounts to the following code:
```c
if (d[s][t] > d[s][x] + d[x][t])
{ d[s][t] = d[s][x] + d[x][t]; p[s][t] = p[s][x]; }
```
Like edge relaxation, this code reads as a restatement of the informal description that we have given, so we use it directly in our implementations. More formally, path relaxation reflects the following:
**Property 21.1** If a vertex $x$ is on a shortest path from $s$ to $t$, then that path consists of a shortest path from $s$ to $x$ followed by a shortest path from $x$ to $t$.
*Proof:* By contradiction. We could use any shorter path from $s$ to $x$ or from $x$ to $t$ to build a shorter path from $s$ to $t$. ■
We encountered the path-relaxation operation when we discussed transitive-closure algorithms, in Section 19.3. If the edge and path weights are either 1 or infinite (that is, a path’s weight is 1 only if all that path’s edges have weight 1), then path relaxation is the operation that we used in Warshall’s algorithm (if we have a path from $s$ to $x$ and a path from $x$ to $t$, then we have a path from $s$ to $t$). If we define a path’s weight to be the number of edges on that path, then Warshall’s algorithm generalizes to Floyd’s algorithm for finding all shortest paths.
---
**Figure 21.7**
*Path relaxation*
These diagrams illustrate the relaxation operation that underlies our all-pairs shortest-paths algorithms. We keep track of the best known path between all pairs of vertices and ask whether a vertex $i$ is evidence that the shortest known path from $s$ to $t$ could be improved. In the top example, it is not; in the bottom example, it is. Whenever we encounter a vertex $i$ such that the length of the shortest known path from $s$ to $i$ plus the length of the shortest known path from $i$ to $t$ is smaller than the length of the shortest known path from $s$ to $t$, then we update our data structures to indicate that we now know a shorter path from $s$ to $t$ (head towards $i$ first).
Figure 21.8
All shortest paths
The two matrices on the right are compact representations of all the shortest paths in the sample network on the left, containing the same information in the exhaustive list in Figure 21.3. The distances matrix on the left contains the shortest-path length: The entry in row \( s \) and column \( t \) is the length of the shortest path from \( s \) to \( t \). The paths matrix on the right contains the information needed to execute the path: The entry in row \( s \) and column \( t \) is the next vertex on the path from \( s \) to \( t \).
<table>
<thead>
<tr>
<th></th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>.41</td>
<td>.82</td>
<td>.86</td>
<td>.50</td>
<td>.29</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>1.13</td>
<td>.51</td>
<td>.68</td>
<td>.32</td>
<td>1.06</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>.95</td>
<td>1.17</td>
<td>.50</td>
<td>1.09</td>
<td>.88</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>.45</td>
<td>.67</td>
<td>.91</td>
<td>0</td>
<td>.59</td>
<td>.38</td>
</tr>
<tr>
<td>4</td>
<td>.81</td>
<td>1.03</td>
<td>.32</td>
<td>.36</td>
<td>0</td>
<td>.74</td>
</tr>
<tr>
<td>5</td>
<td>1.02</td>
<td>.29</td>
<td>.53</td>
<td>.57</td>
<td>.21</td>
<td>0</td>
</tr>
</tbody>
</table>
shortest paths in unweighted digraphs; it further generalizes to apply to networks, as we see in Section 21.3.
From a mathematician’s perspective, it is important to note that these algorithms all can be cast in a general algebraic setting that unifies and helps us to understand them. From a programmer’s perspective, it is important to note that we can implement each of these algorithms using an abstract \(+\) operator (to compute path weights from edge weights) and an abstract \(<\) operator (to compute the minimum value in a set of path weights), both solely in the context of the relaxation operation (see Exercises 19.55 and 19.56).
Property 21.1 implies that a shortest path from \( s \) to \( t \) contains shortest paths from \( s \) to every other vertex along the path to \( t \). Most shortest-paths algorithms also compute shortest paths from \( s \) to every vertex that is closer to \( s \) than to \( t \) (whether or not the vertex is on the path from \( s \) to \( t \)), although that is not a requirement (see Exercise 21.18). Solving the source–sink shortest-paths problem with such an algorithm when \( t \) is the vertex that is farthest from \( s \) is equivalent to solving the single-source shortest-paths problem for \( s \). Conversely, we could use a solution to the single-source shortest-paths problem from \( s \) as a method for finding the vertex that is farthest from \( s \).
The paths matrix that we use in our implementations for the all-pairs problem is also a representation of the shortest-paths trees for each of the vertices. We defined \( p[s][t] \) to be the vertex that follows \( s \) on a shortest path from \( s \) to \( t \). It is thus the same as the vertex that precedes \( s \) on the shortest path from \( t \) to \( s \) in the reverse network. In other words, column \( t \) in the paths matrix of a network is a vertex-indexed array that represents the SPT for vertex \( t \) in its reverse. Conversely, we can build the paths matrix for a network by filling each column with the vertex-indexed array representation of the
Figure 21.9
All shortest paths in a network
These diagrams depict the SPTs for each vertex in the reverse of the network in Figure 21.8 (0 to 5, top to bottom), as network subtrees (left), oriented trees (center), and parent-link representation including a vertex-indexed array for path length (right). Putting the arrays together to form path and distance matrices (where each array becomes a column) gives the solution to the all-pairs shortest-paths problem illustrated in Figure 21.8.
SPT for the appropriate vertex in the reverse. This correspondence is illustrated in Figure 21.9.
In summary, relaxation gives us the basic abstract operations that we need to build our shortest paths algorithms. The primary complication is the choice of whether to provide the first or final edge on the shortest path. For example, single-source algorithms are more naturally expressed by providing the final edge on the path so that we need only a single vertex-indexed array to reconstruct the path, since all paths lead back to the source. This choice does not present a fundamental difficulty because we can either use the reverse graph as warranted or provide methods that hide this difference from clients. For example, we could specify a method in the interface that returns the edges on the shortest path in an array (see Exercises 21.15 and 21.16).
Accordingly, for simplicity, all of our implementations in this chapter include a method \( \text{dist} \) that returns a shortest-path length and either a method \( \text{path} \) that returns the first edge on a shortest path or a method \( \text{pathR} \) that returns the final edge on a shortest path. For example, our single-source implementations that use edge relaxation typically implement these methods as follows:
\[
\begin{align*}
\text{Edge} \ & \text{pathR}(\text{int } w) \ {\{ return \ spt[w]; \}} \\
\text{double} \ & \text{dist}(\text{int } v) \ {\{ return \ wt[v]; \}}
\end{align*}
\]
Similarly, our all-paths implementations that use path relaxation typically implement these methods as follows:
\[
\begin{align*}
\text{Edge} \ & \text{path}(\text{int } s, \text{ int } t) \ {\{ return \ p[s][t]; \}} \\
\text{double} \ & \text{dist}(\text{int } s, \text{ int } t) \ {\{ return \ d[s][t]; \}}
\end{align*}
\]
In some situations, it might be worthwhile to build interfaces that standardize on one or the other or both of these options; we choose the most natural one for the algorithm at hand.
**Exercises**
\(\triangleright\) 21.12 Draw the SPT from 0 for the network defined in Exercise 21.1 and for its reverse. Give the parent-link representation of both trees.
21.13 Consider the edges in the network defined in Exercise 21.1 to be undirected edges such that each edge corresponds to equal-weight edges in both directions in the network. Answer Exercise 21.12 for this corresponding network.
\(\triangleright\) 21.14 Change the direction of edge 0–2 in Figure 21.2. Draw two different SPTs that are rooted at 2 for this modified network.
21.15 Write a method that uses the pathR method from a single-source implementation to put references to the edges on the path from the source vertex to a given vertex w in a Java Vector.
21.16 Write a method that uses the path method from an all-paths implementation to put references to the edges on the path from a given vertex v to another given vertex w in a Java Vector.
21.17 Write a program that uses your method from Exercise 21.16 to print out all of the paths, in the style of Figure 21.3.
21.18 Give an example that shows how we could know that a path from s to t is shortest without knowing the length of a shorter path from s to x for some x.
21.2 Dijkstra’s Algorithm
In Section 20.3, we discussed Prim’s algorithm for finding the minimum spanning tree (MST) of a weighted undirected graph: We build it one edge at a time, always taking the shortest edge that connects a vertex on the MST to a vertex not yet on the MST. We can use a nearly identical scheme to compute an SPT. We begin by putting the source on the SPT; then, we build the SPT one edge at a time, always taking the next edge that gives a shortest path from the source to a vertex not on the SPT. In other words, we add vertices to the SPT in order of their distance (through the SPT) to the start vertex. This method is known as Dijkstra’s algorithm.
As usual, we need to make a distinction between the algorithm at the level of abstraction in this informal description and various concrete implementations (such as Program 21.1) that differ primarily in graph representation and priority-queue implementations, even though such a distinction is not always made in the literature. We shall consider other implementations and discuss their relationships with Program 21.1 after establishing that Dijkstra’s algorithm correctly performs the single-source shortest-paths computation.
Property 21.2 Dijkstra’s algorithm solves the single-source shortest-paths problem in networks that have nonnegative weights.
Proof: Given a source vertex s, we have to establish that the tree path from the root s to each vertex x in the tree computed by Dijkstra’s algorithm corresponds to a shortest path in the graph from s to x. This fact follows by induction. Assuming that the subtree so far computed
has the property, we need only to prove that adding a new vertex \( x \) adds a shortest path to that vertex. But all other paths to \( x \) must begin with a tree path followed by an edge to a vertex not on the tree. By construction, all such paths are longer than the one from \( s \) to \( x \) that is under consideration.
The same argument shows that Dijkstra’s algorithm solves the source–sink shortest-paths problem, if we start at the source and stop when the sink comes off the priority queue.
The proof breaks down if the edge weights could be negative, because it assumes that a path’s length does not decrease when we add more edges to the path. In a network with negative edge weights, this assumption is not valid because any edge that we encounter might lead to some tree vertex and might have a sufficiently large negative weight to give a path to that vertex shorter than the tree path. We consider this defect in Section 21.7 (see Figure 21.28).
Figure 21.10 shows the evolution of an SPT for a sample graph when computed with Dijkstra’s algorithm; Figure 21.11 shows an oriented drawing of a larger SPT tree. Although Dijkstra’s algorithm differs from Prim’s MST algorithm in only the choice of priority, SPT trees are different in character from MSTs. They are rooted at the start vertex and all edges are directed away from the root, whereas MSTs are unrooted and undirected. We sometimes represent MSTs as directed, rooted trees when we use Prim’s algorithm, but such structures are still different in character from SPTs (compare the oriented drawing in Figure 20.9 with the drawing in Figure 21.11). Indeed, the nature of the SPT somewhat depends on the choice of start vertex as well, as depicted in Figure 21.12.
Dijkstra’s original implementation, which is suitable for dense graphs, is precisely like Prim’s MST algorithm. Specifically, we simply change the assignment of the priority \( P \) in Program 20.6 from
\[
P = e.wt()\]
(the edge weight) to
\[
P = wt[v] + e.wt()\]
(the distance from the source to the edge’s destination). This change gives the classical implementation of Dijkstra’s algorithm: We grow an SPT one edge at a time, each time updating the distance to the tree of all vertices adjacent to its destination while at the same time
SHORTEST PATHS
21.2 295
0-1 .41
1-2 .51
2-3 .50
4-3 .36
3-5 .38
3-0 .45
0-5 .29
5-4 .21
1-4 .32
4-2 .32
5-1 .29
Figure 21.10
Dijkstra’s algorithm
This sequence depicts the construction of a shortest-paths spanning tree rooted at vertex 0 by Dijkstra’s algorithm for a sample network. Thick black edges in the network diagrams are tree edges, and thick gray edges are fringe edges. Oriented drawings of the tree as it grows are shown in the center, and a list of fringe edges is given on the right.
The first step is to add 0 to the tree and the edges leaving it, 0-1 and 0-5, to the fringe (top). Second, we move the shortest of those edges, 0-5, from the fringe to the tree and check the edges leaving it: The edge 5-4 is added to the fringe and the edge 5-1 is discarded because it is not part of a shorter path from 0 to 1 than the known path 0-1 (second from top). The priority of 5-4 on the fringe is the length of the path from 0 that it represents, 0-5-4. Third, we move 0-1 from the fringe to the tree, add 1-2 to the fringe, and discard 1-4 (third from top). Fourth, we move 5-4 from the fringe to the tree, add 4-3 to the fringe, and replace 1-2 with 4-2 because 0-5-4-2 is a shorter path than 0-1-2 (fourth from top). We keep at most one edge to any vertex on the fringe, choosing the one on the shortest path from 0. We complete the computation by moving 4-2 and then 4-3 from the fringe to the tree (bottom).
Property 21.3 With Dijkstra’s algorithm, we can find any SPT in a dense network in linear time.
Proof: As for Prim’s MST algorithm, it is immediately clear, from inspection of the code of Program 20.6, that the nested loops mean that the running time is proportional to $V^2$, which is linear for dense graphs.
For sparse graphs, we can do better by using a linked-list representation and a priority queue. Implementing this approach simply amounts to viewing Dijkstra’s algorithm as a generalized graph-searching method that differs from depth-first search (DFS), from breadth-first search (BFS), and from Prim’s MST algorithm in only the rule used to add edges to the tree. As in Chapter 20, we keep edges that connect tree vertices to nontree vertices on a generalized queue called the fringe, use a priority queue to implement the generalized queue, and provide for updating priorities so as to encompass DFS, BFS, and Prim’s algorithm in a single implementation (see Section 20.3). This priority-first search (PFS) scheme also encompasses
Dijkstra’s algorithm. That is, changing the assignment of $P$ in Program 20.7 to
$$P = wt[v] + e.wt()$$
(the distance from the source to the edge’s destination) gives an implementation of Dijkstra’s algorithm that is suitable for sparse graphs.
Program 21.1 is an alternative PFS implementation for sparse graphs that is slightly simpler than Program 20.7 and that directly matches the informal description of Dijkstra’s algorithm given at the beginning of this section. It differs from Program 20.7 in that it initializes the priority queue with all the vertices in the network and maintains the queue with the aid of a sentinel value for those vertices that are neither on the tree nor on the fringe (unseen vertices with sentinel values); in contrast, Program 20.7 keeps on the priority queue only those vertices that are reachable by a single edge from the tree. Keeping all the vertices on the queue simplifies the code but can incur a small performance penalty for some graphs (see Exercise 21.31).
The general results that we considered concerning the performance of priority-first search (PFS) in Chapter 20 give us specific information about the performance of these implementations of Dijkstra’s algorithm for sparse graphs (Program 21.1 and Program 20.7, suitably modified). For reference, we restate those results in the present context. Since the proofs do not depend on the priority function, they apply without modification. They are worst-case results that apply to both programs, although Program 20.7 may be more efficient for many classes of graphs because it maintains a smaller fringe.
**Property 21.4** For all networks and all priority functions, we can compute a spanning tree with PFS in time proportional to the time required for $V$ insert, $V$ delete the minimum, and $E$ decrease key operations in a priority queue of size at most $V$.
*Proof:* This fact is immediate from the priority-queue–based implementations in Program 20.7 or Program 21.1. It represents a conservative upper bound because the size of the priority queue is often much smaller than $V$, particularly for Program 20.7. ■
**Property 21.5** With a PFS implementation of Dijkstra’s algorithm that uses a heap for the priority-queue implementation, we can compute any SPT in time proportional to $E \lg V$.
CHAPTER TWENTY-ONE
Program 21.1 Dijkstra’s algorithm (priority-first search)
This class implements a single-source shortest-paths ADT with linear-
time preprocessing, private data that takes space proportional to \( V \), and constant-time member methods that give the length of the shortest path
and the final vertex on the path from the source to any given vertex.
The constructor is an implementation of Dijkstra’s algorithm that uses
a priority queue of vertices (in order of their distance from the source)
to compute an SPT. The priority-queue interface is the same one used in
Program 20.7 and implemented in Program 20.10.
The constructor is also a generalized graph search that implements
other PFS algorithms with other assignments to the priority \( P \) (see text).
The statement to reassign the weight of tree vertices to 0 is needed for a
general PFS implementation but not for Dijkstra’s algorithm, since the
priorities of the vertices added to the SPT are nondecreasing.
```java
public class GraphSPT
{
private double[] wt;
private Edge[] spt;
GraphSPT(Graph G, int s)
{
int V = G.V();
wt = new double[V]; spt = new Edge[V];
for (int v = 0; v < V; v++) wt[v] = maxWT;
doublePQi pQ = new doublePQi(V, wt);
for (int v = 0; v < V; v++) pQ.insert(v);
wt[s] = 0.0; pQ.lower(s);
while (!pQ.empty())
{
int v = pQ.getmin(); // wt[v] = 0.0;
if (v != s && spt[v] == null) return;
AdjList A = G.getAdjList(v);
for (Edge e = A.beg(); !A.end(); e = A.nxt())
{
int w = e.other(v);
double P = wt[v] + e.wt();
if (P < wt[w])
{
wt[w] = P; pQ.lower(w); spt[w] = e;
}
}
}
}
Edge pathR(int v) { return spt[v]; }
double dist(int v) { return wt[v]; }
}
```
Proof: This result is a direct consequence of Property 21.4.
Property 21.6 Given a graph with V vertices and E edges, let \( d \) denote the density \( E/V \). If \( d < 2 \), then the running time of Dijkstra's algorithm is proportional to \( V \lg V \). Otherwise, we can improve the worst-case running time by a factor of \( \lg(E/V) \) (which is linear if \( E \) is at least \( V^{1+\epsilon} \)) by using a \( \lceil E/V \rceil \)-ary heap for the priority queue.
Proof: This result directly mirrors Property 20.12 and the multiway-heap priority-queue implementation discussed directly thereafter.
Table 21.1 Priority-first search algorithms
These four classical graph-processing algorithms all can be implemented with PFS, a generalized priority-queue-based graph search that builds graph spanning trees one edge at a time. Details of search dynamics depend upon graph representation, priority-queue implementation, and PFS implementation; but the search trees generally characterize the various algorithms, as illustrated in the figures referenced in the fourth column.
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Priority</th>
<th>Result</th>
<th>Figure</th>
</tr>
</thead>
<tbody>
<tr>
<td>DFS</td>
<td>reverse preorder</td>
<td>recursion tree</td>
<td>18.13</td>
</tr>
<tr>
<td>BFS</td>
<td>preorder</td>
<td>SPT (edges)</td>
<td>18.24</td>
</tr>
<tr>
<td>Prim</td>
<td>edge weight</td>
<td>MST</td>
<td>20.8</td>
</tr>
<tr>
<td>Dijkstra</td>
<td>path weight</td>
<td>SPT</td>
<td>21.9</td>
</tr>
</tbody>
</table>
Table 21.1 summarizes pertinent information about the four major PFS algorithms that we have considered. They differ in only the priority function used, but this difference leads to spanning trees that are entirely different from one another in character (as required). For the example in the figures referred to in the table (and for many other graphs), the DFS tree is tall and thin, the BFS tree is short and fat, the SPT is like the BFS tree but neither quite as short nor quite as fat, and the MST is neither short and fat nor tall and thin.
We have also considered four different implementations of PFS. The first is the classical dense-graph implementation that encompasses Dijkstra’s algorithm and Prim’s MST algorithm (Program 20.6); the other three are sparse-graph implementations that differ in priority-queue contents:
- Fringe edges (Program 18.10)
- Fringe vertices (Program 20.7)
- All vertices (Program 21.1)
Of these, the first is primarily of pedagogical value, the second is the most refined of the three, and the third is perhaps the simplest. This framework already describes 16 different implementations of classical graph-search algorithms—when we factor in different priority-queue implementations, the possibilities multiply further. This proliferation
Table 21.2 Cost of implementations of Dijkstra’s algorithm
This table summarizes the cost (worst-case running time) of various implementations of Dijkstra’s algorithm. With appropriate priority-queue implementations, the algorithm runs in linear time (time proportional to $V^2$ for dense networks, $E$ for sparse networks), except for networks that are extremely sparse.
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Worst-Case Cost</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>Classical</td>
<td>$V^2$</td>
<td>Optimal for dense graphs</td>
</tr>
<tr>
<td>PFS, full heap</td>
<td>$E \log V$</td>
<td>Simplest implementation</td>
</tr>
<tr>
<td>PFS, fringe heap</td>
<td>$E \log V$</td>
<td>Conservative upper bound</td>
</tr>
<tr>
<td>PFS, $d$-heap</td>
<td>$E \log_d V$</td>
<td>Linear unless extremely sparse</td>
</tr>
</tbody>
</table>
As is true of MST algorithms, actual running times of shortest-paths algorithms are likely to be lower than these worst-case time bounds suggest, primarily because most edges do not necessitate decrease key operations. In practice, except for the sparsest of graphs, we regard the running time as being linear.
The name Dijkstra’s algorithm is commonly used to refer both to the abstract method of building an SPT by adding vertices in order of their distance from the source and to its implementation as the $V^2$ algorithm for the adjacency-matrix representation, because Dijkstra presented both in his 1959 paper (and also showed that the same approach could compute the MST). Performance improvements for sparse graphs are dependent on later improvements in ADT technology and priority-queue implementations that are not specific to the shortest-paths problem. Improved performance of Dijkstra’s algorithm is one of the most important applications of that technology (see reference section). As with MSTs, we use terminology such as the “PFS implementation of Dijkstra’s algorithm using $d$-heaps” to identify specific combinations.
|
{"Source-Url": "http://ptgmedia.pearsoncmg.com/images/0201361213/samplechapter/sedgewickch21.pdf", "len_cl100k_base": 13200, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 68372, "total-output-tokens": 14113, "length": "2e13", "weborganizer": {"__label__adult": 0.0005993843078613281, "__label__art_design": 0.0003097057342529297, "__label__crime_law": 0.0005860328674316406, "__label__education_jobs": 0.0011968612670898438, "__label__entertainment": 0.00011050701141357422, "__label__fashion_beauty": 0.0002906322479248047, "__label__finance_business": 0.00023305416107177737, "__label__food_dining": 0.0006389617919921875, "__label__games": 0.0022258758544921875, "__label__hardware": 0.0016870498657226562, "__label__health": 0.0009937286376953125, "__label__history": 0.0004954338073730469, "__label__home_hobbies": 0.000152587890625, "__label__industrial": 0.0005998611450195312, "__label__literature": 0.0005774497985839844, "__label__politics": 0.00037598609924316406, "__label__religion": 0.0007138252258300781, "__label__science_tech": 0.052337646484375, "__label__social_life": 0.00010985136032104492, "__label__software": 0.005176544189453125, "__label__software_dev": 0.927734375, "__label__sports_fitness": 0.0007619857788085938, "__label__transportation": 0.0018167495727539065, "__label__travel": 0.0004041194915771485}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54697, 0.06498]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54697, 0.51919]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54697, 0.91801]], "google_gemma-3-12b-it_contains_pii": [[0, 1660, false], [1660, 4560, null], [4560, 6563, null], [6563, 9145, null], [9145, 11437, null], [11437, 13955, null], [13955, 16961, null], [16961, 19414, null], [19414, 22078, null], [22078, 24442, null], [24442, 26861, null], [26861, 29525, null], [29525, 32736, null], [32736, 35740, null], [35740, 36230, null], [36230, 38761, null], [38761, 41038, null], [41038, 43325, null], [43325, 44750, null], [44750, 45796, null], [45796, 48108, null], [48108, 50036, null], [50036, 50643, null], [50643, 52735, null], [52735, 54697, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1660, true], [1660, 4560, null], [4560, 6563, null], [6563, 9145, null], [9145, 11437, null], [11437, 13955, null], [13955, 16961, null], [16961, 19414, null], [19414, 22078, null], [22078, 24442, null], [24442, 26861, null], [26861, 29525, null], [29525, 32736, null], [32736, 35740, null], [35740, 36230, null], [36230, 38761, null], [38761, 41038, null], [41038, 43325, null], [43325, 44750, null], [44750, 45796, null], [45796, 48108, null], [48108, 50036, null], [50036, 50643, null], [50643, 52735, null], [52735, 54697, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54697, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 54697, null]], "pdf_page_numbers": [[0, 1660, 1], [1660, 4560, 2], [4560, 6563, 3], [6563, 9145, 4], [9145, 11437, 5], [11437, 13955, 6], [13955, 16961, 7], [16961, 19414, 8], [19414, 22078, 9], [22078, 24442, 10], [24442, 26861, 11], [26861, 29525, 12], [29525, 32736, 13], [32736, 35740, 14], [35740, 36230, 15], [36230, 38761, 16], [38761, 41038, 17], [41038, 43325, 18], [43325, 44750, 19], [44750, 45796, 20], [45796, 48108, 21], [48108, 50036, 22], [50036, 50643, 23], [50643, 52735, 24], [52735, 54697, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54697, 0.14828]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
d69783f332bf523f3a1e8c1ecb77c3d56d93dc18
|
A Search-based Approach for Accurate Identification of Log Message Formats
Messaoudi, Salma; Panichella, Annibale; Bianculli, Domenico; Briand, Lionel; Sasnauskas, Raimondas
DOI
10.1145/3196321.3196340
Publication date
2018
Document Version
Accepted author manuscript
Published in
Proceedings of the 26th International Conference on Program Comprehension
Citation (APA)
Important note
To cite this publication, please use the final published version (if applicable). Please check the document version above.
Copyright
Other than for strictly personal use, it is not permitted to download, forward or distribute the text or part of it, without the consent of the author(s) and/or copyright holder(s), unless the work is under an open content license such as Creative Commons.
Takedown policy
Please contact us and provide details if you believe this document breaches copyrights. We will remove access to the work immediately and investigate your claim.
A Search-based Approach for Accurate Identification of Log Message Formats
Salma Messaoudi
University of Luxembourg
salma.messaoudi@uni.lu
Annibale Panichella
University of Luxembourg
a.panichella@tudelft.nl
Domenico Bianculli
University of Luxembourg
domenico.bianculli@uni.lu
Lionel Briand
University of Luxembourg
lionel.briand@uni.lu
Raimondas Sasnauskas
SES
raimondas.sasnauskas@ses.com
ABSTRACT
Many software engineering activities process the events contained in log files. However, before performing any processing activity, it is necessary to parse the entries in a log file, to retrieve the actual events recorded in the log. Each event is denoted by a log message, which is composed of a fixed part—called (event) template—that is the same for all occurrences of the same event type, and a variable part, which may vary with each event occurrence. The formats of log messages, in complex and evolving systems, have numerous variations, are typically not entirely known, and change on a frequent basis; therefore, they need to be identified automatically.
The log message format identification problem deals with the identification of the different templates used in the messages of a log. Any solution to this problem has to generate templates that meet two main goals: generating templates that are not too general, so as to distinguish different events, but also not too specific, so as not to consider different occurrences of the same event as following different templates; however, these goals are conflicting.
In this paper, we present the MoLFI approach, which recasts the log message identification problem as a multi-objective problem. MoLFI uses an evolutionary approach to solve this problem, by tailoring the NSGA-II algorithm to search the space of solutions for a Pareto optimal set of message templates. We have implemented MoLFI in a tool, which we have evaluated on six real-world datasets, containing log files with a number of entries ranging from 2K to 300K. The experiments results show that MoLFI extracts by far the highest number of correct log message templates, significantly outperforming two state-of-the-art approaches on all datasets.
CCS CONCEPTS
- Software and its engineering → Search-based software engineering;
- Software and its engineering → Log parsing, log analysis, log message format, NSGA-II
KEYWORDS
log parsing, log analysis, log message format, NSGA-II
1 INTRODUCTION
Logging is a programming practice that is used for gathering run-time information of a software system. Developers carry out logging by inserting into the source code of an application statements that specify which messages and which run-time information to print into the entries of log files.
Logging is a pervasive activity: recent studies \cite{35, 36} show that between 1/30 and 1/58 of the lines of code in large software systems correspond to logging statements. Furthermore, the importance of logging is also recognized by developers: a recent survey reported that 96% of a group of experienced developers from a leading software company “strongly agree/agree that logging statements are important in system development and maintenance” \cite{13}. Indeed, the information contained in log files can be used for a variety of purposes, such as process mining \cite{15, 30}, anomaly detection \cite{4, 12, 14}, behavioral differencing \cite{14}, fault localization \cite{33}, invariant inference \cite{5}, performance diagnosis \cite{21}, and offline trace checking \cite{3}.
All these activities carry out some sort of log analysis, which processes the events corresponding to the entries contained in the log files. Before performing any processing activity, it is necessary to parse the log entries, to retrieve the actual events recorded in the log. A log entry typically includes a timestamp (which records the time at which the logged event occurred) and the actual log message (containing run-time information associated with the logged event).
An example of log entry is the following:
\texttt{20050605-06.45.36 send RST CORE to addr 0x0000df30}
The log message part of a log entry (e.g., the block “send RST CORE to addr 0x0000df30” in the above example) is a block of free-form text, which poses a challenge to parsing because it does not have a structured format. More specifically, a log message is
composed of two parts: 1) a fixed part, also called \textit{(event) template}\textsuperscript{1}, which is the same for all occurrences of the same event type; 2) a variable part, which may vary with each event occurrence, containing tokens filled at run time with dynamic information. In the above example, the template contains the fixed words "send", "to", "addr", while "RST", "CORE" and "0x0000df30" are variable tokens. A template is represented as "send \* \* to address \*\*", where the asterisks indicate placeholders for tokens of the variable part.
The lack of a structured format for log messages leads to the definition of the \textit{log message format identification}\textsuperscript{2} problem: given a log file, we want to identify the different templates used in the log messages contained in the log in order to enable automated data extraction and analysis on a large scale.
Solving this problem for complex and evolving systems requires to tackle several challenging issues. First, in these systems log message formats are numerous, changing on a frequent basis (e.g., in Google systems hundreds of new logging statements are added every month \cite{34}), and are typically not entirely known by those who need to analyze log files.
Second, these systems can produce around 120–200 million log entries per hour \cite{20}. Therefore, log message formats need to be identified automatically and in a scalable way.
Such requirements rule out the use of regular expressions for extracting the templates, since it would still require a manual effort, to create and update regular expressions based on the logging statements contained in the source code of the application. Manual creation and update of regular expressions would be a tedious and error-prone task, given the number of logging statements and the fast pace of their updates \cite{34}. Another strategy would be to statically analyze the application source code, locate logging statements, and extract the templates from the print operations. However, the definition of the static analysis would be tedious and require an extensive knowledge of logging techniques, since logging statements can take different forms in different programming languages and logging frameworks. Furthermore, both strategies outlined above would require to access the source code, which is not always possible, especially in the case of complex software systems that rely on 3rd-party components.
To overcome these limitations, some approaches \cite{11, 12, 17, 19} adopt a black-box strategy that relies on a combination of clustering and heuristic rules to group words into templates, based on their similarity and the frequency within log message blocks. However, our experience on real-world logs shows that these approaches yield low accuracy, as demonstrated by the empirical results reported in this paper. Furthermore, their parameters (e.g., text similarity) need to be fine-tuned for each log to analyze, usually following a trial-and-error process; these requirements make such approaches neither scalable nor effective.
Independently from the specific strategy adopted, any technique for extracting message templates from logs ought to meet two objectives: the generated templates should 1) match as many log messages as possible (i.e., achieve high \textit{frequency} in matching log messages); 2) correspond to the largest extent possible to a particular type of event (i.e., achieve high \textit{specificity}). However, these two objectives—high frequency and high specificity—are conflicting. A template achieving high frequency will contain many tokens in the variable part (to match many log messages), but will be too generic (i.e., it will match messages corresponding to different events); on the other hand, a template achieving high specificity will have a few or no tokens in the variable part (to be able to distinguish between different event types), but it will match only few messages.
Given the presence of conflicting objectives and the limitations of existing solutions \cite{11, 12, 17, 19}, in this paper we propose to recast the \textit{log message format identification problem as a multi-objective optimization problem}, where \textit{frequency} and \textit{specificity} are explicitly considered as two competing objectives to optimize simultaneously. Our approach, named MoLFI (Multi-objective \textit{Log message Format Identification}), leverages an evolutionary approach to solve this problem. MoLFI applies the Non-dominated Sorting Genetic Algorithm II (NSGA-II \cite{10}) on a given log file to search the space of solutions for a Pareto optimal set of message templates. The two main strong points of MoLFI are: 1) it does not require access to the source code of the application producing the log(s) being analyzed, since it is a black-box technique that works only on the log files; 2) different from existing approaches, it does not require any parameter tuning before its execution.
We implemented MoLFI in a prototype tool. We evaluated the accuracy and efficiency of MoLFI on one proprietary and five publicly-available real-world datasets, containing log files with a number of entries ranging from 2K to 300K; we also compared our approach with iPLoM \cite{19} and Drain \cite{17}, two state-of-the-art approaches. The results show that MoLFI achieves by far the highest precision and recall, outperforming the other approaches with substantial improvements in both precision (ranging between +14 pp and +86 pp, with \textit{pp}=percentage points) and recall (ranging between +25 pp and +75 pp) on all datasets, while keeping a running time of less than 126 s when analyzing the largest dataset. A higher accuracy in the identification of log message formats usually has practical implications, in terms of effectiveness, in the log analysis tasks that rely on log message format identification. For example, in the context of anomaly detection—the original motivation for existing work \cite{12, 17}—log analysis is effective only when the parsing accuracy is high enough \cite{16}.
To summarize, the main contributions of this paper are: 1) the formulation of the log message format identification problem as a \textit{multi-objective optimization problem}; 2) the MoLFI approach for the solution of this problem, based on the NSGA-II algorithm; 3) a publicly-available implementation of MoLFI\textsuperscript{3}; 4) the empirical evaluation, in terms of accuracy and efficiency, of the implementation of MoLFI and its comparison with two state-of-the-art approaches.
The rest of the paper is organized as follows. Section 2 gives an overview of multi-objective optimization and genetic algorithms. Section 3 illustrates the problem of log message format identification with an example. Section 4 describes how MoLFI tailors NSGA-II to solve the log message identification problem. Section 5 reports on the evaluation of MoLFI. Section 6 discusses practical applications. Section 7 concludes the paper.
---
\textsuperscript{1}Additional names used in the literature for denoting the fixed part of a log message are "line pattern", "log key", and "message signature".
\textsuperscript{2}This problem is often called "log parsing" in the literature; we believe "log message format identification" is a more specific term, since "log parsing" includes also parsing more structured elements like timestamps and log verbosity levels.
\textsuperscript{3}The evaluation artifacts are available from the following links: [tool GitHub link], [log files GitHub link].
A multi-objective problem is an optimization problem that involves multiple objective functions. Let \( S \) be the space (set) of all feasible solutions and \( F \) be a vector-valued objective function \( F: S \rightarrow \mathbb{R}^k \) composed of \( k \) real-valued objective functions \( F_i = (f_1, \ldots, f_k) \), where \( f_j: S \rightarrow \mathbb{R} \) for \( j = 1, \ldots, k \); a multi-objective optimization problem is defined as \( \max(f_1(x), \ldots, f_k(x)) \) subject to \( X \subseteq S \). In other words, the problem consists in finding a set of feasible solutions that maximize the objective functions in \( F \).
The goodness of a solution in a multi-objective optimization problem is defined in terms of the dominance relation and Pareto optimality. More precisely, a solution \( X \) is said to dominate another solution \( Y \), denoted as \( X < Y \), if and only if for all indices \( i \in \{1, \ldots, k\} \), \( f_i(X) \geq f_i(Y) \) and \( f_j(X) > f_j(Y) \) for at least one index \( j \in \{1, \ldots, k\} \). A solution \( X \) is called Pareto optimal if there does not exist another solution in the search space that dominates it. The set of all Pareto optimal solutions of a given problem is called the Pareto front. The Pareto front can be used to decide which solution to select, according to the preferences of a decision maker.
2.1 Multi-objective optimization problems
A multi-objective problem is an optimization problem that involves multiple objective functions.
2.2 NSGA-II
The Non-dominated Sorting Genetic Algorithm II (NSGA-II) [10] is a well-known and efficient technique to solve multi-objective problems. NSGA-II is a multi-objective genetic algorithm (GA) that provides well-distributed Pareto fronts and good performance when dealing with up to three objectives [10, 18]; it has been widely used in software engineering to solve problems involving multiple objectives [32] and with chromosome representations that require complex data structures (as in our case, see Section 4.2.2).
In NSGA-II (and GAs in general), the candidate solutions to a problem are called chromosomes. The encoding of a chromosome depends on the type of problem to solve. GAs refine and evolve randomly-generated chromosomes through subsequent iterations (called generations), mimicking selection and reproduction mechanisms in nature.
NSGA-II starts with a pool of randomly generated chromosomes (i.e., population). In each generation, the algorithm evaluates the goodness of a chromosome in the current population based on the objectives to optimize. Chromosomes dominating other chromosomes are considered as fitter solutions and therefore have higher chances to be selected for reproduction (i.e., for generating new chromosomes). NSGA-II selects the best solutions (parents) within the current population by using binary tournament selection [10]. Reproduction is performed by combining pairs of parents to form new chromosomes (called offsprings) using two operators: crossover and mutation. The crossover operator generates two offsprings by exchanging some chromosome parts between the two parents. The mutation operator applies small changes to each offspring to get a more diverse solution. Notice that the implementation of mutation and crossover depends on the problem to solve. The new population for the next generation is formed by selecting the fittest individuals among parents and offsprings according to the dominance relation (non-dominated ranking) and crowding distance (to promote diversity) [10].
3 THE PROBLEM OF LOG MESSAGE FORMAT IDENTIFICATION
We illustrate the problem of log message format identification through the example in Figure 1, which provides a simplified excerpt of log entries extracted from an open dataset of logs collected from a BlueGene/L supercomputer system at Lawrence Livermore National Labs.
One can see that the log messages of the first three entries in the example log correspond to the same event type. This event type could be matched with the template \( \langle \text{INFO generating core } * \rangle \), where the variable part contains one token (indicated with the placeholder \( * \)). Similarly, entries of log messages at lines 4–5 could be matched with the template \( \langle \text{FATAL instruction address } * \rangle \).
However, one could define other templates for the log messages considered above. For example, another template that could match the messages at lines 4–5 would be \( \langle \text{FATAL } \times \times \rangle \), with three tokens in the variable part. Notice that this template is more general than the previous one, since it matches two different types of event (one type associated with messages at lines 4–5, and another type associated with the message at line 13). Another possible template would be \( \langle \text{FATAL } \times \text{ address } 0x0000df30 \rangle \), which is too specific because it matches only the log message at line 4 and misses the message at line 5, even if it is of the same event type.
These examples show that two distinct objectives must be met when identifying message templates:
- maximizing the number of log messages matched by each template, i.e., maximizing the frequency of message matches;
- maximizing the specificity of a template to a particular type of event.
These two goals are conflicting: to maximize frequency, templates should contain many tokens in the variable part (to match many log messages); however, such templates would have a low specificity (i.e., they would be too generic), matching messages corresponding to different events. On the other hand, to maximize specificity, templates should contain only a few or no tokens in the variable part (to be able to distinguish between different event types); however, they would match only few messages.
Any method proposed to solve the log message format identification problem has to deal with the trade-off between these two conflicting goals.
4 LOG MESSAGE FORMAT IDENTIFICATION AS A MULTI-OBJECTIVE OPTIMIZATION PROBLEM
In this section, we illustrate how log message format identification can be recast as a multi-objective optimization problem and present our approach MoLFI for the solution of this problem, based on NSGA-II.
4.1 Problem Formulation
As discussed in section 3, we consider frequency and specificity as objective functions to optimize simultaneously. The multi-objective optimization formulation of the log message format identification problem entails that we find, from the set $S$ of all feasible solutions, a set of templates $X = \{\tau_1, \ldots, \tau_n\}, X \subseteq S$, such that each template $\tau_i \in X$ with $i = 1, \ldots, n$, matches as many log messages as possible (high frequency) and contains as few variable tokens as possible (high specificity). More formally, the objective functions are the frequency: $\text{Freq}(X) = \frac{\sum_{i=1}^{n} \text{match}(\tau_i, M)}{n \times |M|}$, and the specificity: $\text{Spec}(X) = \sum_{i=1}^{n} \frac{\text{fixed}(\tau_i)}{n \times \text{tok}^i(\tau_i)}$ where $n$ is the number of templates in $X$, $M$ is a list of log messages, match$(\tau, M)$ denotes the list of log messages in $M$ that match a template $\tau$, fixed$(\tau)$ denotes the number of tokens in the fixed part of $\tau$, and tok$(\tau)$ denotes the total number of tokens in $\tau$.
When determining a solution to this problem, there are two important aspects to assess. First, the templates contained in a (Pareto optimal) solution may not match all the log messages in $M$. For example, the solution $X = \{(\text{FATAL} \ instruction \ address \ 0x00000df30), (\text{INFO} \ generating \ core \ 135)\}$ is Pareto optimal for the log messages in Figure 1, since it has the highest possible specificity ($\text{Spec}(X) = 1$). However, the templates in $X$ match only two out of the 15 log messages ($\text{Freq}(X) = \frac{2}{15}$). Second, different templates $\tau_1$ and $\tau_2$ in the same solution $X$ may match the same log messages, i.e., $\text{match}(\tau_1, M) \cap \text{match}(\tau_2, M) \neq \emptyset$. To avoid this type of solutions, we introduce two additional constraints to the optimization problem to determine the set of feasible solutions $S$.
More specifically, a solution $X = \{\tau_1, \ldots, \tau_n\} \subseteq S$ is feasible if it satisfies the following constraints:
\begin{equation}
\bigcup_{i=1}^{n} \text{match}(\tau_i, M) = M
\end{equation}
\begin{equation}
\text{match}(\tau_i, M) \cap \text{match}(\tau_j, M) = \emptyset \text{ for all } \tau_i, \tau_j \in X, \tau_i \neq \tau_j
\end{equation}
4.2 MoLFI
To solve the multi-objective optimization formulation of the log message format identification problem, we introduce our approach, named MoLFI, which tailors the standard NSGA-II to our context. In particular, we detail the encoding schema and the genetic operators (i.e., crossover and mutation) we use, the pre- and post-processing procedures we apply, and the procedure we follow to select one solution from the Pareto front.
4.2.1 Pre-processing. Before starting the search process, we first pre-process the log messages to improve the accuracy of the process; we follow the guidelines by He et al. [16, 17]. We first use regular expressions to identify trivial variable parts within the log messages based on domain knowledge, e.g., numbers, memory and IP addresses. Strings in the log messages matching these regular expressions are replaced with a special variable token $\#\text{spec}$ that cannot be mutated in the later stages of the search. To reduce the computation cost of the template identification process, we filter out duplicated log messages, reducing the number of messages to consider for generating templates. The messages are then tokenized, using blanks, parentheses and punctuation characters as word-separators. Finally, messages are grouped into buckets, with each bucket containing messages that have the same number of tokens; we denote with $M_L$ the bucket/group containing messages with exactly $L$ tokens.
4.2.2 Encoding Schema. In our context, a solution is a set of templates $X = \{\tau_1, \ldots, \tau_n\}$ where each template $\tau_i$ corresponds to a group of pre-processed log messages having the same length and sharing all fixed tokens in $\tau_i$. Therefore, each template $\tau_i$ is a list of tokens, where each token can be either variable (denoted by the symbols $\ast$ or $\#\text{spec}$) or fixed (i.e., the tokens identified during the pre-processing step).
Although very intuitive, this encoding schema is not efficient for computing the log messages being matched by each template. Indeed, this procedure requires comparing every template against all log messages even if most of them have a number of tokens not compatible with what is prescribed by the template. To speed-up the matching process, we design a two-level encoding schema: a chromosome $C$ is a set of groups $C = \{G_1, \ldots, G_{\text{max}}\}$, where each group $G_L = \{\tau_1, \ldots, \tau_k\}$ is a set of templates having the same number of tokens $L$. This encoding schema guarantees that the matching procedure is applied only for messages and templates of the same length.
Figure 2 shows an example of chromosome for the log messages in Figure 1 based on our encoding schema. It has four groups of templates with lengths 4, 5, 6, and 12; it also satisfies the constraints for feasible solutions.
4.2.3 Initial Population. MoLFI uses the algorithm InitialPopulation (Algorithm 1) for generating the initial population. The algorithm takes as input a set of pre-processed log messages $M$, the population size $N$; it returns a population $P$. Each chromosome is randomly generated inside the loop at lines 4–16: after initializing the chromosome $C$ (line 4), it is iteratively filled with groups of templates (lines 5–15), one group of templates $G_L$ for each group of pre-processed log messages $M_L \in M$ with the same length $L$.\...
Figure 2: An example of chromosome for the log messages in figure 1.
Algorithm 1: InitialPopulation
\begin{itemize}
\item Input: Set of pre-processed log messages \( M \)
\item Population size \( N \)
\item Result: Initial population \( P \)
\end{itemize}
\begin{algorithmic}
1 \caption{Algorithm 1: InitialPopulation}
2 \begin{algorithmic}[1]
3 \State \( P \leftarrow \emptyset \)
4 \While {\( |P| < N \)}
5 \State \( C \leftarrow \emptyset \)
6 \For {each group \( M \in M \)}
7 \State \( G_L \leftarrow \) create an empty group for templates with length \( L \)
8 \State \( \text{unmatched} \leftarrow M_L \)
9 \While {\( |\text{unmatched}| > 0 \)}
10 \State \( \text{log message} \leftarrow \) randomly select one message from \( \text{unmatched} \)
11 \State \( \text{index} \leftarrow \) random integer \( \in [1; L] \)
12 \State \( \text{token} \leftarrow \text{log message}[\text{index}] \)
13 \State \( G_L \leftarrow G_L \cup \{\text{token}\} \)
14 \State \( \text{unmatched} \leftarrow \text{unmatched} \setminus \text{match}(\text{token}, M_L) \)
15 \State \( C \leftarrow C \cup \{G_L\} \)
16 \State \( P \leftarrow P \cup \{C\} \)
17 \EndWhile
18 \EndFor
19 \State \( \text{match}(\text{token}, M_L) \)
20 \EndWhile
21 \EndAlgorithmic
For each group of messages \( M \), the algorithm creates a corresponding group of templates \( G_L \) (line 6). Initially, the group \( G_L \) is empty and therefore it does not match any log message. The algorithm keeps track of the unmatched messages in the set \( \text{unmatched} \), initialized with \( M \) (line 7). Then, a log message is randomly selected from \( \text{unmatched} \) (line 9) and used to generate a template \( \tau \) (lines 10–12). Template \( \tau \) is a copy of the original log message with the exception of the single token (randomly selected at line 11), which is replaced with the variable token "\#spec\#" (line 12). The newly generated template is then added to the group \( G_L \) and used to update the set of unmatched log messages (line 14). The loop at lines 8–14 terminates when the templates composing the group \( G_L \) match all log messages in \( M \) (i.e., when the set \( \text{unmatched} \) is empty). Since this condition has to be satisfied for each group of messages \( M \), the chromosome \( C \) is a feasible solution. Therefore, Algorithm 1 guarantees that all chromosomes in the initial population satisfy our constraints.
4.2.4 Crossover. We implemented the uniform crossover, which is one of the most popular crossover operators [26, 27]. It generates two offsprings by shuffling the different characteristics (groups of templates in our case) of the parents. Let \( A = \{A_1, \ldots, A_{\max} \} \) and \( B = \{B_1, \ldots, B_{\max} \} \) be the two selected parents where each pair of groups \( A_L \in A \) and \( B_L \in B \) matches the same pre-processed log messages \( M_L \in M \) with length \( L \). The uniform crossover first generates a random binary vector \( \beta \) (called the crossover mask) with a length equal to the number of groups in \( A \) and \( B \). Then, the two offsprings \( O_1 \) and \( O_2 \) are obtained as follows: when the binary element in \( \beta \) for the group with length \( L \) is zero, offspring \( O_1 \) inherits group \( A_L \) while \( O_2 \) inherits group \( B_L \); otherwise, \( O_1 \) inherits group \( B_L \) while \( O_2 \) inherits group \( A_L \).
Notice that this crossover operator swaps groups of templates between the two parents without changing the set of templates composing each group. Therefore, it generates offsprings that are feasible solutions: each group \( A_L \in A \) and \( B_L \in B \) covers all pre-processed log messages \( M_L \in M \) and they do not contain overlapping templates (i.e., templates that match the same log messages). Since \( A \) and \( B \) are not modified by our crossover, the properties above are preserved independently from which offspring inherits the two groups.
4.2.5 Mutation. After crossover, offsprings are mutated using the mutation operator to randomly change the generated templates. Given a chromosome to mutate \( C = \{G_1, \ldots, G_{\max}\} \), each group \( G_L \) is mutated with probability \( \beta \). A group \( G_L \) is mutated by changing one of its templates; the template is mutated by adding or removing variable tokens. In particular, let \( \tau = \{\text{token}_1, \ldots, \text{token}_n\} \) be the template to mutate; each token is mutated by adding or removing variable tokens. In particular, let \( \tau = \{\text{token}_1, \ldots, \text{token}_n\} \) be the template to mutate; each token is mutated with probability \( \frac{1}{\beta} \). The token \( \text{token}_n \) is mutated as follows: if it is a fixed one, it is replaced by the variable token "\#spec\#"; if it is a variable token, it is replaced by a fixed token, which is randomly selected among all fixed tokens in position \( i \) of the log messages that match \( \tau \); if it is the special token "\#spec\#" added during the pre-processing, it is not mutated. Therefore, our mutation operator either increases or reduces the number of variable tokens in \( \tau \). In the former scenario, it likely increases the frequency of the original template \( \tau \); in the latter case it increases its specificity.
Different from the crossover, the mutation operator changes the templates within the chromosome’s groups. Therefore, it does not guarantee that the mutated chromosomes satisfy the feasible solution constraints. For this reason, we developed a correction operator that (i) removes overlapping templates (i.e., two or more templates matching the same pre-processed log messages), and (ii) adds randomly generated templates if a mutated group \( G_L \) does not match all messages in \( M_L \). Random templates are added following the same procedure used at lines 7–14 of Algorithm 1. Notice that the correction operator is applied after the mutation operator and it is applied only to the mutated chromosome’s groups.
4.2.6 Post-processing. At the end of the search, NSGA-II returns a set of feasible solutions that are Pareto optimal, i.e., representing optimal trade-off between frequency and specificity. Due to the random nature of NSGA-II, Pareto optimal solutions may contain log message templates with spurious variable tokens, i.e., variable tokens that have been inserted by mutation across the generations.
but that do not contribute to match more pre-processed log messages. For this reason, MoLFI post-processes the templates in each Pareto optimal chromosome with a greedy procedure, which iteratively removes all variable tokens that do not affect the frequency scores. In other words, given a template \( \tau \) to post-process, the procedure temporarily removes one of its variable tokens and checks whether the set of log messages matched by \( \tau \) remains unchanged. If the applied change affects the set of matched log messages, the change is reverted; otherwise it is maintained. The post-processing procedure ends once all variable tokens in \( \tau \) have been verified.
4.2.7 Choosing a Pareto optimal solution. If the number of solutions in the generated Pareto front is large it may be difficult to choose one solution (best trade-off) among the different alternatives. For this reason, researchers proposed various guidelines to find and suggest points of interest in the Pareto front, such as the knee points [6], mid points [22], or the best point (corner) for each objective [23].
According to Branke et al. [6], the most interesting Pareto optimal solution is the knee point because any other solution in the front leading to a small improvement in one of the two objectives (e.g., \( \text{Freq} \)) would lead to a large deterioration in the other objective (e.g., \( \text{Spec} \)). To provide a graphical interpretation of the knee point, Figure 3 depicts an example of Pareto front for the log message format identification problem. The Pareto front is composed of seven non-dominated solutions: points \( A \) and \( B \) are the corner solutions of the front while the other solutions represent intermediate trade-offs. Point \( C \) can be considered as a knee point since any marginal improvement to \( \text{Freq} \) will correspond to a large deterioration in \( \text{Spec} \), and vice versa. Therefore, the knee point leads to the lowest loss in both objectives.
To identify the knee point, we measure the distance of each Pareto optimal solution from the ideal point [26]. The coordinates of the ideal point correspond to the maximum objective values among all solutions in the Pareto front, considering each objective function separately. For example, for the Pareto front in Figure 3, the ideal point has the coordinates \((F_{\text{max}}, S_{\text{max}})\), where \( F_{\text{max}} = 0.85 \) (from point \( A \)) and \( S_{\text{max}} = 0.9 \) (from point \( B \)). More formally, given a Pareto front \( P = \{C_1, \ldots , C_p\} \), the knee point \( C_k \in P \) is the solution minimizing the distance \( \sqrt{(F_{\text{max}} - \text{Freq}(C_i))^2 + (S_{\text{max}} - \text{Spec}(C_i))^2} \), for all \( C_i \in P \).
5 EVALUATION
We have implemented the MoLFI approach as a Python program. In this section we report on the evaluation of the effectiveness of the MoLFI implementation in identifying accurate log message formats.
First, we want to assess the performance of MoLFI in comparison with state-of-the-art techniques, in terms of accuracy and efficiency. Second, there are various factors that may influence the effectiveness of MoLFI, such as (1) the number of templates to identify, (2) the population size in NSGA-II; (3) the removal of duplicate messages from the log file to analyze, performed as part of the pre-processing step; we want to understand whether and to what extent these factors affect the effectiveness of MoLFI. Last, in MoLFI we choose the knee point as most valuable solution from the Pareto front, following the general guidelines by Branke et al. [6]. However, different trade-offs in the Pareto front may provide equal or better results in our context; hence, we want to assess whether the knee point is the best Pareto optimal solution for the log message format identification problem.
Summing up, we investigate the following research questions:
RQ1: How does MoLFI perform when compared to state-of-the-art techniques for the log message format identification problem?
RQ2: Which factors impact the effectiveness of MoLFI?
RQ3: Is the knee point the best solution to choose from the Pareto front?
5.1 Benchmark
To evaluate MoLFI, we used a benchmark composed of six different datasets: five datasets are publicly available and have been used in previous work on the log message format identification problem [16, 17], while the last one is industrial and proprietary.
The five public datasets are HDFS, BGL, HPC, Zookeeper (shortened to “ZK”) and PRX (shortened to “PRX”). HDFS consists of logs from the Hadoop file system that were collected from a 203-node cluster on the Amazon EC2 platform [16]. BGL contains logs generated from the Blue Gene/L (BGL) supercomputer, collected by the Lawrence Livermore National Labs (LLNL) [16]. The logs contained in the HPC dataset were collected from a high-performance cluster with 49 nodes and thousands of cores [16]. The logs in ZK were collected by He et al. [16, 17] from a 32-node cluster. PRX consists of logs generated by a standalone software [16].
The proprietary dataset (named \( PR \)) has been provided by one of our industrial partners, active in the aerospace industry; it contains logs produced by a complex system with more than 20 distributed processes.
All datasets contain log files of various size. For the HDFS, BGL, HPC, ZK, and PRX datasets, we used the same samples of 2K log entries used in previous studies [16, 17]. In addition, we also selected a sample of 100K log entries from BGL and a sample of 60K log entries from HDFS. As for the proprietary dataset, we considered three different log files, generated by three different sub-systems, containing 2K, 20K, and 300K log entries.
Ground truth definition. In the case of the log message format identification problem, the ground truth is represented by the actual log message templates. For our evaluation, we established the ground truth as follows.
For the log files with 2K log entries of the public datasets, we used the ground truth defined by He et al. [16, 17] and publicly available from their replication package. In the case of the BGL and HPC datasets, the original set of correct templates contains some mistakes, e.g., templates with unbalanced parentheses and missing punctuation marks. Therefore, we manually validated and fixed them before performing our evaluation.
No ground truth is available for the proprietary logs, the 100K log file from BGL, and the 60K log file from HDF5. Therefore, we had to manually establish the ground truth. Two validators independently inspected each log file and extracted the corresponding templates. Then, the two sets of templates independently extracted by the two validators were merged into a single ground truth set, by including only the templates extracted by both validators. Templates identified by only one of the two validators were discussed and further added to the ground truth only upon agreement between the validators. At the end of the validation process, we also verified that no log message in our datasets could be matched by more than one single template in the ground truth. In total, 486K log messages were manually inspected to establish the ground truth. The number of log message templates in each log file ranges from 13 (PRX) to 394 (PR with 20K messages).
5.2 Effectiveness of MoLFI
To answer RQ1, we assess the performance of MoLFI, in terms of accuracy and efficiency, in comparison with DRAIN [17] and IPLoM [19], which are the two most recent and effective tools for the log message format identification problem [16, 17]. We use the implementation of DRAIN available in [17] and the one of IPLoM available in [16].
5.2.1 Methodology. The NSGA-II algorithm used in MoLFI requires to set four parameters: crossover probability, mutation probability, population size, and stopping condition. To set these parameters, we followed the guidelines proposed in the literature. More specifically, Arcuri and Fraser [1] and Sayyad et al. [25] have empirically demonstrated that the benefits of fine-tuning the parameters of search-based algorithms often do not compensate for the required overhead; both studies recommend to use the default parameters values, since they provide competitive results.
We set the NSGA-II parameters as follows:
- crossover probability $p_c = 0.70$, since the recommended values are within the interval $0.45 \leq p_c \leq 0.95$ [7, 8];
- the mutation probability $p_m$ is proportional to the length of the chromosome (see section 4.2.5), as recommended in the related literature [10];
- the population size is set to 20 individuals; according to our preliminary experiments (see section 5.3.2), this small value corresponds to the best compromise between accuracy and efficiency;
- the stopping condition is set to 200 generations [10].
As selection operator, we used binary tournament selection [10], which is based on dominance and crowding distance.
For DRAIN, in the case of the public datasets, we used the same parameters values used in [17]; in the case of our proprietary dataset, we used the default parameter values: depth $= 4$, similarity $= 0.5$. We also pre-processed the logs, as suggested in [17], to identify trivial variable parts within the log messages based on domain knowledge.
For IPLoM, we used the default parameter values used in [19]: file support threshold $= 0$, partition support threshold $= 0$, upper bound $= 0.9$, lower bound $= 0.25$, and cluster goodness threshold $= 0.35$.
We ran the three tools on each log file in our benchmark and collected the generated log message templates. We measured the accuracy of each tool by comparing the set of generated templates with the ground truth. Furthermore, we measured the wall-clock time for executing the complete program (including pre- and post-processing tasks for MoLFI). To measure the accuracy, we used the metrics used in previous studies [16, 17], i.e.,\[ Precision = \frac{|CRT\cap GEN|}{|CRT|}, \]
\[ Recall = \frac{|CRT\cap GEN|}{|GEN|}, \]
and F-measure $= 2 \times \frac{Precision \times Recall}{Precision + Recall}$, where \(|GEN|\) denotes the set of templates generated by a tool and \(|CRT|\) denotes the set of templates generated by a tool which are correct, i.e., conform to the ground truth.
To account for the random nature of NSGA-II, we executed MoLFI 50 times on each log and computed the median and standard deviation of the effectiveness metrics; DRAIN and IPLoM were executed only once due to their deterministic nature. However, DRAIN generated duplicated templates, i.e., multiple templates having exactly the same fixed and variable tokens. To avoid any bias due to duplicated templates, we detected and removed them before computing the various effectiveness metrics.
Furthermore, we used the Welch’s t-test to verify whether the F-measure scores achieved by MoLFI are significantly higher than those achieved by the alternative tools. The Welch’s t-test is a test for statistical significance suitable for distributions with different variance. In our case, the variance for DRAIN and IPLoM is zero as they are deterministic; MoLFI may return a non-zero variance due to NSGA-II. For this test, we consider a level of significance $\alpha=0.05$. Other than simply testing the statistical significance, we estimated the magnitude of the differences (effect size) using the Vargha-Delaney ($\tilde{A}_{12}$) statistic [31]. $\tilde{A}_{12}$ takes values in $[0;1]$, and $\tilde{A}_{12} > 0.50$ values indicate that MoLFI outperforms the alternative tool while for $\tilde{A}_{12} < 0.50$ the contrary is true. $\tilde{A}_{12} = 0.50$ if the two tools are equivalent.
5.2.2 Results. Table 1 shows the results of the three tools, grouped by dataset and log file size. Column "#T" indicates the number of templates in a file; column "NTT" indicates the percentage of templates in a file; column "PRE" indicates the percentage of templates generated by a tool; column "REC" indicates the percentage of templates generated by a tool and conform to the ground truth. Furthermore, we estimated the magnitude of the differences (effect size) using the Vargha-Delaney ($\tilde{A}_{12}$) statistic [31]. $\tilde{A}_{12}$ takes values in $[0;1]$, and $\tilde{A}_{12} > 0.50$ values indicate that MoLFI outperforms the alternative tool while for $\tilde{A}_{12} < 0.50$ the contrary is true. $\tilde{A}_{12} = 0.50$ if the two tools are equivalent.
According to our results, MoLFI obtains, on all the log files in the benchmark, a better F-measure than both DRAIN and IPLoM. We compared the effectiveness of our approach with the two state-of-the-art tools and we present the differences in percentage points (pp). The difference between MoLFI and DRAIN in terms of F-measure ranges between $+13$ pp and $+36$ pp. The values for the difference are always statistically significant according to the Welch’s t-test (all $p$-values are lower than 0.01) and the effect size is always large (i.e., $\tilde{A}_{12} \approx 1$). This difference is due both to better precision and to better recall. We also remark that DRAIN crashed...
the templates produced by DRAIN are non-dominated neither by plates having both better frequency and better specificity. Instead, generated by DRAIN and IPLoM. The knee point dominates the corresponding to the frequency and specificity values of the templates knee point (red point) and two further points (in black color) corre-
on the 300K log from the proprietary dataset, without yielding any message template.
The difference between MoLFI and IPLoM in terms of F-measure ranges between $+20 \text{ pp}$ and $+81 \text{ pp}$. For all logs in our study, the differences are statistically significant ($p$-values are always lower than 0.01) with a large effect size ($A_{12} \approx 1$). Also in this case, the better F-measure is ascribable to the substantial improvements in both precision (ranging between $+14 \text{ pp}$ and $+86 \text{ pp}$) and recall (ranging between $+25 \text{ pp}$ and $+75 \text{ pp}$). An interesting case is represented by the 300K log from the proprietary dataset: MoLFI generates very accurate templates achieving an F-measure of 0.91 while IPLoM obtains a very low F-measure of 0.1.
Figure 4 shows an example of the Pareto front generated by MoLFI for the dataset HPC on one single run. It also displays the knee point (red point) and two further points (in black color) corre-
sponding to the frequency and specificity values of the templates generated by DRAIN and IPLoM. The knee point dominates the templates produced by IPLoM, meaning that MoLFI generates templates having both better frequency and better specificity. Instead, the templates produced by DRAIN are non-dominated neither by the knee point nor by the other Pareto optimal solutions. Indeed, their objective scores are located in one of the corners of the Pareto front, meaning that their specificity is very high (few variable tokens) but their frequency is very low. Similar results are obtained also for the other logs in the benchmark. To sum up, both IPLoM and DRAIN are not able to provide optimal compromises between the two objective functions.
In terms of efficiency, MoLFI is the slowest technique; this can be explained because of the usage of NSGA-II, which is an iterative algorithm. The fastest technique is IPLoM, which, however, is also the one with the lowest F-measure values. DRAIN is faster than MoLFI in all the cases with the only exception of the 100K log from the BGL dataset: for this file DRAIN takes 32.89 s while MoLFI takes only 10.91 s. Although MoLFI takes longer to converge than state-of-the-art tools, the increment of the running time has no practical implications since it took less than 126 s when analyzing the largest dataset.
### 5.3 Factors influencing the effectiveness of MoLFI
To answer RQ2, we investigate the effect of the following three factors on the effectiveness of MoLFI: (1) the number of templates to identify in a log file, (2) the population size in NSGA-II; (3) the removal of duplicate messages from the log file to analyze, performed as part of the pre-processing step. In the following, we illustrate the evaluation methodology and the results for each of these factors.
#### 5.3.1 Number of templates
To test the effect of this factor, we used the one-way permutation test [2] to assess whether the number of templates to identify in a log file statistically interacts with the F-measure scores achieved by MoLFI. The permutation test is a non-parametric test and therefore it does not assume that the data are normally distributed. We ran this test with a very large number of iterations (i.e., $10^6$), as suggested in the literature [2].
According to the one-way permutation test, there is no interaction between the number of templates to be identified in a log file
and the F-measure values obtained by MoLFI (p-value=0.08). This means that our technique yields high F-measure scores both with log files containing a low number of templates (e.g., see the 2K log from PRX in Table 1) and with log files containing a high number of templates (e.g., see the 20K log from PR in Table 1).
5.3.2 Population size. Given the nature of NSGA-II, using a large population size may significantly increase the execution time for finding the best solutions; however, using a population with few individuals may yield poor results. We test the effect of this factor by running MoLFI (on each log file of the benchmark) with a population size of 40 and 80 individuals. We repeated each run ten times and computed the median F-measure and execution time. We compared these results with those obtained by the baseline (with a population of 20 individuals, see Table 1).
Table 2 shows the results of this comparison. Column “T” indicates the median execution time in seconds; column “R” is the ratio between the execution time achieved by the new configurations and the baseline; column “F-m” is the median F-measure; column “∆F-m” indicates the difference, in percentage points, between the F-measure achieved by the new configurations and the baseline. All these values are shown for the columns labeled “pop=40” and “pop=80” of Table 2.
In terms of F-measure, MoLFI performs almost equivalently for the three configurations, with an increase for the majority of log files reaching 4pp for the 2K log file from BGL. We remark two exceptions where the F-measure decreased with a population size of 80: the 300K log file from PR (-5pp) and the BGL log file of size 100K (-1pp).
Execution time sharply increases as the population size grows. This is to be expected since a larger population size entails more fitness computations for NSGA-II.
5.3.3 Removal of duplicate messages. In the pre-processing step presented in section 4.2.1, we filter out duplicated log messages, to reduce the number of log messages to consider for generating templates. However, such a reduction may also directly affect the value of one of our two objective functions, frequency, which could be further reflected in changes to the shape of the Pareto front and to its knee point.
To test the effect of this factor, we ran MoLFI by disabling the routine responsible for removing duplicated log messages in the pre-processing step. As above, each run was repeated ten times and we computed the median F-measure and execution time, as well as the ratio between execution times and the difference in percentage points of the F-measure. The results are shown in the column “no filtering” of Table 2. No data are reported for the 300K log from the PR dataset, since it timed-out (> 3 hours) when completing the first generation of NSGA-II.
We compare these effectiveness scores with those reported in Table 1 (i.e., with filtering enabled). We observe that the F-measure scores obtained by the two configurations are the same for all log files, with only 1 pp increase for the BGL dataset. These results show that filtering out duplicated log messages during pre-processing does not significantly alter the final F-measure. However, it results in a substantial reduction of the execution time. For example, when the filter is enabled, MoLFI requires 126 s to converge for the largest log file (the 300K log file from the PR dataset), while it times out (after three hours) for the same log file when the filter is disabled.
5.4 Is the knee point the best solution?
To answer RQ3, we analyze, over the entire benchmark, the F-measure scores achieved by all solutions in the Pareto front. This means comparing the F-measure of the knee point with the scores achieved by the other Pareto optimal solutions. For the sake of analysis, for each log, we selected one single Pareto front among those obtained with 50 independent runs. For the selection, we first computed the F-measure for the knee point generated in each run; then, we selected the knee point having the median F-measure across the runs and its corresponding Pareto front.
Figure 5 shows, for all the log files in our benchmark, the F-measure of the knee points (indicated with red points) when compared with all the Pareto optimal solutions (represented by the boxplots). One can see that, in all cases, the F-measure score of the knee point is located at the very top of the boxplot. This confirms our conjecture that, in the context of the log message format identification problem, the knee point is the best solution to choose from the Pareto front.
6 DISCUSSION
Practical implications. As discussed in Section 5.2, MoLFI achieves a substantial higher accuracy than alternative algorithms. Such improvements in accuracy represent a considerable reduction in the time needed by analysts to inspect the generated templates, validate them and eventually modify the incorrect ones. For example, MoLFI generates 62 templates for HDFS with the 60K log; on average across runs, 60 templates are correct (as they match the ground truth). One incorrect template is $T=(PacketResponder \,*\, for\, block\, *,\, )$, which is too general as it matches log messages belonging to two different log events: (i) when the PacketResponder for a given block terminated correctly and (ii) when it has been interrupted. The log messages for these two log events are very similar as they
<table>
<thead>
<tr>
<th>Dataset</th>
<th>Size</th>
<th>pop=40</th>
<th>pop=80</th>
<th>no filtering</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>T</td>
<td>R</td>
<td>F-m</td>
<td>∆F-m</td>
</tr>
<tr>
<td>BGL</td>
<td>2K</td>
<td>35.84</td>
<td>2.06</td>
<td>0.86</td>
</tr>
<tr>
<td></td>
<td>100K</td>
<td>17.83</td>
<td>1.64</td>
<td>0.80</td>
</tr>
<tr>
<td>HDFS</td>
<td>2K</td>
<td>6.36</td>
<td>1.99</td>
<td>1.00</td>
</tr>
<tr>
<td></td>
<td>60K</td>
<td>18.26</td>
<td>1.77</td>
<td>0.94</td>
</tr>
<tr>
<td>HPC</td>
<td>2K</td>
<td>15.33</td>
<td>2.03</td>
<td>0.90</td>
</tr>
<tr>
<td></td>
<td>2K</td>
<td>7.54</td>
<td>2.05</td>
<td>0.80</td>
</tr>
<tr>
<td>PR</td>
<td>20K</td>
<td>157.88</td>
<td>1.98</td>
<td>0.78</td>
</tr>
<tr>
<td></td>
<td>300K</td>
<td>155.28</td>
<td>1.24</td>
<td>0.91</td>
</tr>
<tr>
<td>PRX</td>
<td>2K</td>
<td>6.55</td>
<td>1.89</td>
<td>0.77</td>
</tr>
<tr>
<td>2K</td>
<td>13.86</td>
<td>2.00</td>
<td>0.90</td>
<td>0</td>
</tr>
</tbody>
</table>
differ only by one single token. Fixing this template would need to create two templates, each one with an additional fixed token. Since $T$ matches only those two log events, fixing it is trivial.
**Sum-scalarization vs. multi-objective search.** An alternative search-based solution to solve our multi-objective problem would be applying sum scalarization [9]. Such a strategy combines the objectives to optimize into one single function by using the sum operator and thus enabling the use of a single-objective genetic algorithm to optimize the aggregated function. In our case, the aggregation function combines frequency and specificity, i.e., $f(X) = \text{Freq}(X) + \text{Spec}(X)$.
To assess this alternative search strategy, we ran a classical genetic algorithm to optimize the function $f(X)$ mentioned above on HDFS with the 60K log. The median F-measure obtained over 10 independent runs is 0.65 ($\pm$ 0.02), which is statistically significantly lower than the value achieved by MoLFI (i.e., NSGA-II and the knee point), which is 0.94. Note that for the single-objective genetic algorithm we use the same parameter values as for NSGA-II.
The role of constraints. In our problem formulation, we consider two constraints: (i) each log message has to be matched by only one template in a solution $X$; and (ii) the templates in $X$ have to match all log messages (100% coverage). The former constraint is straightforward since templates in a given solution $X$ should not overlap; the latter is less intuitive but analysts, for some specific applications, could be interested in solutions not covering all log messages. However, we observed that the solutions obtained when removing the coverage constraint have only one single template. For example, if we run MoLFI on HDFS with 60K logs by disabling the coverage constraint, NSGA-II returns a knee point which is a solution with only one template having one variable token and 12 fixed tokens. Such a template has high frequency ($\text{Freq}=0.06$) and high specificity ($\text{Spec}=12/13=0.94$). No other template is included in the solution because adding any other template would penalize both frequency and specificity.
Limitations. Our approach may produce incorrect results because of the method we use to group messages. In particular, log messages whose variable part has a variable composition (e.g., because of a variable-length argument list), could lead to different templates even if they have the same fixed part.
7 RELATED WORK
Researchers have proposed various black-box techniques for the log message format identification problem. These techniques rely on clustering [12, 28], heuristics [19, 29], longest common sequence method [11], and textual similarities [17]. Recently, He et al. [16] carried out an empirical study comparing four techniques for the log message format identification problem: SLCT [29], LKE [12], LogSig [28], and IPLoM [19]. The results of this study revealed that (i) IPLoM produces the most accurate templates, and (ii) log pre-processing (like the one applied in MoLFI) is very critical to achieving good clustering performance. In a later study, He et al. [17] introduced DRAIN, a novel technique that processes the log messages through a fixed-depth parse tree. Their empirical study showed that DRAIN generates more correct templates than IPLoM.
One limitation of the two best techniques (DRAIN and IPLoM) is that they require their parameters to be tuned for each log file. Such parameters, if not chosen carefully, will significantly affect the performance of the tool. Different from state-of-the-art techniques, our approach MoLFI uses an automated heuristic to automatically choose the best compromise between the two objectives of the log message format identification problem (frequency and specificity) without using a priori, user-defined thresholds. Our evaluation results show that MoLFI significantly outperforms both IPLoM and DRAIN, both in precision and in recall.
8 CONCLUSION AND FUTURE WORK
The log message format identification problem deals with the identification of the different templates used in the log messages. In this paper, we formulated this problem as a multi-objective optimization one, where the goal is to generate log message templates with high frequency (i.e., they match as many log entries as possible) and high specificity (i.e., specific for each log event). To tackle the problem, we introduced MoLFI, a tool implementing a search-based approach based on a multi-objective genetic algorithm and trade-off analysis.
An empirical study involving six real-world datasets (five publicly-available and one proprietary) showed that MoLFI (i) achieved significantly higher accuracy than DRAIN and IPLoM, two state-of-the-art tools; (ii) is highly scalable to large logs since it requires slightly above two minutes to analyze hundreds of thousands of messages.
As part of future work, we plan to improve the effectiveness of MoLFI by investigating other encoding schemas, experimenting with other formulations of the problem (e.g., by introducing the coverage of log messages as another optimization objective), and by handling semantically equivalent templates. We also plan to assess the use of MoLFI for supporting various software maintenance and testing activities, such as boosting test case generation techniques through the definition of new seeding strategies [24] based on input and output values (variable parts) observed in the logs.
ACKNOWLEDGMENTS
This work has received funding from the European Research Council under the European Union’s Horizon 2020 research and innovation programme (grant agreement No 694277), from the Luxembourg National Research Fund (FNR) under grant agreement No C-PPP17/IS/11602677, and from a research grant by SES.
REFERENCES
|
{"Source-Url": "https://pure.tudelft.nl/admin/files/47344874/main.pdf", "len_cl100k_base": 14063, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 45047, "total-output-tokens": 17849, "length": "2e13", "weborganizer": {"__label__adult": 0.00029540061950683594, "__label__art_design": 0.00037980079650878906, "__label__crime_law": 0.0003228187561035156, "__label__education_jobs": 0.0011548995971679688, "__label__entertainment": 7.003545761108398e-05, "__label__fashion_beauty": 0.0001538991928100586, "__label__finance_business": 0.0003123283386230469, "__label__food_dining": 0.00022292137145996096, "__label__games": 0.0005946159362792969, "__label__hardware": 0.0008411407470703125, "__label__health": 0.0003871917724609375, "__label__history": 0.0002899169921875, "__label__home_hobbies": 0.00010079145431518556, "__label__industrial": 0.00033092498779296875, "__label__literature": 0.00026488304138183594, "__label__politics": 0.00022470951080322263, "__label__religion": 0.0003502368927001953, "__label__science_tech": 0.038604736328125, "__label__social_life": 8.910894393920898e-05, "__label__software": 0.0113677978515625, "__label__software_dev": 0.94287109375, "__label__sports_fitness": 0.00023615360260009768, "__label__transportation": 0.0004148483276367187, "__label__travel": 0.00017583370208740234}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68219, 0.04492]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68219, 0.24574]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68219, 0.86105]], "google_gemma-3-12b-it_contains_pii": [[0, 1263, false], [1263, 5644, null], [5644, 13228, null], [13228, 18577, null], [18577, 25257, null], [25257, 31719, null], [31719, 37691, null], [37691, 44890, null], [44890, 48634, null], [48634, 55496, null], [55496, 61317, null], [61317, 68219, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1263, true], [1263, 5644, null], [5644, 13228, null], [13228, 18577, null], [18577, 25257, null], [25257, 31719, null], [31719, 37691, null], [37691, 44890, null], [44890, 48634, null], [48634, 55496, null], [55496, 61317, null], [61317, 68219, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68219, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68219, null]], "pdf_page_numbers": [[0, 1263, 1], [1263, 5644, 2], [5644, 13228, 3], [13228, 18577, 4], [18577, 25257, 5], [25257, 31719, 6], [31719, 37691, 7], [37691, 44890, 8], [44890, 48634, 9], [48634, 55496, 10], [55496, 61317, 11], [61317, 68219, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68219, 0.05138]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
b322fdcbce0836a951ce719fdc667918206966ea
|
11 March 2004
Strategies for Transitioning from SW-CMM to CMMI
Software Engineering Process Group Conference
Kim Caputo
kim.caputo@deltabus.com
Rick Hefner
rick.hefner@ngc.com
SCAMPI, SCAMPI Lead Appraiser, SEPG, and SEI are service marks of Carnegie Mellon University. CMMI, Capability Maturity Model, and CMM are registered in the U.S. Patent and Trademark Office by Carnegie Mellon University.
Agenda
- **Introduction: Transitioning from SW-CMM to CMMI**
- Introduction to the Transition Process 15 min.
- Exercise: In the Zone 15 min.
- Strategies 15 min.
- **Train Track Strategy** 45 min.
- Break 30 min.
- **Maturity for Dummies Strategy** 30 min.
- Exercise: Process Review Practice 15 min.
- Discussion and Blended Strategy 15 min.
- **Transition Risk Management**
- Misconceptions and Misunderstandings 15 min.
- Summary and Q&A 15 min.
Terms: CMM, SW-CMM, CMMI
- **Capability Maturity Model:**
A reference model of mature practices in a specified discipline, used to assess a group’s capability to perform that discipline
- Examples: SW-CMM, SE_CMM, SECM, FAA-iCMM, etc.
- **SW-CMM was created to provide guidelines for improving the software process**
- **CMMI was created to recast the existing CMMs into a common, integrated framework:**
- Reduce differences in terminology, scope, structure, appraisals
- Combine the best features of each model
- Drive disciplines to be engineered and managed more similarly
- Provide a standard structure for developers on new models to follow
Capability Maturity Model®, CMM®, CMM Integration, and CMMI are service marks and registered trademarks of Carnegie Mellon University
Transitioning from SW-CMM to CMMI
- **SW-CMM is being “sunsetted”**
- SEI will not offer the SW-CMM training after 2003, still available from other vendors
- Lead Assessor (LA) and Lead Evaluator (LE) authorizations expire in 2005
- **What does that mean?**
- Organizations can continue to conduct SW-CMM appraisals until 2006
- Organizations can continue to use the SW-CMM and conduct “un-authorized” appraisals indefinitely, assuming it has value for them
- The value of a SW-CMM rating will diminish over time
- Most customers are starting to express interest in the CMMI
- **Companies should consider their strategy for transitioning to CMMI**
Transition Paths
- How (whether and when) to transition, depends upon your starting point and your final goal
- Four starting point possibilities
- Transitioning from SW-CMM
- Transitioning from SE-CMM
- Transitioning from ISO 9001
- New adopter
- Two final goal possibilities
- Achieving a maturity level
- Achieving measurable improvement
Transition Options
A. Transition now
– Appropriate if you haven’t made much progress to date
– Avoids having to transition later
B. Transition after achieving your SW-CMM goal
– Appropriate if you’re close to your goal
– Provides a sense of closure and accomplishment
– Everything needed for SW-CMM is also needed for CMMI
C. Never transition
– Appropriate if you don’t care about the maturity level
– You will be able to conduct unauthorized appraisals indefinitely
Transition Process Steps
Process Review → Action Planning → Improvement Actions
feedback loop
Process Review → Action Planning → Improvement Actions
feedback loop
"Improving the Way We Improve", Kim Caputo, 2001 Serena Global User Conference
Keeping “In the Zone”
Too Much
Management Pressure
Effort for Results
Effort-Results Connection
Too Little
“In the Zone” Worksheet Exercise
- **Management Pressure**
- Too much: They can’t be serious, ignore it
- Too little: They aren’t serious, ignore it
- Just right: They are serious, put effort into getting results
- **Effort for Results**
- Too much: It takes too much effort to sustain, stop it
- Too little: Not enough effort to get results, stop it
- Just right: We’re getting results, is it worth continuing the effort?
- **Effort-Results Connection**
- Too much emphasis: It’s not believable, stop it
- Too little emphasis: Maybe it’s not connected, stop it
- Just right: the results are based on appropriate effort, it’s worth continuing.
Strategies
1. **Train Track Strategy**
- CMM is ingrained in your company (one extreme)
- Analogous to an upgrade
2. **Maturity for Dummies Strategy**
- ISO-based or CMM Level 1 starting point (the other extreme)
- Analogous to a new installation
3. **Blended Strategy**
- Blended cultures, acquisitions, or subcontracts (between the 2 extremes)
- You pick and choose strategy elements based on needs
Train Track Strategy
- **Train...**
- Train to understand the differences
- Between SW-CMM and CMMI
- Between actual practices and CMMI practices
- **Track...**
- Track progress towards achieving implementation of required practices
- **“Train Track”**
- With CMM already ingrained in the organization, the train is already moving, on the right track, so just get everyone on board...
The High Level View
- **Start by determining the scope of the long-term improvement effort**
- Define “organizational unit” (which part of the enterprise)
- Decide which disciplines will participate, and what level you will seek
- Note: If you have achieved SW-CMM levels, you may need lesser goals for SE
- Re-achieving the same level you are at is a reasonable short-term goal
- **Decide whether pilots will be done**
- Short-term scope of improvement effort
- What will you learn by piloting? Will you actually learn that in the pilot? Could you learn it (cheaper, faster) some other way?
- How will you transition to the long-term scope of the improvement effort?
- **Communicate the objectives and approach**
“Process improvement is about changing the processes you are currently using”
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Some Details
- **Map what you have to the CMMI practices**
- Everything you’re already doing is needed for CMMI
- Policies, processes, procedures, training, planning, tracking, etc.
- **Fill generic practice gaps**
- GP 2.6 Manage Configurations
- GP 2.7 Identify and Involve Relevant Stakeholders
- GP 3.1 Establish a Defined Process (*explicit guidelines in OPD*)
- GP 3.2 Collect Improvement Information
- **Define project strategies for the engineering process areas**
- Requirements Development, Product Integration, Verification, Validation
- **Fill process areas gaps**
- Measurement & Analysis, Decision Analysis & Resolution
Mapping
- **CMMI Context**
- What is included in CMMI?
- **CMMI Structure**
- Disciplines
- Process Areas
- Generic Practices
- Representations
- Terminology
- **Transition Options, Strategies, and Resources**
- Transitioning from SW-CMM
- Transitioning from Other Quality Models
- Managing Your Risks in Achieving a Target Level
What’s Included in the CMMI?
- **Maturity model documents**
- Modules for Engineering (SW/SE), Integrated Product/Process Development (IPPD), Acquisition
- Two different representations (staged, continuous)
- **Appraisal documents**
- Appraisal Requirements for CMMI (ARC) – guides appraisal method developers
- **Training modules**
- 3 day Introduction to CMMI (staged, continuous versions)
- 5 day Intermediate CMMI
- 1 ½ day SCAMPI Appraisal Team Member (ATM)
- 5 day SCAMPI Lead Appraiser
- **Appraiser program**
What’s Different? – Conceptually (1 of 2)
- **CMMI is more explicit about identifying how process areas and generic practices apply**
- Identify which work products will be placed under configuration/data management and what levels of CM/DM
- Identify relevant stakeholders and level of involvement
- Identify strategy for risk management
- **CMMI encompasses more engineering activities**
- Adds requirements development, validation
- Identify strategy for verification -- which work products will be verified and how (e.g., peer review, testing)
- Identify strategy for validation -- which work products will be validated and how (e.g., user involvement in requirements review, operational testing)
- **The hard part is defining and documenting your approach**
What’s Different? – Conceptually (2 of 2)
- Supplier Agreement Management includes any component acquired from outside the product for integration into the product delivered to the customer
- E.g., COTS components, GOTS components
- Content of a process definition is more explicit
- Less focus on “documented procedures”
- Only called out where procedures and criteria are critical to the effectiveness of the process
**Process Elements**
- Process roles
- Applicable process and product standards
- Applicable procedures, methods, tools, and resources
- Process performance objectives
- Entry criteria
- Inputs
- Product and process measures to be collected and used
- Verification points (e.g., peer reviews)
- Outputs
- Interfaces
- Exit criteria
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
### Disciplines
- **CMMI model encompasses the software and systems engineering disciplines**
- Stated generically as engineering activities
- Amplifications used to discuss SW/SE differences
- **Additional disciplines are included as add-on process areas**
- Integrated Product/Process Development (IPPD)*
- Acquisition**
<table>
<thead>
<tr>
<th>Level</th>
<th>Process Areas</th>
</tr>
</thead>
<tbody>
<tr>
<td>5 Optimizing</td>
<td>Causal Analysis and Resolution Organizational Innovation and Deployment</td>
</tr>
<tr>
<td>4 Quantitatively Managed</td>
<td>Quantitative Project Management Organizational Process Performance</td>
</tr>
<tr>
<td>3 Defined</td>
<td>Requirements Development Technical Solution Product Integration Verification Validation Organizational Process Focus Organizational Process Definition Organizational Training Risk Management Integrated Project Management (for IPPD*) Integrated Teaming* Integrated Supplier Management** Decision Analysis and Resolution Organizational Environment for Integration*</td>
</tr>
<tr>
<td>2 Managed</td>
<td>Requirements Management Project Planning Project Monitoring and Control Supplier Agreement Management Measurement and Analysis Process and Product Quality Assurance Configuration Management</td>
</tr>
<tr>
<td>1 Performed</td>
<td></td>
</tr>
</tbody>
</table>
Selecting a Discipline to Use
- Different model versions exist
- CMMI-SW
- CMMI-SE/SW
- CMMI-SE/SW/IPPD
- CMMI-SE/SW/IPPD/SS
- You select which disciplines you wish to use, based on where you are trying to improve
- **Example** – A company which engineers and builds computer systems, by acquisition of COTS hardware and development of custom software, using integrated teams
- Use CMMI-SW applied only to the software development
- Use CMMI-SE/SW applied to the computer system and the software
- Use CMMI-SE/SW/IPPD applied to the system, software, and use of teams
- Use CMMI-SE/SW/IPPD/SS applied to the system, software, teams, and COTS acquisition
What’s Different – Process Areas (1 of 2)
Organization process focus
Organization process definition
Training program
Integrated software mgmt
Software product engineering
Intergroup coordination
Peer reviews
Requirements management
Software project planning
Software project tracking & oversight
Software subcontract mgmt
Software quality assurance
Software configuration mgmt
Organization process focus
Organization process definition
Organizational training
Integrated project management
Risk management
Requirements development
Technical solution
Product integration
Verification
Validation
Decision analysis and resolution
Requirements management
Project planning
Project Monitoring and Control
Supplier Agreement Management
Product & Process Quality Assurance
Configuration Management
Measurement and Analysis
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
What’s Different – Process Areas (2 of 2)
- Levels 4 and 5 are more straightforward and easier to implement
- Clarified that Statistical Process Control is expected at Level 4
**LEVEL 5 OPTIMIZING**
- Defect prevention
- Technology change mgmt
- Process change mgmt
**LEVEL 4 MANAGED**
- Quantitative process mgmt
- Software quality mgmt
- Causal Analysis and Resolution
- Org. Process Technology Innovation
- Process Innovation Deployment
- Org. Process Performance
- Quantitative Mgmt of Quality & Process
Process Areas Organized by Category
**Process Management**
- Organizational Process Focus
- Organizational Process Definition
- Organizational Training
- Organizational Process Performance
- Organizational Innovation and Deployment
**Project Management**
- Project Planning
- Project Monitoring and Control
- Supplier Agreement Management
- Integrated Project Management (for IPPD*)
- Risk Management
- Integrated Teaming*
- Integrated Supplier Management**
- Quantitative Project Management
**Engineering**
- Requirements Development
- Requirements Management
- Technical Solution
- Product Integration
- Verification
- Validation
**Support**
- Configuration Management
- Process and Product Quality Assurance
- Measurement and Analysis
- Organizational Environment for Integration*
- Decision Analysis and Resolution
- Causal Analysis and Resolution
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Components within a Process Area
Process Area
Implementation
Specific Goals
- Activities Performed
- Specific Practices
- Subpractices
- Amplifications
- Elaborations
Common Features
Generic Goals
- Commitment to Perform
- Ability to Perform
- Directing Implementation
- Verification
Subpractices Amplifications Elaborations
Institutionalization
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Required, Expected, and Informative Components
- **Specific Goals**
- Activities Performed
- Specific Practices
- Subpractices
- Amplifications
- Elaborations
- **Generic Goals**
- Commitment to Perform
- Ability to Perform
- Directing Implementation
- Activities Performed
- Generic Practices
- Subpractices
- Amplifications
- Elaborations
**Common Features**
- Required
- Needed to satisfy CMMI
- Expected
- Typical practices to meet goals; Used as a starting point in assessments
- Informative
- Ideas to consider
# Common Feature Comparison
<table>
<thead>
<tr>
<th>SW-CMM v1.1 Common Features</th>
<th>CMMI Common Features</th>
</tr>
</thead>
<tbody>
<tr>
<td>Commitment to Perform</td>
<td>Commitment to Perform</td>
</tr>
<tr>
<td>Establish an Organizational Policy</td>
<td>Establish an Organizational Policy</td>
</tr>
<tr>
<td>Ability to Perform</td>
<td>Ability to Perform</td>
</tr>
<tr>
<td>Plan the Process</td>
<td>Plan the Process</td>
</tr>
<tr>
<td>Provide Resources</td>
<td>Provide Resources</td>
</tr>
<tr>
<td>Assign Responsibility</td>
<td>Assign Responsibility</td>
</tr>
<tr>
<td>Train People</td>
<td>Train People</td>
</tr>
<tr>
<td>Establish a Defined Process</td>
<td>Establish a Defined Process</td>
</tr>
<tr>
<td>Directing Implementation</td>
<td>Directing Implementation</td>
</tr>
<tr>
<td>Manage Configurations</td>
<td>Manage Configurations</td>
</tr>
<tr>
<td>Identify and Involve Relevant Stakeholders</td>
<td>Identify and Involve Relevant Stakeholders</td>
</tr>
<tr>
<td>Monitor and Control the Process</td>
<td>Monitor and Control the Process</td>
</tr>
<tr>
<td>Collect Improvement Information</td>
<td>Collect Improvement Information</td>
</tr>
<tr>
<td>Activities Performed</td>
<td>Activities Performed</td>
</tr>
<tr>
<td>Plan the Process</td>
<td>Plan the Process</td>
</tr>
<tr>
<td>Perform the Process</td>
<td>Perform the Process</td>
</tr>
<tr>
<td>Monitor and Control the Process</td>
<td>Monitor and Control the Process</td>
</tr>
<tr>
<td>Measurement & Analysis</td>
<td>Measurement & Analysis</td>
</tr>
<tr>
<td>Measure the Process</td>
<td>Measure the Process</td>
</tr>
<tr>
<td>Analyze the Measurements</td>
<td>Analyze the Measurements</td>
</tr>
<tr>
<td>Verifying Implementation</td>
<td>Verifying Implementation</td>
</tr>
<tr>
<td>Objectively Verify Adherence</td>
<td>Objectively Verify Adherence</td>
</tr>
<tr>
<td>Review with Project Management</td>
<td>Review with Project Management</td>
</tr>
</tbody>
</table>
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Practices
- Practices are the building blocks of the process areas
**Example** - Project Planning Process Area
*Specific Practice 1.1 - Establish a top-level work breakdown structure (WBS) to estimate the scope of the project.*
- To satisfy the required goals, you are **expected** to perform the practices
- Most commercial and defense projects/organizations will implement as written
- **You may perform equivalent practices if they have an equivalent effect toward satisfying the generic or specific goal**
- These are termed “alternative practices”
- Less prevalent in CMMI than in SW-CMM, because the CMMI practices are at a slightly higher level of abstraction
- “Equivalent” is a judgment call – discuss with your appraiser
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Specific Practices vs. Generic Practices
- **Apply to a single process area**
- **Describe activities that implement the process area**
**Example – Requirements Mgmt.**
<table>
<thead>
<tr>
<th>SG 1 Manage Requirements</th>
</tr>
</thead>
<tbody>
<tr>
<td>SP 1.1 Obtain an Understanding of Requirements</td>
</tr>
<tr>
<td>SP 1.2 Obtain Commitment to Requirements</td>
</tr>
<tr>
<td>SP 1.3 Manage Requirements Changes</td>
</tr>
<tr>
<td>SP 1.4 Maintain Bidirectional Traceability of Requirements</td>
</tr>
<tr>
<td>SP 1.5 Identify Inconsistencies between Project Work and Requirements</td>
</tr>
</tbody>
</table>
---
**Generic Practices**
- **Apply to all process areas**
- **Describe activities that institutionalize the process areas**
**GG 2 Institutionalize a Managed Process**
- GP 2.1 Establish an Organizational Policy
- GP 2.2 Plan the Process
- GP 2.3 Provide Resources
- GP 2.4 Assign Responsibility
- GP 2.5 Train People
- GP 2.6 Manage Configurations
- GP 2.7 Identify and Involve Relevant Stakeholders
- GP 2.8 Monitor and Control the Process
- GP 2.9 Objectively Evaluate Adherence
- GP 2.10 Review Status with Higher Level Management
**GG 3 Institutionalize a Defined Process**
- GP 3.1 Establish a Defined Process
- GP 3.2 Collect Improvement Information
Staged Representation
- Provides a defined roadmap for organizational improvement
- Lower level processes are more critical to repeatable success
- Higher level processes build on the lower level processes
Level 1 Performed
Requirements Management
Project Planning
Project Monitoring and Control
Supplier Agreement Management
Measurement and Analysis
Process and Product Quality Assurance
Configuration Management
Level 2 Managed
Requirements Development
Technical Solution
Product Integration
Verification
Validation
Organizational Process Focus
Organizational Process Definition
Organizational Training
Risk Management
Integrated Project Management (for IPPD*)
Integrated Teaming*
Integrated Supplier Management**
Decision Analysis and Resolution
Organizational Environment for Integration*
Level 3 Defined
Level 4 Quantitatively Managed
Causal Analysis and Resolution
Organizational Innovation and Deployment
Quantitative Project Management
Organizational Process Performance
Level 5 Optimizing
Continuous Representation
- Measures maturity (capability level) of each process area
- Permits maturing of selected processes
<table>
<thead>
<tr>
<th>GG 1 Achieve Specific Goals</th>
<th>GP 1.1 Perform Base Practices</th>
</tr>
</thead>
<tbody>
<tr>
<td>GG 2 Institutionalize a Managed Process</td>
<td>GP 2.1 Establish an Organizational Policy</td>
</tr>
<tr>
<td>GP 2.2 Plan the Process</td>
<td>GP 2.3 Provide Resources</td>
</tr>
<tr>
<td>GP 2.4 Assign Responsibility</td>
<td>GP 2.5 Train People</td>
</tr>
<tr>
<td>GP 2.6 Manage Configurations</td>
<td>GP 2.7 Identify and Involve Relevant Stakeholders</td>
</tr>
<tr>
<td>GP 2.8 Monitor and Control the Process</td>
<td>GP 2.9 Objectively Evaluate Adherence</td>
</tr>
<tr>
<td>GP 2.10 Review Status with Higher Level Management</td>
<td></td>
</tr>
<tr>
<td>GG 3 Institutionalize a Defined Process</td>
<td>GP 3.1 Establish a Defined Process</td>
</tr>
<tr>
<td>GP 3.2 Collect Improvement Information</td>
<td></td>
</tr>
<tr>
<td>GG 4 Institutionalize a Quantitatively Managed Process</td>
<td>GP 4.1 Establish Quantitative Objectives for the Process</td>
</tr>
<tr>
<td>GP 4.2 Stabilize Subprocess Performance</td>
<td></td>
</tr>
<tr>
<td>GG 5 Institutionalize an Optimizing Process</td>
<td>GP 5.1 Ensure Continuous Process Improvement</td>
</tr>
<tr>
<td>GP 5.2 Correct Root Causes of Problems</td>
<td></td>
</tr>
</tbody>
</table>
Copyright 2003 Northrop Grumman Space and Mission Systems Corp. All Rights Reserved.
Which Representation Should We Use?
- If you’re starting out on model-based improvements, use the staged representation
- You need guidance on which process areas to improve first
- If you want to communicate your maturity to your customer, use the staged representation
- Maturity Levels are easier to communicate than maturity profiles
- Don’t use the continuous representation until you have reached Maturity Level 3, and then, only if the other 2 conditions don’t apply
- At lower maturity levels, all processes are important
CMMI Appraisals
**SCAMPI (Standard CMMI Appraisal Method for Process Improvement)**
- Industry standard for benchmarking (i.e., publicly declaring maturity level)
- Typically used to verify; evidence compiled and mapped to model
- Can appraise any organization unit, any portion of model
- Rates each practice for each project within appraisal scope
- Emphasis on direct evidence
- 1-3 weeks: interviews, evidence reviews
- Conducted by 4-12 trained appraisal team member; led by an SEI-authorized Lead Appraiser
- *Method Description Document*
**Informal Appraisal Methods**
- Cannot be used for publicly declaring a maturity level
- Typically used for discovery
- Typically includes evidence review; may include interviews
- Conducted by anyone; value is dependent on their skill and experience
- *Appraisal Requirements for CMMI* describes potential requirements for “good” appraisals
- Class A, B, C
- Vendor self-declares how their method relates to ARC
What’s Different? - Terminology
**SW-CMM**
- Key Process Area
- KPA Goal (Implementation)
- Key Practice from Activities Performed
- KPA Goal (Institutionalization)
- Key Practice from other Common Features
**CMMI**
- Process Area
- Specific Goal
- Specific Practices
- Generic Goal
- Generic Practices
Terminology - 1
- **Organization** – An administrative structure in which people collectively manage one or more projects as a whole, and whose projects share a senior manager and operate under the same policies.
- An organization may contain (lower-level) organizations, with infrastructure (policies, etc.) split among the various levels
- Sometimes used to refer to a functional group (e.g., the CM organization)
- **Organizational Unit** –
That part of an organization that is the subject of an appraisal (also known as the organizational scope of the appraisal).
- E.g., a site, a domain, all software projects
Terminology - 2
- **Project** - A managed set of interrelated resources that delivers one or more products to a customer or end user. This set of resources has a definite beginning and end.
- A project can be composed of projects
*The point of improving an organization’s capability is to reduce risk on the next project (as well as current projects).*
- **Senior Manager** – A management role at a high enough level in an organization that the primary focus of the person filling the role is the long-term vitality of the organization, rather than short-term project and contractual concerns and pressures.
- Above a project manager
Terminology - 3
- **Customer** - The party (individual, project, or organization) responsible for accepting the product or for authorizing payment. The customer is external to the project, but not necessarily external to the organization.
- **Stakeholder** - A group or individual that is affected by or in some way accountable for the outcome of an undertaking. Stakeholders may include project members, suppliers, customers, end users, and others.
- **Relevant Stakeholder** - Used to designate a stakeholder that is identified for involvement in specified activities.
- Projects and functional organizations must identify their relevant stakeholders, and define their level of involvement.
**Terminology - 4**
- **Product** - Any tangible output or service that is a result of a process and that is intended for delivery to a customer or end user. A product is a work product that is delivered to the customer.
- Could be a system, a software item, or a service
- *Critical for determining how process areas are applied*
- **Product Component** - Lower level components of the product; product components are integrated to “build” the product.
- **Work Product** - Any artifact produced by a process.
- E.g., deliverable documents, non-deliverable documents, meeting minutes, personal notes, etc.
- Projects and functional organizations must identify their work products and the level of configuration control applied to each
Terminology - 5
- **Adequate, Appropriate, As Needed** – Used to signify that certain activities may not be done all of the time.
- E.g., “corrective action, as needed”
- **Establish and Maintain** - Includes documentation and usage.
- E.g., “Establish and maintain an organizational policy” means that not only must a policy be formulated, but it also must be documented and it must be used throughout the organization.
- **Alternative practice** - A substitute for one or more generic or specific practices contained in CMMI models that achieves an equivalent effect toward satisfying the generic or specific goal.
- Not necessarily a one-for-one replacement for the CMMI practice
- “Equivalent” is a judgment call -- ensure your appraiser agrees on your interpretation
- Less prevalent in the CMMI than in SW-CMM
Strategic Plan Checklist
1. Determine the appropriate scope -- organization and model
2. Review each CMMI practice, within the projects and the organizational groups, to identify and document any interpretation issues
3. Select a Lead Appraiser, based on how they interpret those same issues
- Do they agree on scope?
- Which projects will need to be assessed?
- Are any process areas not applicable, given your scope of work? How will that be worded in the final “certification”?
4. Document your agreement on how the issues will be handled
- What evidence is sufficient to satisfy the practice?
5. Have the projects and organizational groups start putting together the evidence notebooks immediately
6. Track progress towards filling the gaps – have the evidence reviewed by a qualified appraiser (preferably the chosen Lead)
7. 1-2 months before the appraisal, do a final check
8. Ensure the appraisal team has sufficient experience
Maturity for Dummies Strategy
- Maturity is the subject matter
- Process improvement is the method
- Improved results is the goal
- Dummies are not dumb
- Dummies learn fast because they have to
- Dummies don’t want the elaborate details
- “Maturity for Dummies”
- Simple, direct, straight-line approach
- If making changes throws you a curve, straighten it out by taking the derivative.
*Do the Math: Straighten curves by taking the derivative*
*The derivative of $x^2 = 2x$*
Transition Process View (Straightening the Curve)
"Improving the Way We Improve", Kim Caputo, 2001 Serena Global User Conference
The High Level View
- **Process Review**
- Start by determining what people think about where they are and where they want to be
- Don’t introduce CMMI terminology until they are ready
- Win acceptance of the need to improve
- **Action Plan**
- Plan in 3-month segments
- Address documentation, training, records, reviews, progress measures
- **Improvement Actions**
- Define, Make, and Track progress of improvements
- Make results visible with a Progress Review monthly and a Process Review every 6 months
Maturity for Dummies Process Review
- The Derivative
- The questions are derived from a cross-section of all Process Areas for CMMI Level 2 and Level 3, without using specific CMMI terminology
- The questions are not as accurate but are more straightforward
- The answers are not Yes/No, but describe/measure the Gap.
- Data Collection Spreadsheet format:
<table>
<thead>
<tr>
<th>Category: Question</th>
<th>Today What we do today</th>
<th>Tomorrow What we’d like to be doing</th>
<th>Effort Rating Rate each item given for Tomorrow</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
</tbody>
</table>
2002, Kim Caputo, Delta Business Solutions
Effort Ratings and Strategy
- **Get a Baseline Measurement**
- Rate the effort for each “Tomorrow” item response and save the numbers for later comparison
- **Effort Ratings**
0 = No change necessary
1 = needs a few tweaks (include it)
2 = needs some changes (include it)
3 = needs major changes, but not today
4 = needs major changes, soon
5 = needs major changes, now (include it)
- **Strategy**
- Include in Action Plan if rated 1, 2, or 5
- Don’t let the curve throw you off, smooth it
2002, Kim Caputo, Delta Business Solutions
Process Review – Communication Questions
1. How frequently do the developers meet for status/learning?
2. How frequently do the cross-functional project teams meet?
3. What is the agenda for these meetings?
4. How are requirements and requirements changes communicated?
5. How is release status, readiness, and delivery approval communicated?
6. How does management conduct Project Reviews?
7. How does management conduct Phase or Stage-Gate Reviews?
8. How often does sr. management review the organization against goals?
9. How are issues, risks, and action items tracked to closure?
2002, Kim Caputo, Delta Business Solutions
Process Review – Estimation Questions
1. Are the development tasks to perform known?
2. Are the tasks documented?
3. Is there an estimated range of time it takes to complete known tasks?
4. How do the developers and managers adjust the estimates when the task assignment is made?
5. How much of the developers day is spent on known tasks vs. “crisis of the day”?
6. Do the known tasks include planning and evaluation tasks?
7. Is the risk estimated for unknown tasks?
Process Review – Project Measures Questions
1. Is the project scope documented?
2. How is the scope managed and changed?
3. How is the scope reviewed to determine the tasks?
4. Are the tasks, estimated duration, and staffing assignments documented as a schedule?
5. How is the schedule managed and changed?
6. Is the target quality level documented?
7. How is the quality level tracked and managed?
8. How are defect removal tasks assigned/added to the project?
9. Is the target cost level documented?
10. How is the cost level tracked and managed?
11. How are the risks to meeting planned targets identified and managed?
2002, Kim Caputo, Delta Business Solutions
Process Review – Engineering Questions
1. How are requirements gathered, defined, and managed?
2. How is analysis and design done to determine what to build or modify?
3. How is implementation/coding done?
4. How is the code tested?
5. What kinds of reviews or inspections are done?
6. How is the code managed for version and configuration control?
7. How are test plans developed?
8. How is satisfaction of the requirements tested or determined?
9. How is product content and test status tracked?
10. How are defects tracked?
11. Are there any checklists for reviews/inspections?
12. Are there any templates for designs, code, test plans, or tests?
2002, Kim Caputo, Delta Business Solutions
Process Review – Processes Questions
1. Are policies, processes, procedures, checklists, and templates documented?
2. How do people get access to the current versions of these documents? (Website?)
3. How do you know whether people are using these documents? (Reviews or audits?)
4. How are these processes evaluated for effectiveness?
5. How frequently are the processes evaluated for effectiveness?
6. How are these processes changed or improved?
7. How do the current projects consider their specific factors for tailoring the standard processes, checklists, and templates for their use?
8. How does management handle waivers or deviations from standard processes?
2002, Kim Caputo, Delta Business Solutions
## Results Table Example
<table>
<thead>
<tr>
<th>Category</th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>Total Items</th>
<th>Average</th>
<th>Mode</th>
</tr>
</thead>
<tbody>
<tr>
<td>Communications</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Estimation</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Project Measures</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Engineering</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Processes</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
2002, Kim Caputo, Delta Business Solutions
Action Plan according to Generic Practices
- What strategy will be applied generically in all areas that will institutionalize any process areas
<table>
<thead>
<tr>
<th>GG 2 Institutionalize a Managed Process</th>
</tr>
</thead>
<tbody>
<tr>
<td>1. Organizational Policy</td>
</tr>
<tr>
<td>2. Plan</td>
</tr>
<tr>
<td>3. Resources</td>
</tr>
<tr>
<td>4. Responsibility</td>
</tr>
<tr>
<td>5. Training</td>
</tr>
<tr>
<td>6. Configurations</td>
</tr>
<tr>
<td>7. Stakeholders</td>
</tr>
<tr>
<td>8. Measurements</td>
</tr>
<tr>
<td>9. Audits</td>
</tr>
<tr>
<td>10. Reviews</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>GG 3 Institutionalize a Defined Process</th>
</tr>
</thead>
<tbody>
<tr>
<td>11. Process Definition</td>
</tr>
<tr>
<td>12. Improvement Data</td>
</tr>
</tbody>
</table>
Process Review Worksheet Exercise
- **In pairs or groups, practice interviewing each other**
- Choose one of the five categories
- Ask the first three questions for a sample
- Answer “Today” and “Tomorrow” first,
Then for each “Tomorrow” item response, give an effort rating from 0-5.
- **Discussion questions**
- How do you compare? Same or different challenges?
- Any improvement suggestions?
- How do you think people in your organization will react to a Process Review?
- **Blended Strategy**
- If your organization is a blend,
not one extreme (CMM-ingrained) or the other (CMM Level 1),
then how can you blend the 2 strategies for an appropriate strategy for you?
Blended Strategies Account for Zoning Out
Too Much
Management Pressure
Effort for Results
Effort-Results Connection
Too Little
Just Right
Blended Strategy 1: Incrementerfall
- Incrementerfall = Incremental + Waterfall
- **Start with Train-Track**
- Fall *(due to reorg, new management not convinced)*
- Do Maturity for Dummies
- **Continue with Train-Track**
- Fall *(due to low effort, or performance bar raised)*
- Do Maturity for Dummies
- **Continue with Train-Track**
- Fall *(due to not seeing effort-results connection)*
- Do Maturity for Dummies
2003, Kim Caputo, Delta Business Solutions
Blended Strategy 2: Watermental
- Watermental = Waterfall + Incremental
- Start with Maturity for Dummies
- Action Plan and Improvements with good progress
- Start Train-Track
- When Mentally Frozen
Re-Start with Maturity for Dummies
- Continue with Train-Track
- When Mentally Frozen (Again)
Re-Start with Maturity for Dummies
- Continue with Train-Track
2003, Kim Caputo, Delta Business Solutions
Transition Risk Management
- Identify potential risks
- If (this happens)
Then (this might happen)
- Quantify schedule delays
- Quantify cost in dollars over budget
- Quantify defects or cost to quality
- Identify mitigation actions
- What to do to prevent occurrence, or reduce impact
- Identify contingencies and triggers
- What to do if the risk event occurs
Risks Sound Like This…
“I didn’t think Validation applied to our project.”
“I thought the organization did that.”
“Our customer won’t let us do that.”
“I thought this was a software assessment.”
“Why aren’t these projects included in the appraisal?”
“I want to do CMMI – I just don’t want to change our process.”
Risks Look Like This…
Senior management wants to adopt industry best practices (or wants the CMMI rating), but may not understand…
...implied costs
- Process improvement staff
- Policies, processes, procedures
- Training
- Quality assurance
- Measurement repository
- Learning curve
- Hiring expertise
- Appraisals
...improvement concepts
- Near-term investment, long-term benefits
- Bureaucracy vs. discipline
- Standardization vs. institutionalization
- Discipline makes the organizations less agile (initially)
- The need to enforce less popular practices
“Aligning CMMI Strategies with Individual, Project, and Organizational Perspectives”, Rick Hefner, 2003 Software Technology Conference
Risks Can Be Phrased Like This…
- If the CMMI Level Goal does not seem realistic, then people assume it’s not serious and they won’t engage in the effort, causing a schedule delay.
- If you start with a formal appraisal, and the results are less than what managers are expecting, then management might not respond with an appropriate degree of management pressure (too much or too little), causing a schedule delay.
- If you and your appraiser interpret practices in different ways for your organization’s context, then obtaining recognition at the target maturity level is at risk, causing defects in the quality of the appraisal process.
Transition Risk Mitigation Actions
- Timelines are appropriate for communicating expectations of urgency, but they must be realistic
- **Identify your appraiser up-front**
- Significant differences exist among appraisers, especially on their interpretations of the CMMI practices
- Get their up-front agreement that you have interpreted correctly for your context
- **Do not start with a formal appraisal**
- If you want help identifying the gaps and strategy, have an experienced CMMI appraiser do an informal appraisal
- Results should focus on what the right strategy is, given where you are
- **Once you have your strategy defined, seek CMMI experienced help (not just SW-CMM experience)**
- Does our strategy make sense? Are there better options? Are out timelines reasonable?
Key Questions for Transitioning
- What does “sunsetting the SW-CMM” mean?
- Can we still do SW-CMM assessments? For how long?
- What are the advantages/disadvantages in adopting the CMMI?
- We only develop software – does adopting the CMMI make sense?
- What are our transition options?
- We’re working on our next maturity level – should we transition now or wait?
- What does it mean to be keeping “in the zone”?
- SW-CMM is ingrained in our organization – what strategy should we use?
- We’re still trying to move up from Level 1 - what strategy should we use?
- We have a blended team – what strategy should we use?
- What are some of the risks we need to beware of during transition?
Summary
- The CMMI can provide valuable guidance for improving your engineering processes
- Your strategy for adopting the CMMI is key to success
- Depending on whether your organization is at one extreme or the other, there are 2 strategies to choose from (or blend)
- Train Track Strategy
- Maturity for Dummies Strategy
- Learning from experience and careful planning can reduce risk and ensure success
Contact Information
- Kim Caputo, Delta Business Solutions
Visiting Scientist, Software Engineering Institute
11 Alato Drive
Mission Viejo, CA 92693 USA
(949)837-3048
(949)837-3082 FAX
kim.caputo@deltabus.com
www.deltabus.com
- Rick Hefner, Northrop Grumman
One Space Park R2/1136
Redondo Beach, CA 90278
(310) 812-7290
rick.hefner@ngc.com
|
{"Source-Url": "https://resources.sei.cmu.edu/asset_files/Presentation/2004_017_001_22646.pdf", "len_cl100k_base": 9744, "olmocr-version": "0.1.50", "pdf-total-pages": 62, "total-fallback-pages": 0, "total-input-tokens": 97482, "total-output-tokens": 11739, "length": "2e13", "weborganizer": {"__label__adult": 0.0003981590270996094, "__label__art_design": 0.0007467269897460938, "__label__crime_law": 0.0003609657287597656, "__label__education_jobs": 0.0108795166015625, "__label__entertainment": 0.0001068711280822754, "__label__fashion_beauty": 0.0002617835998535156, "__label__finance_business": 0.00476837158203125, "__label__food_dining": 0.00037550926208496094, "__label__games": 0.0007658004760742188, "__label__hardware": 0.0006780624389648438, "__label__health": 0.0004489421844482422, "__label__history": 0.0004119873046875, "__label__home_hobbies": 0.0002288818359375, "__label__industrial": 0.000736236572265625, "__label__literature": 0.00045371055603027344, "__label__politics": 0.0002999305725097656, "__label__religion": 0.0004475116729736328, "__label__science_tech": 0.0121612548828125, "__label__social_life": 0.00019991397857666016, "__label__software": 0.012847900390625, "__label__software_dev": 0.951171875, "__label__sports_fitness": 0.0004153251647949219, "__label__transportation": 0.0005517005920410156, "__label__travel": 0.0003056526184082031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41351, 0.01328]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41351, 0.22203]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41351, 0.87554]], "google_gemma-3-12b-it_contains_pii": [[0, 402, false], [402, 872, null], [872, 1669, null], [1669, 2445, null], [2445, 2801, null], [2801, 3292, null], [3292, 3539, null], [3539, 3845, null], [3845, 4510, null], [4510, 4932, null], [4932, 5334, null], [5334, 6236, null], [6236, 6890, null], [6890, 7241, null], [7241, 7924, null], [7924, 8702, null], [8702, 9548, null], [9548, 10726, null], [10726, 11399, null], [11399, 12306, null], [12306, 12822, null], [12822, 13764, null], [13764, 14213, null], [14213, 14780, null], [14780, 17380, null], [17380, 18210, null], [18210, 19376, null], [19376, 20383, null], [20383, 21577, null], [21577, 22116, null], [22116, 23081, null], [23081, 23386, null], [23386, 24012, null], [24012, 24655, null], [24655, 25353, null], [25353, 26100, null], [26100, 26929, null], [26929, 27878, null], [27878, 28372, null], [28372, 28502, null], [28502, 29027, null], [29027, 29837, null], [29837, 30392, null], [30392, 31023, null], [31023, 31492, null], [31492, 32159, null], [32159, 32854, null], [32854, 33567, null], [33567, 34277, null], [34277, 35125, null], [35125, 35823, null], [35823, 36161, null], [36161, 36637, null], [36637, 37053, null], [37053, 37431, null], [37431, 37750, null], [37750, 38448, null], [38448, 39091, null], [39091, 39887, null], [39887, 40577, null], [40577, 40988, null], [40988, 41351, null]], "google_gemma-3-12b-it_is_public_document": [[0, 402, true], [402, 872, null], [872, 1669, null], [1669, 2445, null], [2445, 2801, null], [2801, 3292, null], [3292, 3539, null], [3539, 3845, null], [3845, 4510, null], [4510, 4932, null], [4932, 5334, null], [5334, 6236, null], [6236, 6890, null], [6890, 7241, null], [7241, 7924, null], [7924, 8702, null], [8702, 9548, null], [9548, 10726, null], [10726, 11399, null], [11399, 12306, null], [12306, 12822, null], [12822, 13764, null], [13764, 14213, null], [14213, 14780, null], [14780, 17380, null], [17380, 18210, null], [18210, 19376, null], [19376, 20383, null], [20383, 21577, null], [21577, 22116, null], [22116, 23081, null], [23081, 23386, null], [23386, 24012, null], [24012, 24655, null], [24655, 25353, null], [25353, 26100, null], [26100, 26929, null], [26929, 27878, null], [27878, 28372, null], [28372, 28502, null], [28502, 29027, null], [29027, 29837, null], [29837, 30392, null], [30392, 31023, null], [31023, 31492, null], [31492, 32159, null], [32159, 32854, null], [32854, 33567, null], [33567, 34277, null], [34277, 35125, null], [35125, 35823, null], [35823, 36161, null], [36161, 36637, null], [36637, 37053, null], [37053, 37431, null], [37431, 37750, null], [37750, 38448, null], [38448, 39091, null], [39091, 39887, null], [39887, 40577, null], [40577, 40988, null], [40988, 41351, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41351, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41351, null]], "pdf_page_numbers": [[0, 402, 1], [402, 872, 2], [872, 1669, 3], [1669, 2445, 4], [2445, 2801, 5], [2801, 3292, 6], [3292, 3539, 7], [3539, 3845, 8], [3845, 4510, 9], [4510, 4932, 10], [4932, 5334, 11], [5334, 6236, 12], [6236, 6890, 13], [6890, 7241, 14], [7241, 7924, 15], [7924, 8702, 16], [8702, 9548, 17], [9548, 10726, 18], [10726, 11399, 19], [11399, 12306, 20], [12306, 12822, 21], [12822, 13764, 22], [13764, 14213, 23], [14213, 14780, 24], [14780, 17380, 25], [17380, 18210, 26], [18210, 19376, 27], [19376, 20383, 28], [20383, 21577, 29], [21577, 22116, 30], [22116, 23081, 31], [23081, 23386, 32], [23386, 24012, 33], [24012, 24655, 34], [24655, 25353, 35], [25353, 26100, 36], [26100, 26929, 37], [26929, 27878, 38], [27878, 28372, 39], [28372, 28502, 40], [28502, 29027, 41], [29027, 29837, 42], [29837, 30392, 43], [30392, 31023, 44], [31023, 31492, 45], [31492, 32159, 46], [32159, 32854, 47], [32854, 33567, 48], [33567, 34277, 49], [34277, 35125, 50], [35125, 35823, 51], [35823, 36161, 52], [36161, 36637, 53], [36637, 37053, 54], [37053, 37431, 55], [37431, 37750, 56], [37750, 38448, 57], [38448, 39091, 58], [39091, 39887, 59], [39887, 40577, 60], [40577, 40988, 61], [40988, 41351, 62]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41351, 0.10075]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
51f0f741ba7f087e791266d114f7bdbfabb7c98c
|
Change Propagation in Decentralized CompositeWeb Services
Walid Fdhila, Aymen Baouab, Karim Dahman, Claude Godart, Olivier Perrin, François Charoy
To cite this version:
Walid Fdhila, Aymen Baouab, Karim Dahman, Claude Godart, Olivier Perrin, et al.. Change Propagation in Decentralized CompositeWeb Services. 7th International Conference on Collaborative Computing: Networking, Applications and Worksharing - CollaborateCom 2011, Oct 2011, Orlando, United States. hal-00647004
HAL Id: hal-00647004
https://inria.hal.science/hal-00647004
Submitted on 1 Dec 2011
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Change Propagation in Decentralized Composite Web Services
Walid Fdhila, Aymen Baouab, Karim Dahman, Claude Godart, Olivier Perrin, and François Charoy
LORIA - INRIA - UMR 7503
BP 239, F-54506 Vandœuvre-lès-Nancy Cedex, France
{firstname.lastname}@loria.fr
Abstract—Every company wants to improve the way it does business, or produce things more efficiently, and make greater profit. Therefore, business processes have become subject to evolutionary changes, which in turn increase the need for an efficient change support. In this sense, many researches were conducted to deal with business process adaptation to changes. The latter may result in the restructuring of the whole or a part of the process. Most of the proposed approaches focus on adaptation to changes in centralized processes. In sharp contrast to these works, our operation of change adaptation that we present in this paper, concerns decentralized orchestrations. Indeed, many recent approaches were proposed to decompose a composite web service into small partitions. Since the activities, the control and data flows are distributed over these partitions, it becomes difficult to specify the changes directly. Moreover, changing a derived partition may affect the way it interacts with others. In order to overcome these deficiencies, we propose a design-time methodology to support changes in decentralized business processes. We mainly demonstrate how to propagate the changes made on a centralized specification of composite web service to its resulting decentralized sub-processes.
Keywords—decentralized orchestration, business process, change propagation, web service.
I. INTRODUCTION
The Service-Oriented Architecture (SOA) is a proven collection of principles for structuring large-scale systems in order to improve manageable and to streamline change. One of the pillars of the SOA is its ability to rapidly compose multiple services into an added-value business process, and then to expose the resulting composition as a composite service [1]. Despite the decentralized nature of the context of the B2B and B2C interactions, the conception and implementation of a typical business process rely on a centralized execution setting. The relevant research literature on business management confirms that the decentralization of business processes is a critical need for several reasons [1].
In a previous work, we proposed an approach to partition a composite web service [2], [3], [4]. The partitioning transforms the centralized process into behaviorally equivalent distributed sub-processes each of which related to a criteria. These partitions are executed independently at distributed locations and can be invoked remotely. They directly interact with each other using asynchronous messaging without any centralized control. The flexibility introduced by the derived decentralized processes on the other hand raises new requirements like adaptation to change. Neither our approach or similar approaches on decentralization deal with the problem of change propagation after partitioning. However, in today’s dynamic business world, the economic success of an enterprise increasingly depends on its ability to react to changes within its environment in a quick and flexible way [5]. Therefore, a critical challenge for the competitiveness of any enterprise is its ability to quickly react to business process changes and to adequately deal with them [6]. Causes for these changes can be manifold and include the introduction of new laws, market dynamics, or changes in customers’ attitudes [7]. For these reasons, companies have recognized business agility as a competitive advantage, which is fundamental for being able to successfully cope with business trends.
Changes may range from simple modifications of the process to a complete restructuring of the business process to improve efficiency. In the context of the decentralized service orchestrations, applying these changes in a straightforward manner on the derived orchestration partitions is a complex maintenance task, since the control and data flows are decomposed over multiple partitions. In this sense, this paper presents a method for adaptation to change in the decentralized composite web services. In sharp contrast to previous works [8], [9], [10], [11], our change adaptation concerns decentralized orchestrations. Given a well-behaved structural update on a centralized orchestration, our approach automates the change forward propagation that consistently propagates the update to the derived decentralized partitions. This includes the identification of the partitions concerned by the modification, and the incorporation of the necessary changes in each of them. The main advantage of this method, is that only concerned partitions by the change are affected, and there is no need to recompute the whole decentralization or redeploy all the partitions.
The reminder of this paper is structured as follows. Section II introduces a motivating example to illustrate the importance of change adaptation in decentralized orchestrations. We adopt this example to explains the different steps of our approach. Section III presents the formal definitions needed
to provide a generic approach, while section IV details our adaptation to change mechanism for the decentralized processes. After a reviewing of the properties of our approach in Section V and its evaluation, the section VI and VII we discuss the related works, summarize the contribution and outline future directions.
II. MOTIVATING EXAMPLE
The composite web services are generally captured by means of an orchestration model: a process model in which each activity represents either an intermediate work step (e.g. a data transformation) or an interaction with one of the services participating in the composition (the component services). The process model specifies the control-flow and data-flow relations between activities, using a specialized language such as the Business Process Execution Language (WS-BPEL) or the Business Process Modeling Notation (BPMN).
To motivate and illustrate the method presented in this paper, we make use of a sample orchestration (cf. Figure 1). The corresponding process model is captured in the BPMN notation, and it includes both control and data dependencies. The process is represented by a directed acyclic graph where nodes are activities or control patterns and edges are data or control dependencies. Activities are depicted with boxes with the activity name inside and the web service it refers to. The arcs between boxes describe the dependencies. This leads to a well defined chronological execution of the activities. In this example, we consider that services are known in advance. In particular this process represents a collaboration with four services \( s_1 \), \( s_2 \), \( s_3 \) and \( s_4 \). Data edges are represented by dashed arrows, and each control pattern has an identifier. After \( a_1 \) termination, the data \( d_1 \) is sent to \( a_2 \) or \( a_3 \) or both of them are executed. This execution terminates when it reaches the terminate state.
Based on our partitioning techniques presented in [2], [3], Figure 2 depicts a decentralized execution settings for the process example of Figure 1. The latter is partitioned into four partitions that are executed by four distributed orchestrators (preferably collocated with the web services). Each partition \( P_1 \) is responsible for all activities that are delegated to a given service and defines the relationships between them. The connectivity between activities of the centralized process is translated to that between activities of different partitions, through asynchronous message exchange mechanism. This includes data and control links (dashed arrows) represented by \( c_1 \), \( c_2 \), and \( d_1 \), \( d_7 \) respectively. The schema, illustrates only a part of the interconnection mechanism.
Now, consider that the designer wants to make some changes, which result in a restructuring of the process activities. Specifying these changes directly on the decentralized partitions is a complex and error-prone task. Indeed, the activities are distributed over partitions, and a local change on a partition may affect other partitions, since they are related. Hence, it is more easier to apply the changes...
on the centralized specification, and then propagate these modifications to the derived partitions with respect to control and data flows.
Let’s consider the example depicted in Figure 1, and suppose that the fragment $F$ (gray box, consisting of $OR_{a_5}$, $a_{10}$, $a_{11}$, $a_{17}$ and $OR_{f_3}$) should be replaced by the fragment $F'$ (consisting of $AND_{a_6}$, $a_{25}$, $a_{26}$, $a_{27}$ and $AND_{f_3}$). The data link, initially connecting $a_{17}$ and $a_{23}$ is modified by a data link between $a_{25}$ and $a_{23}$. Obviously, this replacement would affect mainly the partitions $P_{s_2}$ and $P_{s_4}$, since the modification includes only activities invoking $s_2$ and $s_4$ respectively (c.f. Figure 2). As can seen in the above example, the changes on the centralized specification, results in restructuring of the concerned derived partitions. They can either be done as an insertion, an update or a deletion of tasks. In Figure 2, the gray boxes in partitions $P_{s_2}$ and $P_{s_4}$, represent the fragments which are affected by the change. These fragments are sub-processes with single entry/single exit and should be replaced by the updated fragments. To conclude, the main problem behind this change is: (i) How to identify the concerned partitions, and in each partition the fragments to be changed or restructured? (ii) How the concerned activities and control patterns are deleted or updated? (iii) Where to insert the new fragments and how? (iv) Finally, how to update the communications with other partitions to preserve the semantics of the initial process?
### III. Formal Model
In order to provide a generic approach for change adaptation in the decentralized business processes, we adopt a high level reasoning using an abstract notation. A process is specified in an abstract way (e.g. using a graph based formalism), and mapped onto the implementation level. We do not presume any particular process modeling approach, but simply assume that the basic elements of a process can be specified in an abstract way to be translated to an executable process language (i.e. process structure in terms of atomic activities and sub-processes, dependencies between the steps of a process, etc). By definition, a process which specifies a web service composition defines the relationship between service invocations. This relationship may characterize either the control or data flow structure.
**Definition 1 (Process):** Formally, a process $\mathcal{P}$ is a tuple $(O, D, \mathcal{E}_c, \mathcal{E}_d, S)$ where
- $O$ is a set of objects which can be partitioned into disjoints sets of activities $A$, events $(\text{start and end})$ and control patterns $CTR$,
- $D$ is a set of data,
• \( \mathcal{E}c \) is a set of control edges where, \( \mathcal{E}c \subset \mathcal{O} \times \mathcal{O} \).
• \( \mathcal{E}d \) is a a set of data edges where, \( \mathcal{E}d \subset \mathcal{A} \times \mathcal{A} \times \mathcal{D} \).
• \( \mathcal{S} \) is the set of services invoked by the process.
In this paper, we consider that the processes are structured [12]. This means that different activities are structured through control elements such as AND-split, OR-split, AND-join, OR-join, etc., and for each split element, there is a corresponding join element of the same type. Additionally, the split-join pairs are properly nested. The process, has a single entry and a single exit. A process activity consists of a one-way or a bidirectional interaction with a service via the invocation of one of its operations. In conversational compositions, different operations of a service can be invoked with the execution of different activities. The set of activities that refer to the same service \( s \) is denoted \( \mathcal{A}_s \mid s \in \mathcal{S} \). A control edge characterizes the mapping relationship while a data edge characterizes the mapping relation of the output and the input values of two activities.
**Definition 2 (Activity):** An activity \( a_i \in \mathcal{A}_s \) is a tuple \(( \mathcal{I}_n, \mathcal{O}_n, s) \) where \( \mathcal{I}_n \subset \mathcal{D} \) is the set of \( a_i \)'s inputs and \( \mathcal{O}_n \subset \mathcal{D} \) is the set of \( a_i \)'s outputs, \( s \) is the service invoked by \( a_i \).
Activities are related to each other and are dependent on each other. These dependencies are intra-process. Dependencies may also exist across processes and are referred to as inter-process dependencies. A path between two objects (activity, event or control pattern) is defined by the set of edges which link them. We define the preset (postset) of an activity \( a_i \), denoted \( \bullet a_i \), \( (a_i \bullet) \), as the set of activities which may execute just before (after) \( a_i \) and related to it by a set of control dependencies.
**Definition 4 (Preset):** \( \bullet a_i = \{ a_j \in \mathcal{A} \mid \exists \text{path}_{ji} = e_{1}, e_{2}, \ldots, e_{n} \in \mathcal{E}_c \text{ where } \forall k, 1 < k < n, \text{ target}(e_k) = \text{source}(e_{k+1}) \wedge \text{source}(e_1) = a_i \wedge \text{cible}(e_n) = a_j \} \).
**Definition 5 (Postset):** \( a_i \bullet = \{ a_j \in \mathcal{A} \mid \exists \text{path}_{ij} = e_{1}, e_{2}, \ldots, e_{n} \in \mathcal{E}_c \text{ where } \forall k, 1 < k < n, \text{ target}(e_k) = \text{source}(e_{k+1}), \text{target}(e_1), \text{source}(e_n) \in CTR \} \).
The partitioning of a composite web service, leads to a set of interconnected partitions, each of which defines the relationship between the objects it includes. Each partition communicates with other partitions using the interaction patterns (i.e. send, receive,..) [13].
**Definition 6 (Partition):** A sub-process or a partition is a tuple \( P_s = (\mathcal{O}_s, \mathcal{D}_s, \mathcal{E}_c, \mathcal{E}_d) \) where
- \( \mathcal{O}_s \) is a set of objects of \( P_s \), \( \mathcal{O}_s \subset \mathcal{O} \cup \mathcal{A}_{dummy}(i) \)
where \( \mathcal{A}_{dummy}(s) \) is a set of dummy activities. Dummy activity is an activity with zero execution time (used for synchronization).
- \( \mathcal{D}_s \subset \mathcal{D} \cup \mathcal{S}_{sync} \), where \( \mathcal{S}_{sync} \) is a set of control data necessary for synchronization with other partitions.
- \( \mathcal{E}_c \) is the set of control edges, \( \mathcal{E}_c \subset \mathcal{O}_s \times \mathcal{O}_s \).
- \( \mathcal{E}_d \) is the set of data edges, \( \mathcal{E}_d \subset \mathcal{A}_s \times \mathcal{A}_s \), (control edges between partitions are transformed to data edges since they are routed in messages).
- \( s \in \mathcal{S} \) is the set of services invoked by the partition.
**Example:** The definition of \( \mathcal{P}_{s1} \) (c.f. figure 2) is the tuple \( \mathcal{P}_{s1} = (\mathcal{O}_{s1}, \mathcal{D}_{s1}, \mathcal{E}_{c_{s1}}, \mathcal{E}_{d_{s1}}) \) where,
- \( \mathcal{O}_{s1} = \{ a_{1,8,9,15,12}, \text{e}_{dummy_{1}}, \text{start}_{1}, \text{end}_{1}, \text{OR}_{1,2,3,4_{sp}}, \text{OR}_{1,2,3,4_{j}} \} \)
- \( \mathcal{D}_{s1} = \{ d_{1}, d_{5}, \ldots \} \)
- \( \mathcal{E}_{c_{s1}} = \{ \text{e}_{\text{start}_{1}, a_{1}}, \text{e}_{a_{1}, \text{OR}_{1_{sp}}}, \text{e}_{\text{OR}_{1_{sp}}, \text{OR}_{2_{sp}}}, \text{e}_{\text{OR}_{2_{sp}}, \text{OR}_{3_{sp}}}, \ldots \} \)
- \( \mathcal{E}_{d_{s1}} = \{ c_{1}, c_{2}, a_{1}, \text{P}_{s1.a_{4}}, \text{P}_{s4} (i.e. d_{1}) \} \)
Next, we define the transitive postset (resp., transitive preset) of an activity \( a_i \) denoted \( T_{\mathcal{A}_1} \bullet (T_{\mathcal{A}_1}) \), as the set of activities in the same partition as \( a_i \), which may execute just after (before) it, and linked to it by a set of control dependencies. In the centralized process, the path between \( a_i \) and its transitive postset (resp., transitive preset) may include other activities of other partitions.
**Definition 7 (Transitive Postset):** Formally, for an activity \( a_i \in \mathcal{P}_{ck} \), \( T_{\mathcal{A}_1} \bullet = \{ a_j \in \mathcal{P}_{ck} \mid \text{path}_{ji} = e_{1}, e_{2}, \ldots, e_{n} \subset \mathcal{E}_c \text{ where } \forall 1 < k < n, \text{target}(e_k), \text{source}(e_k), \text{target}(e_{1}), \text{source}(e_{n}) \notin \mathcal{A}_{ck} \} \).
**Definition 8 (Transitive Preset):** Formally, for an activity \( a_i \in \mathcal{P}_{ck} \), \( T_{\mathcal{A}_1} \bullet = \{ a_j \in \mathcal{P}_{ck} \mid \text{path}_{ij} = e_{1}, e_{2}, \ldots, e_{n} \subset \mathcal{E}_c \text{ where } \forall 1 < k < n, \text{target}(e_k), \text{source}(e_k), \text{target}(e_{1}), \text{source}(e_{n}) \notin \mathcal{A}_{ck} \} \).
**IV. Change Propagation**
In this section, we present our methodology for decentralized business processes adaptation to change. We remind that our approach concerns only already partitioned processes. This means that we do not seek to provide a change support for a centralized process. Instead, we demonstrate how to propagate the changes made on a centralized specification of a composite web service to its resulting decentralized sub-processes. The approach is structured as follows. First the designer specifies the changes using the centralized process specification, then we compute the new configurations of the decentralized fragments enclosing the changes. Finally, we propagate the changes to the concerned partitions. In this way, only the fragments which are concerned by the changes would be affected. Moreover, there is no need to re-partition the
centralized process and re-deploy all the derived partitions.
A. Change operations
In general, process models can be decomposed into SESE fragments [14]. A SESE fragment is a non-empty subgraph in the process model with a single entry and a single exit edge [15]. For every change in the process model, there is at least one enclosing fragment. Here, we consider only the smallest fragment that encloses the changes. This can be achieved using the process structure tree (PST) [14]. In the following, we consider that the fragments enclosing the changes are already identified (the identification issue is out of scope of this paper). Formally, a fragment has the same definition as a process (c.f. definition 1), except it has no start and end events, instead it has one entry and one exit edges. We can resume the changes that can be made on a process model, by three formal operations as follows:
- **Insert(fragment, entry, exit):** this operation is used to insert a new fragment into the process. This fragment should be inserted between the entry and exit edges in the centralized process model.
- **Delete(entry, exit):** this operation is used for the deletion of the fragment between the entry and exit edges in the centralized process model.
- **Update(fragment, entry, exit):** this operation updates the existing fragment between entry and exit edges in the centralized process model, and replace it by fragment. This operation can also be replaced by the two consecutive operations delete(entry, exit) and insert(fragment, entry, exit).
It should be noted that a fragment ranges from a simple activity to a enhanced structured sub-process with a single entry/single exit. Let’s consider the example of figure 1. The fragment $\mathcal{F}$ to add in the process model is defined by $\mathcal{F} = (O_\mathcal{F}, D_\mathcal{F}, E\mathcal{F}, O_\mathcal{F}, S_\mathcal{F})$ and the fragment to delete is defined by $\mathcal{F} = (O_\mathcal{F}, D_\mathcal{F}, E\mathcal{F}, O_D, S_\mathcal{F})$. Then, the change operation is defined by Update($\mathcal{F}, \mathcal{F}, \mathcal{F}.entry, \mathcal{F}.exit)$ where $\mathcal{F}.entry = e_{a1, OR_{sp}}$ and $\mathcal{F}.exit = e_{a11, OR_{sp}} \in E_{CB}$. This operation can also be transformed as follows:
$$\text{Update}(\mathcal{F}, \mathcal{F}.entry, \mathcal{F}.exit) \Rightarrow \text{Delete}(\mathcal{F}, \mathcal{F}.entry, \mathcal{F}.exit) \land \text{Insert}(\mathcal{F}, \mathcal{F}.entry, \mathcal{F}.exit).$$
B. Change adaptation
This section describes the different steps to propagate the changes made on the centralized process model to the derived decentralized partitions. To have a better understanding, we refer to the motivating example depicted in Figure 1) to illustrate the adaptation process, then we detail our approach using a generic process model.
We remind that we want to replace the fragment $\mathcal{F}$ in the centralized process by the fragment $\mathcal{F}$. For this purpose, we first identify the partitions affected by this change using activities identifiers. For instance, the deletion of activity $a_{10} : s_4$ in $\mathcal{F}$ or the insertion of the new activity $a_{25} : s_2$ in $\mathcal{F}$ means the deletion or the insertion of the same activities from $P_{s4}$ or to $P_{s2}$ respectively. The second step,
is to identify the blocs of activities to change inside the affected partitions. Indeed, a simple change in a partition may result in other modifications (including interactions with other partitions or control patterns). For example (c.f. figure 2), the deletion of the activity $a_{11}$ in $P_{s2}$ results in the deletion of all the fragment enclosed between $OR_{s2}$ and $OR_{s1}$ since the other activity in parallel with it, is dummy. For each identified fragment, we notice the entry and the exit edges. Two use cases are possible: the fragment is updated and replaced by another fragment, or deleted. Using the new fragment $F'$, the next step is to determine what to insert in each partition. For this purpose, we have to partition $F'$.

As can seen in Figure 3, the partitioning of the fragment $F_t$, leads to two fragments $F_{t1}$ and $F_{t2}$, connected by a control edge $c_{4}$ (for more details about the decentralization process refer to [2]). The affected fragments by the change are respectively, $F_1$ and $F_2$, and therefore, the initial change operation is transformed into two updates on $P_{s2}$ and $P_{s4}$ respectively. Figure 4 illustrates the transformation operation, where $F_1$ is updated by $F_{t1}$ in $P_{s2}$ and $F_2$ is updated by $F_{t2}$ in $P_{s4}$.
Now, consider a general example of a centralized process model $P$, as depicted in Figure 5. The process model is structured through split and join patterns, and enclosed with a start / end events. The partitioning of this process, results in $|S|$ interconnected partitions $P_1$, $P_j$, $P_K$, etc, each of which executed by a separate orchestrator (c.f. Figure 6). The steps toward change propagation are as follows:
1. **Change specification**: the designer specifies the changes to do using change operations: Insert, Delete and Update. If the operation is a delete, then he has to indicate the concerned fragment (i.e. in figure 5 $\text{Delete}(\text{Entry}edge, \text{Exit}edge)$). If the operation is an Insert, then he has to specify the fragment to add and in which place in the process model (i.e. in figure 5 $\text{Insert}(F_t, \text{Entry}edge, \text{Exit}edge)$). Otherwise, he has to specify both the fragment to update and the new fragment to insert (i.e. in Figure 5 $\text{Update}(F_t, F'_1, F_exit)$).
Next, we consider the Update operation since it is more general and includes the two other operations.
2. **Partitions identification**: Using the fragments $F$ and $F_t$, we identify all the partitions that would be affected by the change. Indeed, during partitioning, each activity is assigned to a partition upon to a certain criteria. If the activity responds to the criteria of the partition then it would be assigned to it (i.e. activities having the same role, or invoking the same service). So, using the criteria assigned to each activity we can determine the partition it would belong to. By this way, each partition having a criteria of one of $F$ or $F_t$ activities would be affected by the change.
3. **Fragments partitioning**: this step consists in decentralizing separately the fragments $F_t$ and $F$ into interconnected sub-fragments, using partitioning techniques for structured processes. In figure 6, we take into consideration only the sub-fragments $F_{P_j}$, $F_{P_K}$, $F_{P_1}$ and $F_{P_J}$, since they cover the three possible scenarios: insert, delete or update a sub-fragment into a partition.
4. **Change translation**: After $F$ and $F_t$ partitioning, change operation for the process model is decomposed into one or more change operations. Each operation represents the change to make on the corresponding partition. The generic formula for operation transformation is $\text{operation}_i(x, y, ..) \Rightarrow \text{operation}_i(x_1, y_1, ..) \land .. \land \text{operation}_i(x_2, y_2, ..)$, where $\text{operation}_i$ is the change to apply to partition $P_i$. For instance, the generated change operations on partitions $P_1$, $P_j$ and $P_K$ are as follows:
$$\text{Update}_{P_i}(F_t, F_{P_j}, F_{P_K}, F_{P_1}, F_{P_2}, F_{P_3}, F_{P_4}, F_{P_5}, F_{P_6}, F_{P_7}) \land \text{Delete}_{P_j}(F_{P_1}, F_{P_2}, F_{P_3}, F_{P_4}, F_{P_5}, F_{P_6}, F_{P_7}) \land \text{Insert}_{P_K}(F_{P_1}, F_{P_2}, F_{P_3}, F_{P_4}, F_{P_5}, F_{P_6}, F_{P_7})$$
It should be noticed, that the entry and the exit of the $\text{Insert}$ construct should be computed (next step).
5. **Partitions adaptation to change**: This step consists in applying the changes to the corresponding partitions. For this purpose, we first, have to determine exactly where to insert the sub-fragments $F_{P_j}$, $F_{P_K}$. The first scenario related to the update of $F_{P_j}$ in $P_j$ is simple, since we
already know the entry and exit edges of $F_{P_J}$. So, we have just to look for these edges in the partition and replace all the fragment between them by the fragment $F_{P_J'}$. The deletion of the latter, implies the deletion of all the interactions with other activities in the same partition or other partitions. The partitions which interact with any activity concerned by the change is also concerned by the change, since we have to update its corresponding interaction edges. Formally, the update of $F_{P_J}$ in a $P_J$ by $F_{P_J'}$ corresponds to the deletion of all objects $o \in O_{F_{P_J}}$, edges $e \in E_{F_{P_J}} \cup E_{d_{F_{P_J}}}$, and data, and their substitution by the objects, edges, and data of $F_{P_J'}$.
The Delete operation application is similar to the update, except that we do not insert a new sub-fragment. We simply look for the entry and exit of $F_{P_I}$ in the partition $P_I$. Then we delete the sub-fragment between them. If the entry edge of the sub-fragment to delete, is linked to a (choice or parallel) split control pattern (outside the sub-fragment), and the exit edge is linked to its corresponding join element, then we look if the other branches linking these two elements include only dummy activities or not. If yes then we delete these two patterns. We iterate this operation on each nested constructs linking the sub-fragment $F_{P_I}$ to its transitive preset $T_{F_{P_I}}$ and postset $T_{F_{P_I}}$ (c.f. definition 7, 8) (we extend the definition of transitive postset (transitive preset) to that between a fragment and its subsequent (previous) activities). Otherwise, we replace the sub-fragment to delete, by a dummy activity.
Now, to insert sub-fragment $F_{K'}$ in the partition $P_K$, we have to identify the entry and exit edges. For this purpose, we first compute the transitive preset and postset of $F_{K'}$ in $P_K$ ($T_{F_{K'}}$, $T_{F_{K'}}$). Then, we identify all the control patterns that link them in the centralized process model.
Next, we identify each split pattern $ctr$ in this control path linking it to its $F_{K'}$, such as $ctr$ is in the path linking it to its $F_{I_K}$ ($ctr$ is the correspondent join element of $ctr$). For each choice $ctr$ found, we look if it already exists in the partition. If yes, we just add a new branch linking $ctr$ to $ctr$ in which we put $F_{I_K}$. If no, we add it and its corresponding $ctr$, then we put the $F_{I_K}$ between them (in parallel with a dummy activity). In some cases, the update or the insertion of a fragment may result in the creation of a new partition or the deletion of an existing partition.
The propagation of the changes made on the centralized process to the derived decentralized partitions are formally described by three rules. These rules include all the steps mentioned previously. According to the change operation (update, delete or insert), we execute the corresponding actions. These actions represent the identification of the affected partitions by the change, the identification of the fragments to be changed in these partitions and the modifications to apply. The modifications range from the change operations to apply on the concerned partitions to the update of the interactions with other partitions. In these rules $dec(F)$ is a function that returns the decentralized sub-fragments of the fragment $F$.
**Rule 1**
**Operation**: $Delete_p(F\_entry, F\_exit, F \subset p)$
**Actions**:
- $\forall F_I \in dec(F), p_i \leftarrow Identify\_PartitionOf\_F_I$
- $\forall F_i \in dec(F), (entry_i, exit_i) \leftarrow Identify\_In(F_i, p_i)$
- $\forall F_i \in dec(F), Delete_p(entry_i, exit_i)$
- $\forall a_j \in \bullet F, \forall a_k \in F \bullet update\_connection(a_j, a_k)$
Rule 2
Operations: Insert_p(F, l, entry, exit)
Actions:
∀ F,l ∈ dec(F), p_l ← IdentifyPartitionOf(F, l)
∀ F,l ∈ dec(F), (entry, exit) ← IdentifyIn(F, p_i)
∀ F,l ∈ dec(F), Insert_p(F, l, entry, exit)
∀ a_j ∈ • F_l, update_connection(a_j, F)
∀ a_k ∈ F_l • update_connection(F, a_k)
Rule 3
Operations: Update_p(F, l, F.entry, F.exit), F ∈ p
Actions:
∀ F,l ∈ dec(F), p_l ← IdentifyPartitionOf(F, l)
∀ F,l ∈ dec(F), p_l ← IdentifyPartitionOf(F, l)
∀ F,l ∈ dec(F), (entry, exit) ← IdentifyIn(F, p_i)
∀ F,l ∈ dec(F), F,j ∈ dec(F) s.t. p_i = p_j. Update_p(F, l, entry, exit) where (entry, exit) ← IdentifyIn(F, p_j)
∀ F,l ∈ dec(F) s.t. j ∈ dec(F) \ p_i, Insert_p(F, l, entry, exit) where (entry, exit) ← IdentifyIn(F, p_j)
∀ F,l ∈ dec(F) s.t. j ∈ dec(F) \ p_i, Delete_p(F, l, entry, exit) where (entry, exit) ← IdentifyIn(F, p_j)
∀ a_j ∈ • F, update_connection(a_j, F)
∀ a_k ∈ F • update_connection(F, a_k)
V. Evaluation of the approach
This section presents the properties of our change propagator. Given a well-behaved structural update on the centralized process model and the derived decentralized sub-processes, our approach automates the change forward propagation that consistently transforms the update on the source into the related target partitions, as presented in Section IV. Then we show the applicability of our approach by reviewing the motivating example and presenting an implementation.
A. The properties of the approach
In order to describe this approach following our work in [16] and defined in definitions 1 and 6, the process partitioning is a total function of the type \( dec : \mathcal{P} \rightarrow \{\mathcal{P}_s\}_{s \in S} \) that takes a source centralized process in \( \mathcal{P} = (\mathcal{O}, \mathcal{D}, \mathcal{E}_c, \mathcal{Ed}, \mathcal{S}) \) and produces a target set of decentralized partitions \( \mathcal{P}_s = (\mathcal{O}_s, \mathcal{D}_s, \mathcal{E}_c, \mathcal{Ed}_s) \) where \( s \in S \). It establishes a consistency relation, denoted \( \mathcal{C} \subseteq \mathcal{P} \times \{\mathcal{P}_s\}_{s \in S} \) between the source and the target process models. This relation captures the mapping between the centralized process logic in \( \mathcal{P} \) and the (same) decentralized process logic described in \( \{\mathcal{P}_s\}_{s \in S} \). Since our decentralization algorithm is idempotent as we have presented in [2]: it can be applied multiple times without changing the result, then \( \mathcal{C} \) is a total function.
Now, consider a source centralized process model \( p \in \mathcal{P} \) and a target partition set \( \delta_\mathcal{P} \) that are consistent with respect to the relation \( \mathcal{C} \), i.e., \( (p, \delta_\mathcal{P}(p)) \in \mathcal{C} \) means that \( p \) was previously decentralized to \( \delta_\mathcal{P}(p) \). Given a source change \( \delta_\mathcal{P} \) that alters \( p \) to \( \delta_\mathcal{P}(p) \), the problem is to translate the well-behaved change of the source process \( \delta_\mathcal{P} \) into a well-behaved changes on the target partitions \( (\delta_\mathcal{P}(p))^{e \in S} \), such that the application of both updates results in consistent process models. The change propagator that provides this function is of the type \( \mathcal{P} \times \Delta_\mathcal{P} \times \{\mathcal{P}_s\}_{s \in S} \rightarrow \{\mathcal{P}_s\}_{s \in S} \). For \( p \in \mathcal{P} \), \( \delta_\mathcal{P} \in \Delta_\mathcal{P} \) and \( dec(p) \in \{\mathcal{P}_s\}_{s \in S} \), it determines \( (\delta_\mathcal{P}(p))^{e \in S} \in \Delta_\mathcal{P}_s \) and then computes the changes on the partitions \( (\delta_\mathcal{P}(p))^{e \in S} \) such that the updated models are consistent, i.e., \( (\delta_\mathcal{P}(p), (\delta_\mathcal{P}(dec(p)))^{e \in S}) \in \mathcal{C} \). We use \( \Delta_\mathcal{P} : \mathcal{P} \rightarrow \mathcal{P} \) and \( \Delta_\mathcal{P}_s : \{\mathcal{P}_s\}_{s \in S} \rightarrow \{\mathcal{P}_s\}_{s \in S} \) as an abbreviation for the update types respectively on the processes and on the partitions. They represent the space of all partial functions describing the changes on each of the centralized and decentralized process models and which can be described by productions, i.e. the change operation defined in Section IV.
In our semantics, a process and its decentralization result (i.e., the derived partitions) are specified with graphs as introduced in Section II. Then, a change on a process implies a modification on the graph structure which can be expressed by graph rewriting rules [17]. Formally, given a graph \( \mathcal{G} \), a graph rewriting rule (i.e., also called production) consists of injective morphisms of the form \( \delta_\mathcal{G} : \mathcal{L} \rightarrow \mathcal{R} \) that transform a source graph \( \mathcal{L} \) into a target graph \( \mathcal{R} \). In order to apply this rewrite rule to the initial graph \( \mathcal{G} \), a match \( m : \mathcal{L} \rightarrow \mathcal{G} \) is needed to specify which part of \( \mathcal{G} \) is being updated. Then, the application of \( \delta_\mathcal{G} \) to \( \mathcal{G} \) via a match \( m \) for \( \delta_\mathcal{G} \) is uniquely defined by the graph rewriting \( \mathcal{G} \triangleright_{\delta_\mathcal{G}, m} \mathcal{H} \). This rule application induces a co-match \( m^\prime : \mathcal{R} \rightarrow \mathcal{H} \) which specifies the embedding of \( \mathcal{R} \) in the result graph \( \mathcal{H} \). For more details on the so called forward satisfaction associated to the graph rewriting refer to [17]. Generally, the problem of a graph rewriting technique is that it is considered to be undecidable. However, if it meets certain criteria, then, we can conclude that it is terminating and locally confluent.
Firstly, the most important criteria is the change propagation correctness: a graph-based change propagator must return consistent process models. In this paper, we suppose that when applying a rewriting rule to a given graph \( \mathcal{G} \), it is enough to consider the case where the morphisms that matches \( \mathcal{L} \) to \( \mathcal{G} \) is injective [18], and that the match \( m \) is a total label-preserving, type-preserving and root-preserving [17] graph morphism. However, to be correctly applied, the productions must satisfy the structural consistency of the centralized process constraints. Note that we assume the well-behavedness of the updates propagated by the designers. It means that the graph production on a centralized process is consistent with the behavioral requirements, and after the production the process remains structured. Moreover, the fragment or process partitioning preserves by definition the well-behaved process semantic. Secondly, a fundamental law is that the change propagation should
deterministic [19]: for each centralized process model input there is a unique decentralization result. In our case, the change propagator is modeled by a mathematical function. It means that given the same pair of the centralized and its decentralized models, and a finite set of changes (i.e., bounded within the SESE fragment) on the source centralized process model, our propagator produces the same changes on the target partitions.
Finally, our propagator takes as a parameters the previous decentralization, i.e., \((p, \text{dec}(p)) \in C\), and the update of the source process \(\delta_P\). In order to adapt \(\text{dec}(p)\) the potential changes induced by \(\delta_P\), and rather than executing the decentralization afresh on the entire updated centralized process model, i.e., \(\text{dec}(\delta_P(p))\), our change propagator enforces an in-place synchronization between \(\delta_P(p)\) and \(\text{dec}(p)\) by translating the updates \(\delta_P\) into well-behaved target updates \((\delta_P)_{S} \in S\) to get \((\delta_P, (\text{dec}(p))_{S}) \in S\) consistent with \(\delta_P(p)\). The change translation can be seen as a partial function of the type \(\Delta_P \rightarrow \Delta_S\). The reason is that in the case where \(\delta_P\) is small, generally, it corresponds to a small update of the partitions: \((\delta_P)_{S} \in S\). The performance savings for those computations are expected to be high in comparison with a \(\text{diff}\)-based method [20], [17]. Taking into account a fragment in the source process \(p\) and a fragment in the previously obtained partitions \(\text{dec}(p)\), the effort to determine \((\delta_P)_{S} \in S\) with the partition identification and to compute \((\delta_P, (\text{dec}(p))_{S}) \in S\) should be much less than to apply a new decentralization \(\text{dec}(\delta_P(p))\) and a \(\text{diff}\) between the new result and the previous \(\text{dec}(p)\). The speedup of this incremental decentralization and the partitions adaptation to change results in a reasonable decoupling from the processes and partitions size [21].
B. Proof of concepts prototype
The change propagator has been successfully implemented and integrated with our previous development of the partitioning algorithm [2] as an extension to a BPMN Editor [22]. This BPMN editor is based on a graph visualization library, and it is used to model a source centralized process model, for instance the structured process of Figure 1. After applying our partitioning algorithm, we obtain the partitions depicted in Figure 2 using the graph library. Moreover, we have developed a filter that logs the process model editing operations presented in Section IV. Actually, the specification of the entry and the exit of a fragment is performed manually, for example as depicted in Figure 3, but it can be easily automated. The change propagation algorithm is implemented in the DROOLS [23] inference engine, and it automatically computes the graph editing operation sequence that manipulates the partitions. The experimental results are encouraging, but still needs to be validated in a real-scale case. We refer the reader to [21] for further discussions on the scalability measurements of a similar incremental model synchronization technique.
VI. RELATED WORK
Several issues related to change management have been addressed in business process management, and workflow literature [24], [25], [26]. These proposals deal with adaptive process management. For instance, the ADEPT proposal enables controlled changes at the process type as well as the process instance level [9]. The authors, present a formal foundation for the support of dynamic structural changes of running workflow WF instances. Based upon a formal WF model (ADEPT). They also define a set of change operations (ADEPTflex) that support users in modifying the structure of a running WF.
In [8], Van der Aalst and Jablonski present important issues related to process changes and discuss organizational structures. In [11], the authors motivate the need for the controlled change of organizational models. In particular, they present different adaptations models to be supported by respective components (e.g. to extend, reduce, replace, and re-link model elements).
Alanen and Porres describe in [20] an algorithm to compute elementary change operations. In [27], Kolovos et al. describe the Epsilon merging language. The latter is used to specify how models are merged. Kelter et al. present in [28] a generic model differencing algorithm. In [29], Cicchetti et al. propose a metamodel for the specification and detection of syntactical and semantical conflicts. Rinderle et al. [14] have studied disjoint and overlapping process model changes in the context of the problem of migrating process instances.
All the mentioned approaches, address change adaptation in a centralized process. They also deal, with how to dynamically adapt running instances to changes. This, may be complementary to our work.
In the decentralized setting, [14] presents a formal model for a distributed workflow change management (DWFCM) that uses a rules topic ontology and a service ontology to support the needed run-time flexibilty. A system architecture and the workflow adaptation process are presented. The approach aims to generate a new workflow that is migration consistent with the original workflow. This work is different from our proposal, since they do not seek to propagate a pre-defined changes on a centralized process to that on the derived partitions. Their work is more focused on run-time adaptation using the migration rules.
In [16] the authors present a unidirectional model incremental transformation approach. Its central contribution is the definition and the realization of an automatic synchronizer for managing and re-establishing the structural consistency of heterogeneous source and target models. From a design-time perspective, an evolution describes the update on model’s internal structures that can be assimilated to a graph. They express the model evolutions and their transformation using conditional graph rewriting techniques.
VII. Conclusion
Lifecycle support of BPM solutions is becoming more and more important. In order to achieve the goals of BPM implementation, it is required to support process analysis and improvement, which necessitates a framework for managing business process changes. In this paper, we have presented an approach to adapt decentralized orchestrations to changes specified on the corresponding centralized process. The proposed approach is based on three change patterns Insert, Update and Delete. The method consists in partitioning the fragment to change into sub-fragments, which in turn, are integrated into the corresponding partitions. To the best of our knowledge, this is the first work that takes on changes adaptation in decentralized composite web services. Evidently, there are some limitations inherently implied by the usage of only the structured processes. Thus, as a perspective we further to extend our approach to handle non-structured processes. Moreover, the introduced operations can be composed to give rise to process update types with enhanced semantics for the users (e.g., move of fragment, refactoring of fragments: splitting and merging). However, we restricted our presentation to the structural correctness. The integration of our update translation operator in a previously developed ATLAS Transformation Language chain [30] for the Eclipse SOA Tools Platform is in development.
REFERENCES
|
{"Source-Url": "https://inria.hal.science/hal-00647004/file/fdhila_Collab_2011.pdf", "len_cl100k_base": 11212, "olmocr-version": "0.1.42", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 48746, "total-output-tokens": 13912, "length": "2e13", "weborganizer": {"__label__adult": 0.00025272369384765625, "__label__art_design": 0.00043129920959472656, "__label__crime_law": 0.00026988983154296875, "__label__education_jobs": 0.0010204315185546875, "__label__entertainment": 7.18832015991211e-05, "__label__fashion_beauty": 0.00013506412506103516, "__label__finance_business": 0.0005307197570800781, "__label__food_dining": 0.00028967857360839844, "__label__games": 0.00038743019104003906, "__label__hardware": 0.0005445480346679688, "__label__health": 0.0004546642303466797, "__label__history": 0.0002617835998535156, "__label__home_hobbies": 7.617473602294922e-05, "__label__industrial": 0.00034618377685546875, "__label__literature": 0.0002951622009277344, "__label__politics": 0.00026607513427734375, "__label__religion": 0.00033354759216308594, "__label__science_tech": 0.038482666015625, "__label__social_life": 9.822845458984376e-05, "__label__software": 0.014984130859375, "__label__software_dev": 0.93994140625, "__label__sports_fitness": 0.00020003318786621096, "__label__transportation": 0.000362396240234375, "__label__travel": 0.00018537044525146484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50665, 0.02702]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50665, 0.46749]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50665, 0.85431]], "google_gemma-3-12b-it_contains_pii": [[0, 1109, false], [1109, 6326, null], [6326, 9476, null], [9476, 12203, null], [12203, 18988, null], [18988, 22319, null], [22319, 27114, null], [27114, 30865, null], [30865, 37691, null], [37691, 43854, null], [43854, 49755, null], [49755, 50665, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1109, true], [1109, 6326, null], [6326, 9476, null], [9476, 12203, null], [12203, 18988, null], [18988, 22319, null], [22319, 27114, null], [27114, 30865, null], [30865, 37691, null], [37691, 43854, null], [43854, 49755, null], [49755, 50665, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50665, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50665, null]], "pdf_page_numbers": [[0, 1109, 1], [1109, 6326, 2], [6326, 9476, 3], [9476, 12203, 4], [12203, 18988, 5], [18988, 22319, 6], [22319, 27114, 7], [27114, 30865, 8], [30865, 37691, 9], [37691, 43854, 10], [43854, 49755, 11], [49755, 50665, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50665, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-22
|
2024-11-22
|
e323ab650d57d029f8d5e0840a689b747e11f962
|
A Domain Engineering for Interactive Learning Modules
Danilo L. Dalmon and Leônidas O. Brandão
Instituto de Matemática e Estatística, Universidade de São Paulo
Department of Computer Science
Rua do Matão 1010, Cidade Universitária, São Paulo, SP - Brazil
Email: ddalmon@ime.usp.br, leo@ime.usp.br
Anarosa A. F. Brandão
Escola Politécnica, Universidade de São Paulo
Department of Computer and Digital Systems Engineering
Email: anarosa.brandao@poli.usp.br
Seiji Isotani
Instituto de Ciências Matemáticas e de Computação, Universidade de São Paulo
Laboratory of Software Engineering
Email: sisotani@icmc.usp.br
For creating educational systems, each developer usually applies different approaches to specific situations, including advanced software engineering techniques. In the case of systems that provide interactivity-intensive assignments, problems during their development include difficulties to manage component repositories and the absence of a systematic process to support code reuse. Interactive Learning Modules (iLM) are systems designed in this context, which also provide key functionalities to facilitate the teacher’s work. To address the problems faced during theirs development, a Domain Engineering is proposed to build iLM. In order to define the iLM software family, this paper presents the core features of existing systems, describes the method used to produce an application framework and how to instantiate it. Restructuration of existing iLM using the proposed Domain Engineering is reported with initial high gains in productivity and system quality.
Classification: D.2.2 Design Tools and Techniques; D.2.11 Software Architecture; D.2.13 Reusable Software; K.3.1 Computer Uses in Education.
Keywords: Educational Software; Domain Engineering; Application Framework; Interactive Learning Modules.
1. INTRODUCTION
The problem of developing educational software is not new. Nicolson and Scott (1986) analyzed educational software development cycles and reported that the technology developed is often inadequate for both teachers and learners. Educational Software are tools created to be used by students and teachers, and they are expected to improve students’ knowledge about some subject and/or help teachers to produce better educational content (Tchounikine, 2011).
In order to establish a clear goal for any educational software, the literature points out the importance of interactivity to increase students’ motivation and learning outcomes. For instance, many authors address the improvement in students’ understanding through their interactivity with the learning content (Isotani and Brandão, 2008, Kortenkamp, 2004, Sims, 1997, and Ruthven, Hennessy and Deaney, 2007). Also, interactivity through quick feedback for each student’s response is important to keep them motivated (Hentea, Shea and Pennington, 2003, Hara and Kling, 1999).
Interactive Learning Modules (iLM), formerly known as e-LM (Rodrigues, Brandão and Brandão, 2010), are educational software that focus on these interactive features and the main characteristics of which are: running in web-browsers, presenting authoring tools, promoting interactivity-intensive assignments and
Developing educational software is expensive and time-consuming. Moreover, to produce new systems that provide interactivity demanded by teachers and educators may imply higher costs, related to specifying, developing and testing the system with the final users, teachers and students. An approach to reduce costs and improve maintainability during software development is code reuse. Nevertheless, without a systematic process to support code reuse, this approach could be ineffective, even considering a small group of people that share almost the same knowledge. This was occurring in our research group, in which five iLM were developed: iGeom (Isotani and Brandão, 2008), iGraf (do Prado, 2006), iCG, iComb (Eisenmann and Brandão, 2009) and iVProg (Kamiya and Brandão, 2009) without the adoption of a systematic software process and people organization.
In addition, the development of educational systems has some differences from other specific-area software in some aspects (Tchounikine, 2011), which makes code reuse difficult (Spalter and van Dam, 2003). These differences include components with numerous granularities, self managed repositories, ill-defined quality criteria and social issues, such as team organization and project management. Many attempts, including applying software engineering techniques, were made to solve these problems (Roschelle, Kaput, Stroup and Kahn, 1998, Spalter and van Dam, 2003, Ateyeh and Lockermann, 2006), but some issues still remain, such as systematic use and reuse of components available in repositories, limited interactivity provided, and underlying pedagogical approaches that prevent teachers from using systems in broader educational contexts.
In order to overcome many of these problems, a Software Product Line (SPL) approach was chosen for developing the iLM software family. The intended outcome of this research is to provide a Domain Engineering for improving the development of these systems. This technique defines team organization and a systematic development process to improve reuse and quality of a group of similar software (Clements and Northrop, 2001). Domain Engineering can be used to: (i) design the refactoring of a set of existent iLM; to (ii) develop new iLM; and to (iii) add new domain-independent features to them. An application framework was used to manage variability in Domain Engineering design and implementation (Dalmon et al., 2011a).
Our main goal is to report the development of a Domain Engineering for a specific family of educational software, the iLM, in order to highlight lessons learned and development results. It is not our goal to contribute to the SPL field of research. The work presented is inserted in a research project the long term goal of which is to develop and to evaluate a SPL for iLM. This evaluation will be possible after several years of SPL use so there will be data about software quality, development, maintenance and evolution under the influence of this technique. Currently, the first version of Domain Engineering is completed and Application Engineering is starting, which provides data about the initial influences of the SPL technique on the maintenance of existing iLM.
The text is organized as follows. Section 2 presents some approaches from the literature to the development of educational software, highlighting the main challenges focusing on code reuse. Section 3 describes existing iLM as a product family. The method and the development of the Domain Engineering are detailed respectively in sections 4 and 5. Section 6 reports current Application Engineering results and a first evaluation. The paper ends with some conclusions and future directions.
2. EDUCATIONAL SOFTWARE DEVELOPMENT AND CODE REUSE
Developing high quality educational software is expensive, time-consuming and is usually done in exceptional contexts, such as research projects at universities, by students without professional experience (Spalter and van Dam, 2003). Studies indicate that, in some cases of highly computer-managed learning, it can take more than 100 hours of programming for each hour of instruction (Aleven, McLaren, Sewall and Koerding, 2008). For being influenced by different factors in design and development in comparison with regular enterprise systems, educational software developers elaborated specific techniques for code reuse. In this section, we present some related work that report several of these factors and techniques.
Software used for educational purposes can be divided into three groups (Mor and Winters, 2007): (a) those intended to organize and to present content, such as LMS; (b) those intended to provide assignments, such as tutors and simulators; and (c) those not intended to be educational despite being used as such, such as text editors or Internet search engines. This categorization serves mainly to restrict the context of this analysis. This paper relies on the group of educational software which provides interactive assignments.
In fact, we are interested in the development of systems that provide domain-specific features to support teachers’ everyday work, as well as interactivity-intensive assignments to students. By domain-specific features we mean functionalities that use domain specificities in system design in order to improve learning. By interactivity-intensive assignments we mean the possibility of interacting with the assignment through specific types of interactivity, e.g. manipulate, construct and support (Sims, 1997, Tang, 2004). Manipulate interactivity allows the modification of domain-specific objects to simulate behavior and then make conjectures and tests. Construct interactivity allows the creation of objects before manipulation or simulation. These types of interactivity are essential to constructivist problem-based learning approaches (Albanese and Mitchell, 1993, Savery and Duffy 1995), which we value the most. Additionally, the support type of interactivity, which feedbacks students on their performance, provides many benefits to teachers and students (Tang, 2004). The feedback could be “right or wrong” information (Isotani and Brandão, 2008) or could be a more sophisticated dialog, such as those provided by Intelligent Tutoring Systems (Aleven et al., 2008).
A literature review shows several approaches to facilitate code reuse during the development of educational software. In the context of the ESCOT Project (Roschelle et al., 1998, Roschelle, Digiano, Chung, Repenning, Tager and Treinen, 2000), the task of authoring educational components was divided among teams of developers and teachers. Therefore, code reuse was based on the search for environments and authoring tools for assembling software components, which resulted in using a JavaBeans (Oracle, 2012) component repository to create small applications to a broad extent in middle and high-school curricula. Problems related to the development of educational software and their usage were reported by Spalter and van Dam (2003). Among others, they have identified problems related to team organization, the lack of programming skills and interoperability among components. Moreover they have pointed out issues related to the growth of intellectual property and problems of software usage for pedagogical purposes in schools. To overcome such problems, Spalter and van Dam (2003) have proposed a family of educational software called Exploratories. Each Exploratories application was built to support a specific knowledge domain, such as the circulatory system in Biology, and was (recursively) composed of code components in order to address interoperability and flexibility issues. However, the goal of independent sub-applications available on the web, where a regular teacher would assemble them for classroom use, was still far away.
In the same direction of using components and repositories to foster reuse, Bote, Hernandez, Dimitriadis, Asensio, Gomez and Vega (2004) worked with IMS Learning Design – IMS-LD (IMS, 2003) specification to make components interoperable and grid-based techniques to build a family of collaborative educational systems to provide domain-specific assignments to a computer architecture course. They adopted an approach in which the teacher could enter his or her students’ data and tailor the tool by using grid scripting to assemble IMS-LD components. On the contrary, our approach tries to reduce the amount of teacher work by removing the need to learn complex technologies, such as grid scripting.
An alternative method to foster reuse is to design a development process to create flexible components that can be reused in different educational contexts (Douglas, 2001, Muzio, Heins and Mundell, 2002, Boyle, 2003, Polsani, 2003). Thus, the whole system is reusable instead of just parts of the code. Generally they are supported by repositories of Learning Objects (LO) and other educational systems (Richards, Mcgreal, Hatala and Friesen, 2002, Nash, 2005). Pankratius, Stucky and Vossen (2005) proposed the reengineering of existing disconnected LO using Aspect Oriented Programming – AOP to reuse code during LO development. AOP was used to describe original LO and how to use them, or parts of them, to create new LO. These approaches solve many reuse problems, provide benefits to programmers and designers, but they are far from the teacher’s everyday work.
The example of LO used by Pankratius et al. (2005) is related to digital information products. This kind of LO fits in the group of educational systems that intend to organize and present content. A significant effort has been spent on developing techniques to increase the quality of digital information products and to reduce
the effort to develop them by reuse. These products do not have the same educational goals or computational structure as assignment-based educational software such as iLM. Nevertheless, some contributions from these works can be extended to the context of developing assignment-based systems, such as methods to foster code reuse and lessons learned from facing difficulties with managing people and setting requirements.
IMS-LD specification was also used to create a family of similar tools using a model-driven generative approach (Dodero and Díez, 2006). A feature model was used to list the available features that were mapped into models through IMS-LD files, which could be shared as LO. Additionally, the same specification was used during the instantiation of a framework for reengineering presentation of educational software (Choquet and Corbière, 2006). This framework models learning scenarios that can get existing systems to create new and more organized ones.
AOP was also adopted to provide reuse of content-intense systems (Ateyeh and Lockermann, 2006). In this work, AOP was applied to woven aspects similarly to those of a SPL, with domain engineering and course engineering (which has the role of application engineering in a SPL) detached. Domain engineering has been modeled using an ontology, and in each step there were content and didactics components. A courseware authoring tool was developed to produce LO, such as LMS modules and digital information products. Oberweis, Pankratius and Stucky (2007) proposed the full use of SPL to the creation and maintenance of digital information products. In the case of e-Learning Systems, Ahmed and Zualkernan (2011) reported a SPL that is structured to create systems that model entire courses on a given subject, using components repository and a process based on different views of assets.
In addition to code reuse, there are different educational software design proposals that consider contributions from other aspects, for instance, from content experts, teachers, instructional designers, institution practices, curriculum and usability (Mayes and Fowler, 1999, Douglas, 2001, Muzio et al., 2002, Sampson and Karampiperis, 2006). Furthermore, the related literature also highlights other aspects. An educational system should not be user-centered, in which the “user” has a domain knowledge and uses it with the system, but learner-centered, in which the “user” aims to develop a domain knowledge by using it (Quintana, Krajcik, Soloway and Norris, 2002). This implies deep graphical user interface and content structural changes. Interactivity is very important to educational software, and different types of interactivity must be considered to foster different types of learning (Tang, 2004), on which the whole system is based. Also, the tool must be in line with teacher’s instructional practices, and not establish new ones (Hinostroza, Rehbein, Mellar and Preston, 2000), since this could alter the system most basic requirements.
Finally, the literature presents many uses of software engineering techniques to enhance educational software development. These approaches contributed to our research with lessons learned and challenges to be faced. They propose the development of educational software only intended to present content while they do not support interactive assignments which is a key feature for such systems. Nevertheless, it is possible to learn from these approaches how to support code, architecture and process reuse. Unfortunately, few of them consistently report pros and cons, evaluation methods, or differences in development contexts (systems size, team size, team experience), limiting knowledge capitalization (Tchounikine, 2011).
In order to contribute to the field, our proposal adopts the SPL approach to deal with code, architecture and process reuse during the development of a family of educational software that is intended to provide domain-specific assignments with different types of interactivity, e.g. manipulate and construct interactivity (Sims, 1997). Such a family is described in the next section.
3. THE SOFTWARE FAMILY OF INTERACTIVE LEARNING MODULES
Our research group develops educational software intended to improve the learning and teaching processes mainly by facilitating teachers’ work and providing interactive assignments to students. These systems, called iLM, were developed following some guidelines to be compatible with a communication protocol of LMS (Rodrigues et al., 2010), but they were also conceived as single applications.
Prior to this work, five systems were built within the iLM family: iGeom, an Interactive Geometry System (Isotani and Brandão, 2008); iGraf, a system to study mathematical functions and graphics (do Prado, 2006); iCG is a system that emulates a computer with an embedded compiler; iComb, an educational counting
system (Eisenmann and Brandão, 2009); and iVProg, a visual programming system (Kamiya and Brandão, 2009). Fig. 1 shows some of their screens.
Although their development had followed some guidelines, they did not follow a systematic development process. For instance, iGeom has been developed since 2000. Currently, with five developers working on iGeom, it is at version 5 and it has 46,000 lines of code. The first deployment of iComb occurred in 2007 and it had 7500 lines of code written by two programmers. At present, the second version is being developed by a third developer. Therefore, their maintainability has become a hard task and the adoption of software engineering techniques is imperative for the group research and development success.

In order to decide what software engineering technique to adopt, a systematic analysis of existing iLM was conducted and some commonalities among them were observed so that we could characterize them as a family of similar software products. Thus, we decided to apply a SPL approach for the development of new iLM and the refactoring of existing ones.
During the systematic analysis of iLM, their core features were identified (Dalmon et al., 2011a):
- **Run in web-browsers** – by running in web-browsers, iLM are platform independent and can be used in classrooms as well as in distance education.
- **Communication with LMS** – under a simple protocol, iLM communicate with LMS in order to (a) open assignments files and (b) send the student’s assignment solution back to the LMS.
- **Authoring tools** – to allow the creation of assignments and the choice of a pedagogical approach. Usually, educational software adopts an underlying pedagogical approach that may limit the systems flexibility and content reuse for teachers.
- **Interactivity-intense assignments** – systems of the iLM family provide interactivity-intense assignments since users can create or modify domain-specific objects within assignments to simulate a behavior and then make conjectures and tests.
Besides the core features, we had identified some optional features exploited by the learning and teaching processes. Although these features were included in the SPL core, we kept them optional.
• **Automatic checking of assignments** – as an additional interactivity feature, feedback is one of the most important features in educational software (Hentea et al., 2003). In assignment-based systems, such as iLM, an automatic assessment feature can help both teachers and students. By using an iLM with such a feature embedded in an LMS, it is possible to store all the students’ results, and students can profit by checking whether their solution is correct. This raises students’ motivation and release teachers from the task of checking their assignments (Isotani and Brandão, 2008).
• **Intelligent tutoring** – Intelligent Tutoring Systems – ITS bring many benefits to educational practices (Koerdinger and Corbett, 2006). By using ITS features during the authoring of iLM assignments, teachers can increase the amount and quality of feedback interactivity provided by the system. In spite of being suggested, this feature is under development for an existing iLM (Dalmon, Brandão and Brandão, 2011b).
After specifying and defining the iLM software family, we detail the scope of the SPL approach in the next section.
4. **DOMAIN ENGINEERING METHOD FOR ILM**
This section presents the method used to develop the Domain Engineering of a Software Product Line (SPL) for iLM in order to allow a discussion of its influence on the development process in next sections. A SPL consists of methods and tools to define and to guide the creation of iLM, fostering code, architecture and process reuse (Clements and Northrop, 2001). It is composed of two parts, Domain Engineering in which code, architecture and process are developed for reuse, and Application Engineering, which makes use of code, architecture and process from Domain Engineering to develop iLM. The main goals of applying this technique for developing iLM are to reduce the effort during systems creation and maintenance, to improve systems quality and to provide systematic processes for design, implementing, testing and documenting.
The SPL approach affects four aspects of development: business, architecture, process and organization (Linden, Schmidt and Rommes, 2007). Business sets the main goals of the products that will be created by the SPL. Architecture defines the systems code structure, and where code reuse is more evident. Process establishes the methods, activities and steps along the development; and organization sets the tasks attribution to developers. Our focus lies on the architecture and on process aspects. The business aspect is defined as the approach taken by the research group, which is mainly to contribute to the community by providing open source tools, while the main goals of the iLM family is helping teachers and students. The organization aspect is defined by delegating tasks to graduate students and programmers with scholarships. Currently, the group consists of seven people, one for each iLM, one for the SPL, and two newcomers as additional programmers for iGeom and iVProg.
The method applied to the Domain Engineering for iLM is a slightly modified PLUS method (Gomaa, 2004). It was chosen mainly considering the team’s experience in UML-based software design and the availability of documentation, as there is no SPL expert in the team. PLUS states that the features of the aimed systems must be listed and classified as core (compulsory), variant (that varies from a range of possibilities) and optional (that can be chosen or not). Therefore, during application engineering, developers must choose which possibility of each variant feature and whether the system will have the optional features. Later, during the analysis step, classes must also be classified as core, variant and optional, which must reflect the previous features classification.
The change in PLUS was made in order to adapt the method to the iLM domain, because of the variability encountered among existing systems. Features are categorized as core, alternative or optional, but classes are only categorized as core or variant. This is due to the fact that in our systems each class only implements one feature, thus they can only be of types core or variant (mainly user interface and domain model classes), no matter whether the feature is core or optional. This simplifies implementation of individual components. Additionally, when core and optional features have only alternative behaviors, such as user interfaces, they are not considered alternatively in order to simplify the design and to separate user interface implementation from the other classes.
Moreover, the Spiral model of software development process (Bohem, 1986) was integrated to the Domain Engineering process, to define how the PLUS method would be applied. Fig. 2 depicts a schematic view of the used process. First, we defined the Domain Engineering scope, by describing the system family, the core requirements, core and optional features that will be provided as the preliminary design. Then, an iterative development step, including software analysis, design, implementation and testing, is performed to build the first Domain Engineering prototype. With this prototype, it is possible to start the development of iLM in Application Engineering. Whenever application engineering sets new requirements and features for Domain Engineering, it restarts an iterative development step, in order to provide new prototypes, or releases.
Fig. 2: Schematic view of the process used: SPL with PLUS method and Spiral models.
In this context, the PLUS method utilization started by listing the non-functional requirements of existing systems, then a feature analysis was made, categorizing the features into core or optional. Later, some desired features were added and categorized. The next step was use cases description for all features. During the analysis phase, UML class diagrams were created, categorizing classes into core or variant for each feature, followed by UML sequence diagrams for each use case. During design, groups of classes within features were organized into components, before implementation and testing.
An application framework was chosen for the Domain Engineering implementation. In this case, application engineering consists of the framework instantiation and specialization. Variability management at code level is performed with two types of variability points in the framework for building iLM: (a) groups of components that form an optional feature must be chosen, or not, to be part of the system; and (b) variant classes within components that define specific behaviors of the system by inheritance. Therefore, during application engineering, developers must choose which features the system will have, and the behavior of each of them by inheriting abstract classes of the framework.
In the next section, we describe the development of Domain Engineering, represented by the first version of the framework, and the detailed methods for application engineering.
5. DEVELOPMENT OF DOMAIN ENGINEERING FOR ILM
This section presents the development of Domain Engineering for building iLM. According to the Spiral process and PLUS method described in the previous section, it was conducted in four steps: requirements analysis, feature analysis, use case analysis and an iterative step of design, implementation and testing, resulting in the framework prototype. The four steps will be detailed next.
5.1. Requirements Analysis
During the preliminary design and the requirements phase, regarding the framework development, the analysis of desired and existing requirements resulted in the list below. Application engineering considers additional requirements, which are described later.
- **Documentation** – a Domain Engineering framework must be well documented so that it is possible to maintain it during domain application and to use it easily during engineering application.
- **Extensibility** – the framework for building iLM must be capable of absorbing new features and specific features of iLM as the family of systems grows.
- **Maintainability** – existing iLM have poor maintainability. One of the main goals of using Domain Engineering approach is to improve the code quality, which is key in this work.
- **Open source** – our project will follow an open source approach in order to provide free tools to educational institutions and to allow a community to develop iLM.
- **Platform compatibility** – they must be compatible with any operational system in order to be used by any educational institution.
- **Resource constraints** – some educational institutions in developing countries have outdated computational resources; hence, iLM must be lightweight and demand low processing power.
- **Reusability** – as Domain Engineering, the framework most important requirement is code reusability.
- **Testability** – to ensure maintainability and reusability, the framework code must be highly testable.
Existing iLM explicit requirements were only platform compatibility, resource constraints and open source. The additional requirements defined in this research mainly reflect systematic reusability in a software life cycle longer than two years.
5.2. **Feature Analysis**
The features of the iLM family were defined by mapping functionalities of existing iLM and some additional ones. Fig. 3 shows a feature model with the core and optional features described in section 3, divided into two levels of sub-features.

This diagram follows the FODA, **Feature Oriented Domain Analysis** (Kang, 1990) notation, in which an arc between features means alternative features and a circle means optional feature. An iLM has all mandatory features (which are provided by the framework), one of the alternative features (which is the iLM specific domain) and may have one or more optional features. A brief description of the sub-features is presented.
- **Domain Operations** – contains all domain-specific functionalities that must be defined during application engineering. It is an alternative feature; each iLM thus has a different implementation, such as geometry in *iGeom* and counting in *iComb*. This sub-feature implements domain-specific manipulate and construct types of interactivity.
- **Assignment Management** – the management of assignments is performed by this feature. It allows the user to author and edit assignments as a teacher, and to solve an assignment as a student. The modeling of assignments is domain independent, which allows this feature to be mandatory and provided by the framework.
- **Communication Management** – provides the functionality for opening and saving files and for communicating assignment data through the iLM protocol. These tasks can be entirely implemented during Domain Engineering, thus it will be independent of the specific data being transferred.
• **Configuration Management** – this feature manages the system configuration, with parameters such as language and teacher or student versions (to enable or disable assignment authoring). Configurable behaviors specified during application engineering can also use this feature.
• **Functionalities over Assignments** – this feature has operations over assignments that are being solved by the student or authored by the teacher. Examples are automatic checking of the student’s solution (which is provided by the framework, even though considered as optional) and exporting to images. Other functionalities may be included, such as exporting assignments as Learning Objects standard packages.
• **Functionalities over Domain Operations** – this feature manages the user’s domain operations during an assignment. It provides domain-independent functionalities that facilitate or improve manipulate and construct types of interactivity. For instance, it has sub-features of undo and redo, domain operations history, domain object list (which are mandatory) and others, such as scripts and intelligent tutoring.
There are many feature interactions among mandatory features, which are omitted in Fig. 3 for simplicity, and all of them depend on the existence of the **Domain Operations** feature. For instance, authoring and editing assignments (from **Assignment Management** feature) depend on reading and writing files and on the configuration of the teacher or student version. Since the framework handles all interactions among mandatory features, during Application Engineering, developers of iLM do not need to consider them. In the case of optional features, they can depend on each other (as **Intelligent Tutoring** depends on **Tutor Authoring**), but no mandatory or alternative feature depends on them.
All subsequent development adopting the PLUS method is highly dependent on this feature division. Next in the paper, feature means one of the groups of sub-features listed above. Use case analysis and each step during prototype development is also divided into these sub-features.
**5.3. Use Case Analysis**
For designing the framework, the use case analysis was conducted for each mandatory or core feature (since it will not provide alternative or optional features). As its result, five use case diagrams were created. Each use case, depending on its sub-feature, is classified as core or optional.
Fig. 4 shows, as an example, a combined use case diagram for the **Assignment Management** and **Functionalities over Assignments** features. Core sub-features are depicted in **bold** and optional sub-features in **italic**. We briefly describe its use cases below:

• **Assignment Solution** – the user playing the role of student opens the iLM with an assignment to be solved; the assignment file is provided by the LMS server which embeds the iLM.
• **Intelligent Tutoring** – in the case of an iLM and an assignment with intelligent tutoring features, when the file is opened, the tutor is also executed. After finishing the assignment, it sends tutoring data to the LMS server.
• **Automatic Checking** – when the student wants to check whether his or her solution is correct, if available, the automatic checking is launched. It sends the assignment result to the LMS which embeds the iLM. The result can be stored for further analysis.
• **Assignment Authoring** – the user opens the iLM playing the role of teacher. All features for assignment authoring are available to this role. The assignment file can be stored in the LMS server.
• **Tutor Authoring** – if the iLM has intelligent tutoring features, while authoring an assignment, the user can set the tutor behavior.
• **Assignment Editing** – as a teacher, the user can open assignment files to edit from the LMS server page. The available features are the same as in the Assignment Authoring use case.
• **Assignment Export** – the teacher may also, when available, export the assignment authored to standard specifications such as IMS-LD (IMS, 2003) or SCORM (Advanced Distributed Learning, 2004).
According to the adopted development process, having finished the first iteration of software analysis for Domain Engineering, the next step is to develop its first version, as described in the next section.
### 5.4. Framework development
After the use case analysis, the application framework development was composed of an iterative phase of software analysis, design, implementation and testing. The Domain Engineering of a SPL intends to provide code, architecture and process for reuse. The framework provides the code and architecture, while the method for its use provides a systematic reusable process for developing iLM. This section describes the iterative development steps, and then the results from each of the development iterations, including a discussion about the influence of the used method and some lessons learned.
Software analysis takes data from requirements and creates a coarse structure of the software. In this case, each use case diagram was analyzed individually in order to generate separated UML class diagrams. We define code components that had a one-to-one relation with features. Variability management was considered by choosing which classes had variant behaviors and which were constant. All diagrams had variant classes only on user interfaces, except the one modeling the **Domain Operations** feature.
In the last iterations, variability management had little impact on implementation, as the architecture got more concise and analysis was reviewed mainly to solve problems faced during implementation or to add more flexible or simpler project choices. The PLUS method was of great importance during conception but not during refinement. This may be due to the relative small size of the project and the number of people involved.
The design phase transforms the coarse architecture from analysis into a well defined set of communicating components. This was done using design patterns (Gamma, Helm, Johnson and Vlissides, 1995 and Gomaa, 2003) in the first iterations and refactoring techniques later (Fowler, Beck, Brant, Opdyke and Roberts, 1999 and Kerievsky, 2004). The main product of this phase, obtained in the last iterations, was a component architecture that reflected feature variability in a good manner. This was allowed by the PLUS method and refined design decisions incrementally, which were used to restrain variability management only to the analysis and design phases, making it more transparent during implementation. Consequently, implementation could deal with each component individually, no matter how it would be used during application engineering. It is important to highlight that this design level was not attained until the last iterations, and was a result of several implementation efforts and iterations.
The implementation phase generates code from the designed architecture, and was a key phase to identify when to start new development iterations. Testing phase was conducted along implementation with a small time offset. Because of design decisions, considerations over variability management reduced over time, together with the difficulty in programming.
Development took four main iterations, most of them dedicated to design the framework. At the first iteration, design was under specifying, which hindered implementation. In the second iteration, design activities took longer but the result was an over specifying design, which also impaired other phases. By the
third iteration, design was mature and most of the implementation was achieved. Finally, during the fourth iteration, some design flaws were corrected and the method for using the framework was simplified. For testing the framework, an iLM was created to serve as an example. This iLM-example has no pedagogical objectives and its functionalities were defined in order to instantiate the flexible points of the framework.
The proposed method to use the developed framework also matured throughout the iterations by getting more and more simple. Here, the PLUS method aided to model variability points which were implemented as hotspots (Fayad and Schmidt, 1997), such that the instantiation of different of these flexible points were similar. The framework started with many hotspots with no relation to each other and, as design was refined, hotspots were merged and were organized into three groups: domain model, domain user interface and plug-ins of functionalities over assignments and over domain operations. To document this method, we developed three manuals, in ascending order of technical depth: (a) How to instantiate the framework; (b) How to extend the framework with plug-ins; and (c) How the framework works internally. The most used was (a), which has a step-by-step nature, providing a systematic process for developing an iLM. Moreover, maintenance and evolution issues were considered throughout the manuals and code documentation.
Based on our experience in applying our process to a set of different learning systems, we have identified the most important characteristics of the framework, namely iterative design and implementation, a powerful method, good design decisions and improved by feedbacks from developers. Iterative design and implementation made explicit errors early, reducing the amount of rework and turning the fixing task easier. A powerful modeling method, such as PLUS, guided the early design, was over-used sometimes, and then turned almost transparent in later iterations with the help of good design decisions, which made implementation simpler. Lastly, documenting and the users’ opinion made visible some design that could be enhanced.
5.5. Framework current state
The application framework that implements the Domain Engineering has a component architecture, as shown in Fig. 5. This architecture can be divided into two groups: (a) the user interface, with the two components in the upper part of the diagram; and (b) the features, with six components, one for each feature in the feature diagram. Core components are shown in **bold font**, the variant components in *italic and underlined*, and the optional ones in *comic sans font*. The framework currently provides all core components, some abstract classes for the variant components, and some examples of components for the optional ones.

Each of the components is detailed as follows:
- **DomainUserInterface** – is composed of abstract classes that are Java Swing components, which must be inherited and specialized to provide domain specific behavior. The framework also provides functionalities to create buttons and to trigger domain operations.
• **BaseUserInterface** – this is an empty frame with basic and domain-independent functionalities that is responsible for initializing and for showing the **DomainUserInterface** component. Another responsibility is the management of each module user interfaces (the plug-ins).
• **DomainModel** – the component that provides the model on which the domain operations must be created. It is a group of abstract classes that model domain operations, objects and functionalities.
• **AssignmentControl** – a component for the management of assignments, which is also responsible for managing plug-ins. The main control class connects assignments with plug-ins, with the communication component and with the domain model.
• **SystemControl** – is responsible for initializing the whole system and for managing the configuration of features. It also provides the public interface that is used by LMS for external communication.
• **AssignmentModule** – is the component responsible for setting the plug-in architecture to modules that provide functionalities over domain operations. In addition to the provided architecture, the framework has three modules: undo/redo, history of domain operations and a list of domain objects. These modules can be used as examples or basis for the development of new plug-ins.
• **SystemModule** – is the component responsible for setting the plug-in architecture to modules that provide functionalities over assignments. The framework also provides an example of system module: the automatic checking module.
• **Communication** – this component has the functionalities related to communicating with other systems, such as saving and reading files, opening assignments and sending evaluations to LMS.
The current state of the framework has around 5,000 lines of code within 50 classes and 12 interfaces. Each component is a Java Package. All the features were been implemented, except for some details of teacher and student versions and other configuration parameters. The code is available as open source at http://ccsl.ime.usp.br/redmine/projects/ima/files.
Regarding the framework evolution and extension, the method proposes the inclusion of plug-in based functionalities, as AssignmentModule and SystemModule components. A manual was created to document the method in detail for this development. The proposed systematic method for using the framework to develop an iLM is presented in next section.
### 5.6. Method for instantiating the Framework
Application Engineering is the process of using the products of Domain Engineering to develop systems of the family, in this case, iLM. This section details the method of instantiating the application framework and using the systematic process provided by Domain Engineering.
First, one must know which specific domain the iLM will provide to teachers and students. Among the iLM features, the application framework provided by Domain Engineering does not have the domain operations and can be extended by functionalities over domain operations and assignments. Hence, in order to develop an iLM, in this phase one must define, within the chosen domain, what the domain operations are and if it will use plug-in based functionalities.
Examples of domain operations, in existing iLM, are: in iGeom, creating points, lines, circumferences, moving points, editing objects, reflecting objects to an axe; and in iGraf, creating functions, curves, points, editing these objects, animating them, etc. Moreover, there are two types of plug-in based functionalities: domain-specific and domain-independent. Domain-independent plug-ins, modules such as undo/redo and automatic assessment, are considered framework extensions as they can be developed during Domain Engineering. Nevertheless, it is possible that a certain domain needs specific functionalities, such as specific intelligent tutoring and specific export engines (e.g., exporting iVProg programs to programming languages). For this reason, domain specific plug-ins must be developed during Application Engineering.
Different cookbooks are proposed for each alternative or optional component in Fig. 5. In the case of **DomainModel** component, each domain specific operation must be modeled as a class inheriting **DomainAction** class, which is a Command design pattern (Gamma et al., 1995). These operations manipulate
objects of classes inheriting DomainObject class. The receiver of DomainAction objects is always the Singleton concrete DomainModel object, the abstract class of which is also provided by the framework. DomainModel implements all operations, it is the core of the iLM domain.
In the case of plug-ins, the modules of AssignmentModule and SystemModule components, implementation is different for each kind. If they implement the AssignmentModule interface, they are Observers of DomainActions and/or DomainObjects, so they must do something when an operation is triggered and/or an object is created or destroyed. If they implement SystemModule, its functionality manipulates an Assignment object, which has data of all DomainActions and DomainObjects, but also of propositions, other modules, etc. These modules also have access to communication functionalities provided by the framework.
DomainUserInterface is the remaining component. Its design can be produced as a standalone domain-specific user interface, which must be put together using the Strategy pattern. In the end, the connection of this user interface with the framework is made by inheriting the DomainGUI class. This class has some methods that were designed to connect the interaction mechanisms of the user interface with the DomainAction objects. Thus, for instance, when a button is pressed in DomainGUI, a DomainAction object is triggered, which calls a DomainModel method to execute the functionality.
Another step in designing DomainUserInterface component is the user interface for authoring assignments, which is also based on the Strategy pattern. The AuthoringGUI abstract class provided by the framework must be inherited to allow the final user, usually a teacher, to author domain-specific assignments for this iLM. This step is simply allowed by inheriting AuthoringGUI class and by implementing its abstract methods, which are specific for each datum of the Assignment object.
In summary, the suggested method for Application Engineering using the framework provided by Domain Engineering consists of: defining domain operations and objects, which are implemented as DomainAction or as plug-ins, and designing two user interfaces, the domain and the authoring one. In the end, the complete iLM consists of the framework, the chosen plug-ins, the objects of the domain model, and the specific user interfaces. This method is described in detail in the manuals provided with the framework and is also available (in Portuguese) with its code at http://ccsl.ime.usp.br/redmine/projects/ima/files.
6. RESULTS AND DISCUSSION
As mentioned in Section 1, the evaluation of complete results concerning an SPL and its products is a long term task. Nevertheless, since an SPL can be divided into Domain Engineering and Application Engineering, some intermediate results can be analyzed during each of the aforementioned phases. In fact, Domain Engineering may be analyzed through the work products that will be generated by following its associated process, the use of its underlying architecture and the provided code. Moreover, such analysis may be provided by the description of Application Engineering for the iLM SPL, or even part of it, associated with some metrics to evaluate what is already done.
Therefore, we analyze process, architecture and code reuse, and an estimative on quality and maintainability for each system, following some pre-established criteria. Such criteria consider that some existing iLM would be adapted to the proposed Domain Engineering in order to achieve the long term goals of improving quality for maintainability and evolution, and that some iLM would be built from scratch. Thus, process reuse would be analyzed by interviewing the developers before and after the use of Domain Engineering. Architecture reuse would be analyzed by comparing the new structure of the system with the previous one. Code reuse would be analyzed by evaluating how much of the code (%) could be discarded from the old system. Quality and maintenance could be estimated by requirements and maintainability analysis.
In this section, we describe how Application Engineering for the existing iLM is being conducted. We present current products of the development process and we discuss the corresponding results by highlighting some lessons learned. Currently, each iLM is being rebuilt or adapted in order to work with the framework. Also, a new iLM to support Genetics teaching and learning is in its early stage of development, and it has used the proposed method from the very beginning. Depending on the iLM specificities and developers’
profiles, their adaptation to the proposed Domain Engineering follows a different path towards the integration to the framework. The current stage of adopting the Domain Engineering to the existing iLM is described as follows.
*iGeom* is being adapted through disentangling the code, mainly between the user interface and the geometry model. The separation of concerns was made in order to make the system architecture compatible with that of the framework. Since *iGeom* is the oldest and the largest (46,000 lines of code), maintenance issues were common and justified the effort of restructuring. Two programmers with professional experience in programming are working on *iGeom*. They are refactoring the older version of *iGeom* by applying our Domain Engineering approach, good practices of programming and professional tools. Thus they have enhanced the development process and its products. Currently, *iGeom* is being integrated to the framework code.
With *iGraf* and *iComb*, adaptation is similar to *iGeom*, but in smaller scales. *iGraf* has around 15,000 lines of code (one third of *iGeom*) and was being restructured even before the Domain Engineering development due to maintenance issues. As the framework reached stability, this restructuring was adapted to follow its design. This task is performed by one developer with only academic experience in programming and it is now being finished in order to be integrated to the framework. On the other hand, the adaptation of *iComb*, with half the size of *iGraf*, also started with a non-experienced programmer and was delayed due to administration issues. The current stage is still at the beginning of separation of concerns and domain model specification.
*iVProg* is being rebuilt from scratch rather than adapted. Reasons for this includes the fact that *iVProg* was created based on Alice (Carnegie Mellon University, 2012), a well established educational software, that was simplified and adapted to be an iLM for 2 years. The current version of *iVProg* has around 37,000 lines of code, most of them as Alice’s legacy, which makes it very hard to maintain and to modify. In the last three months, one programmer with no professional experience is developing the new *iVProg* version, rebuilding it from scratch using Domain Engineering for the family. The domain model and the domain user interface of this new version are ready, now with good and clean design as guided by Domain Engineering. There was gain in productivity not only due to the use of Domain Engineering but also due to the reuse of the domain-specific feature design. The integration of the new *iVProg* to the framework code has just started.
In this context, process reuse analysis resulting from interviews with the developers shows that they came from ad-hoc development, in which requirements were defined at any time and features were designed directly on the code, to a guided development stated by the process provided by Domain Engineering. After the beginning of the restructuration process, they knew beforehand what to do, and it was possible to know where they were going in the long term. Consequently, development was more organized and satisfactory.
As far as code reuse is concerned, we can only estimate it since the refactoring of our learning systems is not yet completed. Still, architecture reuse has had the most important impact on the developers’ work. The percentage of code reuse decreases with the system size; *iGeom* has around 35% of code for domain independent features and system structure, while *iComb* has over 45%. *iVProg*, due to its legacy code structure, cannot be analyzed this way. The modularity of these systems increases when their architecture are restructured in order to be compatible with the framework, and the responsibilities of each component in the overall architecture gets clearer. A key point stated by *iGeom* and *iVProg* programmers is that with the provided architecture, they do not need to spend time thinking of how the system code should be organized, and this organization does not need to change over time due to including specific features.
The system quality may be evaluated through the requirements that were fulfilled. Since requirements that are common to the iLM family are provided by Domain Engineering, system quality that relies on them can be estimated by testing the framework. These tests are currently being conducted to assure this quality. Moreover, architecture reuse can affect the quality of domain-specific features but, since they are implemented with a previously tested structure, the tasks of specification, design and debugging are benefited. Maintainability is mainly dependent on documentation, architecture and code quality. On the one hand, for common structure and features, they are provided directly by Domain Engineering, being reviewed by all programmers that use it, raising its quality iteratively. On the other hand, they are guided by Domain
Engineering, which also allows the iterative revision. These considerations, added to the fact that restructuring leads to better quality systems from the initial stage of development, also contributes to making maintenance easier.
7. CONCLUSIONS
Interactive Learning Modules (iLM) have the potential to improve teaching and learning quality by providing adequate technology that meets teachers’ and students’ needs in both classroom and distance education settings. However, the development of this software family is complex and time-consuming, mostly because the lack of methods and processes that help its development. To overcome this problem, we proposed a Domain Engineering within a Software Product Line (SPL) approach to define and to guide the iLM development process.
To characterize the iLM software family, we conducted an initial analysis of five iLM developed to enhance learning in different domains (Geometry – iGeom, Mathematical Functions – iGraf, Counting – iComb and Programming – iCG and ivProg). This initial result helped to identify common and desired features that are essential to keep the functional consistency among them and it provided the foundations to build an application framework. With this framework, Domain Engineering provides documentation to foster process, architecture and code reuse during the development of iLM.
The main contribution of this work is the centralization of knowledge about the iLM family as the result of Domain Engineering, in the proposed application framework. Before that, knowledge was spread among existing systems, now detailed specifications and code can be shared among all iLM with the support of our framework. This is important in order to increase standardization among common functionalities of existing and new iLM and to facilitate the understanding of the systems developed in our research group by others. The proposed Domain Engineering provides code, architecture and process reuse, and code reuse usually gets more attention. Besides the importance of code reuse, our results show that architecture and process reuse have great influence on systems development, mostly if they were ad-hoc implemented before.
Research on evaluating the use of software engineering methods and techniques for the development of educational software is at its early stages. This work intends to disseminate the idea of using and evaluating these methods and techniques by showing preliminary results of the evaluation of applying a SPL approach to develop or to refactor iLM. In the long term, we expect to provide continuously better evaluation of the software engineering techniques used, while improving the educational software development process.
Future work consists of finishing the adaptation and rebuilding of existing iLM. After that, we could better analyze code reuse provided by Domain Engineering. Also, new iLM are being created from scratch using Domain Engineering, which can generate new development results as well as new data for studying its influence. As a long term goal, maintenance and evolution of existing iLM will be monitored in order to evaluate maintenance gains.
8. ACKNOWLEDGMENTS
Danilo L. Dalmon is supported by FAPESP under grant 2010/06805-2. This work was partially supported by FAPESP (2011/10926-2) and CNPq (550449/2011-6).
9. REFERENCES
Danilo L. Dalmon is supported by FAPESP under grant 2010/06805-2. This work was partially supported by FAPESP (2011/10926-2) and CNPq (550449/2011-6).
|
{"Source-Url": "https://www.ime.usp.br/~leo/artigos/Domain_Engineering_For_iLM_final.pdf", "len_cl100k_base": 11609, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 59075, "total-output-tokens": 12795, "length": "2e13", "weborganizer": {"__label__adult": 0.0006651878356933594, "__label__art_design": 0.0007381439208984375, "__label__crime_law": 0.0006022453308105469, "__label__education_jobs": 0.052154541015625, "__label__entertainment": 0.00013947486877441406, "__label__fashion_beauty": 0.0003600120544433594, "__label__finance_business": 0.0005202293395996094, "__label__food_dining": 0.0007214546203613281, "__label__games": 0.0013074874877929688, "__label__hardware": 0.001232147216796875, "__label__health": 0.0007157325744628906, "__label__history": 0.0005674362182617188, "__label__home_hobbies": 0.00020682811737060547, "__label__industrial": 0.0006303787231445312, "__label__literature": 0.0006651878356933594, "__label__politics": 0.00046539306640625, "__label__religion": 0.0009517669677734376, "__label__science_tech": 0.0087127685546875, "__label__social_life": 0.0002541542053222656, "__label__software": 0.00743865966796875, "__label__software_dev": 0.9189453125, "__label__sports_fitness": 0.0005207061767578125, "__label__transportation": 0.0009965896606445312, "__label__travel": 0.0003693103790283203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60332, 0.01436]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60332, 0.67904]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60332, 0.94549]], "google_gemma-3-12b-it_contains_pii": [[0, 3195, false], [3195, 7668, null], [7668, 12924, null], [12924, 17820, null], [17820, 20143, null], [20143, 24705, null], [24705, 28189, null], [28189, 31037, null], [31037, 34251, null], [34251, 38697, null], [38697, 41939, null], [41939, 46312, null], [46312, 50948, null], [50948, 55947, null], [55947, 60332, null], [60332, 60332, null], [60332, 60332, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3195, true], [3195, 7668, null], [7668, 12924, null], [12924, 17820, null], [17820, 20143, null], [20143, 24705, null], [24705, 28189, null], [28189, 31037, null], [31037, 34251, null], [34251, 38697, null], [38697, 41939, null], [41939, 46312, null], [46312, 50948, null], [50948, 55947, null], [55947, 60332, null], [60332, 60332, null], [60332, 60332, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60332, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60332, null]], "pdf_page_numbers": [[0, 3195, 1], [3195, 7668, 2], [7668, 12924, 3], [12924, 17820, 4], [17820, 20143, 5], [20143, 24705, 6], [24705, 28189, 7], [28189, 31037, 8], [31037, 34251, 9], [34251, 38697, 10], [38697, 41939, 11], [41939, 46312, 12], [46312, 50948, 13], [50948, 55947, 14], [55947, 60332, 15], [60332, 60332, 16], [60332, 60332, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60332, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
791ccc9418f7df0f56ed241c3720de3122c46e0d
|
Type-Directed Completion of Partial Expressions
Daniel Perelman
University of Washington
perelman@cs.washington.edu
Sumit Gulwani
Microsoft Research Redmond
{sumitg,tball}@microsoft.com
Thomas Ball
University of Washington
djg@cs.washington.edu
Abstract
Modern programming frameworks provide enormous libraries arranged in complex structures, so much so that a large part of modern programming is searching for APIs that “surely exist” somewhere in an unfamiliar part of the framework. We present a novel way of phrasing a search for an unknown API: the programmer simply writes an expression leaving holes for the parts they do not know. We call these expressions partial expressions. We present an efficient algorithm that produces likely completions ordered by a ranking scheme based primarily on the similarity of the types of the APIs suggested to the types of the known expressions. This gives a powerful language for both API discovery and code completion with a small impedance mismatch from writing code. In an automated experiment on mature C# projects, we show our algorithm can place the intended expression in the top 10 choices over 80% of the time.
Categories and Subject Descriptors D.2.6 [Software Engineering]: Programming Environments—Integrated Environments; D.2.13 [Software Engineering]: Reusable Software—Reuse Models; I.2.2 [Artificial Intelligence]: Automatic Programming—Program synthesis
General Terms Languages, Experimentation
Keywords program synthesis, partial expressions, code completion, type-based analysis, ranking
1. Introduction
Modern programming frameworks such as those found in Java and .NET consist of a huge number of classes organized into many namespaces. For example, the .NET Framework 4.0 has over 280,000 methods, 30,000 types, and 697 namespaces. Discovering the right method to achieve a particular task in this huge framework can feel like searching for a needle in a haystack. Programmers often perform searches through unfamiliar APIs using their IDE’s code completion, for example Visual Studio’s Intellisense, which requires the programmer to either provide a receiver or iterate through the possible receivers by brute force. Fundamentally, today’s code completion tools still expect programmers to find the right method by name (something that implicitly assumes they will know the right name for the concept, which may not be true) and to fill in all the arguments.
Our approach: We define a language of partial expressions, in which programmers can indicate in a superset of the language’s concrete syntax that certain subexpressions need to be filled in or possibly reordered. We interpret a partial expression as a query that returns a ranked list of well-typed completions, where each completion is a synthesized small code snippet. This model is simple, general, and precisely specified, allowing for a variety of uses and extensions. We developed an efficient algorithm for generating completions of a partial expression. We also developed a ranking scheme primarily based on (sub)typing information to prefer more precise expressions (e.g., a method taking AVerySpecificType rather than Object).
Code-completion problems addressed: We have used our partial expression language and its implementation for finding completions to address three code-completion problems:
1. Given k arguments and without distinguishing one as the object-oriented receiver, predict a method call including these and possibly other arguments. Note that the name of the method being called is not given; the method name, along with the order of arguments to it, is the output of our system.
2. Given a method call with missing arguments, predict these arguments (with simple expressions such as variables or field and property lookups of variables).
3. Given an incomplete binary expression such as an assignment statement, predict field and property lookups (i.e., given e predict e.f) on the left or right side of the operation.
Results: We demonstrate that our approach ranks the correct result highly most of the time and often outperforms or complements existing widely deployed technologies like Intellisense. To collect a large amount of empirical data, we have chosen to leave IDE integration and user studies to future work. Instead, we take existing codebases and run our tool after automatically replacing existing method calls, assignments, and comparisons with appropriate partial expressions. On our corpus of programs, results include:
• For over 80% of method calls (and over 90% if we know the call’s return type), there are two or fewer arguments to the call such that with only those arguments, our system will rank the intended method name within the top 10.
• If a simple argument (e.g., a variable) is omitted from a method call, our system can fill it back in correctly (the top-ranked choice) 55% of the time.
• When a field or property lookup is omitted from an expression, we can use surrounding type context to rank the missing property in the top 10 over 90% of the time.
Overall, our work demonstrates that IDEs could use already-available type information to help programmers find methods they want and save keystrokes much more than they do today.
1 Properties are syntactic sugar for writing getters and setters like fields.
The static ResizeDocument method is the first choice.
```
Point
this.BeginLocation
this.Center
this.EndLocation
DynamicGeometry.Math.InfinitePoint
shapeStyle.GetSampleGlyph()
.RenderTransformOrigin
this.shape.RenderTransformOrigin
this.ArcShape.Point
this.Figure.StartPoint
this.Shape.RenderTransformOrigin
```
**Figure 2.** The first ten results generated and ranked by our system for the query `?((img, size)).`
```
point
class of the DynamicGeometry library. There, point is the only local variable of type Point. In this case, the actual argument was `this.Center` which appears third in the list.
Synthesizing Field Lookups
For a more targeted version of the above, the search can be narrowed by specifying the base object to look under. We will consider synthesizing field lookups in the context of a comparison operator. The query “`Distance(point, ?)`” produces a list of Points that could be filled in as the second argument. This includes any locals, fields, or static fields or methods or recursively any fields of those of type Point. For example, Figure 3 shows the results of that query in the context of the EllipseArc class of the DynamicGeometry library. There, `point` is the only local variable of type Point. In this case, the actual argument was `this.Center` which appears third in the list.
```
PaintDotNet.Actions.CanvasSizeAction
.ResizeDocument(img, size, o, o)
PaintDotNet.Functional.Func.Bind(o, size, img)
PaintDotNet.Pair.Create(size, img)
PaintDotNet.Quadruple.Create(size, img, o, o)
PaintDotNet.Triple.Create(size, img, o)
```
2.2 Code Completion
Today, programmers can use code completion such as Intellisense in Visual Studio to try to navigate unfamiliar APIs. Intellisense completes code in sections separated by periods (“.”) by using the type of the expression to the left of the period and textually searching through the list for any string the programmer types. If there is no period, then Intellisense will list the available local variables, types, and namespaces. This often works well, particularly when the programmer has a good idea of where the API they want is or if there are relatively few choices. On the other hand, it performs poorly on our examples.
point.X >= this.P1.X
point.X >= this.P2.X
point.X >= this.Midpoint.X
point.X >= this.FirstValidValue().X
point.Y >= this.P1.Y
point.Y >= this.P2.Y
point.Y >= this.Midpoint.Y
point.Y >= this.FirstValidValue().Y
point.X >= this.Length
point.Y >= this.Length
Figure 4. The first ten results generated and ranked by our system for the query point.?.m >= this.?.m.
Synthesizing Method Names
Using Intellisense to find the nonexistent Shrink method, a programmer might type “img shr”, see that there is no “Shrink” method, and then skim through the rest of the instance methods. As that will also fail to find the desired method, the programmer might continue by typing in “PaintDotNet.” and use Intellisense to browse the available static methods, eventually finding PaintDotNet.Actions.CanvasSizeAction where the method is located. Hopefully documentation on the various classes and namespaces shown by Intellisense’s tooltip will help guide the programmer to the desired method, but this is dependent on the API designer documenting their code well and the documentation using terminology and abstractions that the programmer understands. A programmer would likely search through many namespaces and classes before happening upon the right one.
Synthesizing Method Arguments
If the user has already entered “Distance(point, ” and then triggers Intellisense, Intellisense will list of every namespace, type, variable, and instance method in context even though many choices will not type-check (as the programmer may intend to call a method or perform a property lookup on one of those objects). When the list is brought up, the most recently used local variable of type Point, which would be point in this case, will be selected. The programmer will have to read through many unrelated options to locate the other values of type Point.
Note that Eclipse’s code completion is actually significantly different in this scenario. It will list all of the local variables valid for the argument position along with common constants like null. If a more complicated expression is desired, the user has to cancel out and request the normal code completion which is similar to Visual Studio’s.
Synthesizing Field Lookups
Given “point.”, Intellisense will list all fields and methods of that object. The listing will go only one level deep: if the user wants a field of a field, they have to know which field to select first.
2.3 Prospector
The Prospector tool by Mandelin et al. [10] is an API discovery tool which constructs values using mined “jungloids” which convert from one input type to one output type and are combined into longer jungloids. The tool uses a local variable to construct a value of the output type. The motivating example in this prior work is converting an IFile to an ASTNode in the Eclipse API which requires a non-obvious intermediate step involving a third type: IFile file = ...;
ICompilationUnit cu =
JavaCore.createCompilationUnitFrom(file);
ASTNode ast = AST.parseCompilationUnit(cu, false);
(a) e ::= call | var.Name | e..fieldName | e:=e | e<e
call ::= methodName(e₁, ..., eₙ)
(b) ⌜ e ::= a | ? | φ
| ⌜ a ::= e | a..(?|?|φ|a..(?|?|φ) | ⌜ e:=e | ⌜ e≥e
call ::= ?({e₁, ..., eₙ}) | methodName(e₁, ..., eₙ)
Figure 5. (a) Expression language (b) Partial expression language
The Prospector UI triggers language only at assignments to variables, but that is a minor implementation detail.
Synthesizing Method Arguments
As Prospector can consider only one type as input, a programmer might query for a conversion from Size to Document or from Document to Document, which does not quite match the programmers intuition of wanting to resize the document. Prospector will return methods with arguments it cannot fill in. It prefers fewer unknown arguments, so ResizeDocument would likely be rather far down in the list of options for either query.
Synthesizing Field Lookups
Prospector does not take suggestions of starting points from the user, although its UI could theoretically be modified to do so. On the other hand, Prospector has only one target type and cannot make more complicated expressions like the one above with a >= operator. The closest corresponding use of Prospector would be to guess the type for either side of the comparison and have Prospector find fields of that type.
3. Partial expression language
Queries in our system are partial expressions. A partial expression is similar to a normal (or “complete”) expression except some information may be omitted or reordered. A partial expression can have many possible completions formed by filling in the holes and reordering subexpressions in different ways.
Complete expression syntax
Before defining partial expressions, we first define a simple expression language given by the e and call productions in Figure 5(a), which models features found in traditional programming languages. Our simple language has variables, field lookups, assignments, a comparison operator, and method calls. (Other operators are omitted from the formalism.) Also, the receiver of a method call is considered to be its first argument in order to simplify notation as when reordering arguments, an argument other than the first may be chosen as the receiver.
Partial expression syntax
Partial expressions are defined by the ⌜ e and ⌜ call productions in Figure 5(b). Partial expressions support omitting the following classes of unknown information:
- Entire subexpressions. ? gives no information about the structure of the expression, only that it is missing and should be filled in. On the other hand, ◦ should not be filled in: it indicates a...
subexpression to ignore due to being independent of the current query (so making it a question mark would only add irrelevant results) or simply being a subexpression the programmer intends to fill in later, perhaps due to working left-to-right.
• Field lookups. The field production defines a series of four question mark suffixes which are slightly different ways of saying that an expression is missing one or more field lookups or the desired expression is actually the result of a method call on the expression. The question mark suffix is short for “field” and can be completed as a single field lookup or nothing. The question mark suffixes complete as the question mark versions repeated as many times as needed.
• Simple method calls. The .?m suffix is like the .?f suffix. The ‘n’ is short for “zero-argument method call” and can be completed as a call to an instance method with zero additional arguments or also as a field lookup or nothing.
• Which method to call. ?(\(e_1, e_2\)) represents a call to some unknown method with two known arguments, which may themselves be partial expressions.
• Number and ordering of arguments to a method. For unknown methods, there may also be additional arguments missing or the arguments may be out of order, which is represented by the use of set notation for the arguments in ?(\(e_1, e_2\)).
Partial expression semantics
Figure 6 gives the full semantics of the partial expression language. The judgement nondeterministically takes a partial expression to a complete expression with the exception that any \(\_\) subexpressions remain. With the exception of the .? rules, each rule removes or refines some hole, making the partial expression one step closer to a complete expression. The bottom rule allows for the composition of other rules. The top leftmost rule allows any of the .? suffixes to be omitted. For type checking, \(\_\) is treated as a wildcard: as long as some choice of type for the \(\_\) works, the expression is considered to type check. The actual algorithm implemented does not use these rules exactly, although it matches their semantics.
The partial expressions language semantics never add operations like multiplication or new method calls (other than to zero-argument methods). The idea is that any place where computation is intended should be explicitly specified, and the completions simply list specific APIs for the computations. The exception for zero-argument methods is made because they are often used in place of properties for style reasons or due to limitations of the underlying language.
Examples
The first example from Section 2, \(\text{Point}(.\_\text{img, size})\), is a method call with an unknown name and two complete expressions as arguments. It can be expanded to any method that can take those two variables in any two of its argument positions, so \(\text{Point}(.\_\text{img, size})\) is a valid completion. Note that no attempt is made to fill in the extra argument. This is done to reduce the number of choices when recommending methods; for other applications fully completing the expression may be useful. The user may afterward decide to convert the \(\_\) to ? or some other partial expression.
Our second example from Section 2, \(\text{Point}.?\text{m}(.\_\text{img, size})\), can take one step to one of:
1. \(\text{Point}.?\text{m}(.\_\text{img, size})\).
2. \(\text{Point}.?\text{m}(.\_\text{img, size})\).
3. \(\text{Point}.?\text{m}(.\_\text{img, size})\).
or many other possibilities. Any local in scope or global (static field or zero-argument static method) could be chosen to appear before the .?m. Whatever is selected is completed to some expression of type Point. Any .? suffix can be omitted when completing an expression, so point.?m can be completed as point which is the first option in Figure 5. This .?m can also become one or more lookups by going to this.?m in one step and the .?m becomes some field. For \(\text{ArcShape}(.\_\text{this.}?)\), further completed to \(\text{ArcShape}(.\_\text{this.}?)\) of the completions mentioned so far would have been valid for .?f instead of .?m as well. On the other hand, for \(\text{shapeStyle}(.\_\text{this.}?)\), the first .?m from the .?m is completed with an instance method \(\text{GetSampleGlyph}()\) that returns an object with a field \(\text{RenderTransformOrigin}\) of type Point which the remaining .?m can complete to.
An unknown method’s arguments may themselves be partial expressions. For example, \(?(\text{strBuilder}(.\_\text{e.})?)\) could expand to \(\text{Append}(.\_\text{strBuilder, e.StackTrace})\) (which would normally be written as \(\text{strBuilder.Append(e.StackTrace)}\)).
The third example from Section 2, \(\text{point}.?\text{m} => \_\text{this.}?)\), also uses .?m, so the completions work as above, but, as there are two of them in the expression related by the =>, there must be a definition of => which is type compatible with the two completions. In this example, all the comparable fields have types int or double. But suppose \(\text{Point}.\_\text{has a field Timestamp of type DateTime\_}, then\_\text{Point.Timestamp} \_\text{this.P1.Timestamp} \_\text{has a valid completion, but Point.X} \_\text{this.P1.Timestamp would not.}\)
4. Algorithm
This section describes an algorithm (represented by the boxed section of Figure 4) for completing partial expressions. The algorithm takes a partial expression and an integer \(n\) as input and returns an ordered list of \(n\) proposed completions. The algorithm has access to static information about the surrounding code and libraries: the types of the values used in the expression, the locals in scope, and the visible library methods and fields. Bounding \(n\) is important because some partial expressions have an infinite list of completions. What constitutes a valid completion is defined by Figure 6.
The algorithm described in this section does completion finding and ranking simultaneously in order to compute the top \(n\) completions efficiently. Section 4.1 describes the ranking function. Section 4.2 describes the completion finder and the integrated algorithm whose design is informed by the ranking function.
score(expr) = ∑s∈subexp(expr) score(s) + ∑s∈subexp(expr) tdt(type(s) , type(param(s))) + 2 · dots(expr) + ∑s∈subexp(expr) abstype(s) − abstype(param(s))
score(call) = score(call) + (isNonLocalStatic(call) ∨ isNonLocalStatic(call)) + max(0, 3 − nsArgs(call) − receiver(call)) · \left|\bigcup_{s\in\text{argnames}(call)} \text{ns}(\text{type}(a))\right|
scorecmp(expr1, expr2) = score(expr1 < expr2) + 3 · (name(expr1) ≠ name(expr2))
nsArgs(call) = \{ a ∈ subexp(s) | type(a) is not primitive \}
Figure 7. The ranking function. Note that boolean values are considered 1 if true and 0 if false and that abstract types (abstype(·)) are considered not equal if both are undefined.
4.1 Ranking
This section defines a function that maps completed expressions that may contain subexpressions to integer scores. This function is used to rank the results returned by the completion finder in ascending order of the ranking score (i.e., a lower score is better). The function is defined such that each term is non-negative, so if any subset of the terms are known, their sum is a lower bound on the ranking score and can be used to prune the search space.
The computation is a sum of various terms summarized in Figure 7. score(·) applies to all expressions while scorec(·) is a specialized version with tweaks for method and scorecmp(·) is a specialized version with a tweak for comparisons. The computation is defined recursively, so for methods or operators with arguments, the sum of the scores of their arguments is added to the score. The scoring function incorporates several features we designed based on studying code examples and our own intuition. This section explains these features in detail. Section 5.4 evaluates each feature’s contribution to our empirical results.
Type distance The primary feature in the ranking function is “type distance”, for example from a method call argument’s type to the type of the corresponding method parameter. Informally, it is the distance in the class hierarchy, extended to consider primitive types, interfaces, etc. For example, if Rectangle extends Shape which extends Object, tdt(Rectangle,Shape) = 1 and tdt(Rectangle, Object) = 2. Far away types are less likely to be used for each other, so method calls and binary operations where the arguments have a higher type distance are less likely to be what the user wanted.
Formally, the distance from a type α usable in a position of type β to that type β, tdt(α, β), is defined as follows:
\[
tdt(α, β) = \begin{cases}
\text{undefined} & \text{no implicit conversion of } α \text{ to } β \\
0 & \text{if } α = β \\
1 & \text{if } α \text{ and } β \text{ are primitive types} \\
1 + \text{td}(s(α), β) & \text{otherwise}
\end{cases}
\]
s(α) is the explicitly declared immediate supertype of α which to minimizes tdt(s(α), β). Note that tdt(α, β) is used by the ranking function only when it is defined as that corresponds to the expression being type correct.
The type distance term is the sum of the type distances from the type of each argument arg to the type of the corresponding formal parameter param(arg). For method calls this is well-defined; binary operators are treated as methods with two parameters both of the more general type, so the type distance between the two arguments to the operator is used.
Depth The next term prefers expressions with fewer subexpressions. The ranking scheme prefers shorter expressions by computing the complexity of the expression which is approximated by the number of dots in the expression and multiplying that value by 2 to weight it more heavily. For example, dots(“this.foo” = 1 so it would get a cost of 2 while dots(“this.bar.To Baz()”) = 2 so it would get a cost of 4. To avoid double counting, any dots which are part of subexpressions are not counted here and instead are included via the subexpressions score term.
In-scope static methods Instance method calls will tend to have a type distance of zero for the receiver, so type distance has an implicit bias against static method calls. Noting that static methods of the enclosing type can be called without qualification, just like instance methods with this as the receiver, our ranking algorithm should similarly not disfavor such in-scope static methods. This is fixed by adding a cost of 1 if either the method is an instance method or the method is a static method that is not in scope.
Common namespace As related APIs tend to be grouped into nearby namespaces, the algorithm prefers calls where the types of all the arguments with non-primitive types and the class containing the method definition are all in the same namespace. Primitive types, including string, are ignored in this step because they are used with varying semantics in many different libraries. Furthermore, deeper namespaces tend to be more precise so a deep common namespace indicates the method is more likely to be related to all of the provided arguments. Specifically, the algorithm takes the set of all namespaces of non-primitive types among the arguments, treats them as lists of strings (so “System.Collections” is “System.Collections”) finds the (often empty) common prefix, and uses its length to compute the “namespace score”. To avoid this boosting the scores of instance calls with only one non-primitive argument, the similarity score is 0 in that case.
In order to have the namespace similarity term be non-negative, namespace similarities are capped at 3, and 3 minus the length of the common prefix is used as the common namespace term.
Same name Comparisons are often made between corresponding fields of different objects. Whether two fields have corresponding meanings can be approximated by checking if they have the same name. That is, p.X is more likely to be compared to this.Center.X than to this.Center.Y. To capture this, a 3 point penalty is assigned to comparisons where the last lookups on the two sides do not have the same name. The value is intentionally chosen to be greater than the cost of a lookup, so a slightly longer expression that ends with a field of the right name is considered better than a shorter one that does not.
Abstract type inference
We now introduce an important refinement to the basic ranking function that partitions types into “abstract types” based on usage, which is particularly important for commonly used types like string. Abstract types may have richer semantics than string such as “path” or “font family name”. Our approach is based on the Lackwit tool that infers abstract types of integers in C[11].
Abstract types are computed automatically using type inference. An abstract type variable is assigned to every local variable, formal parameter, and formal return type, and a type equality constraint is added whenever a value is assigned or used as a method call argument. As all constraints are equality on atoms, the standard unification algorithm can be implemented using union-find.
In order to avoid merging every abstract type .ToString() or .GetHashCode() is called on, methods defined on Object are
treated as being distinct methods for every type. All other methods have formal parameter and formal return type terms associated with their definition which are shared with any overriding methods. A more principled approach might involve a concept of subtyping for abstract types, but that would greatly complicate the algorithm for what would likely be minimal gain.
For example, consider the following code from Family.Show[
```csharp
string appLocation = Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments),
App.ApplicationFolderName);
if (!Directory.Exists(appLocation))
Directory.CreateDirectory(appLocation);
return Path.Combine(appLocation,
Const.DataFileName);
```
Directory.Exists, Directory.CreateDirectory, and Path.Combine take appLocation as their first argument, so the analysis concludes their first arguments are all the same abstract type. Furthermore, from the first statement, that must also be the abstract type of the return values of Path.Combine and Environment.GetFolderPath. On the other hand, there is no evidence that would lead the analysis to believe the second argument of Path.Combine is of that abstract type, instead App.ApplicationFolderName and Const.DataFileName are believed to both be of some other type. Intuitively, a programmer might call those two types "directory name" and "file name".
In the ranking function, the type distance computation is refined by adding an additional cost of 1 if the abstract types do not match.
### 4.2 Completion finder
This section presents a general algorithm for computing the top ranked completions of a partial expression, first giving a naive implementation and then discussing optimizations. The main logic is Algorithm 1 which returns a generator that returns all completions of a partial expression in order by score. The `yield return` statement returns a single completion, and when the next completion is requested, execution continues on the next statement. The first `n` elements of `AllCompletions(c)` are the top `n` ranked completions of `c`.
Note that for any partial expressions containing `?.f` or `?.m`, this generator will usually continue producing more completions forever, but can be called only `n` times to get just the top `n` completions. It may be easier to first read the algorithm while ignoring the `score` variable, which is necessary to handle the unbounded result set for `?.f` or `?.m`. Then it is a simple recursive algorithm which computes every possible completion of its subexpressions and uses those completions to generate every possible completion of the entire expression (e.g. all methods that can take those arguments). Note that `?` is interpreted as `vars.s` or `?.m` where `vars.s` is a special subexpression whose list of completions is every local and global variable in scope.
We now discuss various useful optimizations.
### Cache subexpression scores
A subexpression’s score will be needed for every completion it appears in. To compute it only once, the algorithm is redefined such that it returns a set of pairs of completions and their scores.
### Compute completions not in score order
In the algorithm given above, completions with a score not equal to score are discarded and regenerated later. To avoid that work,
Methods are a prime candidate for indexing as there are many methods and few that take a specific type. Although the current implementation does not do so, queries for multiple field lookups could also be made more efficient using an index that indicates for each type which types are reachable by a .?*f or .?*m query, how many lookups are needed, and which lookups can lead to a value of that type. For example, a Line type with Point fields p1 and p2 and a GetLength() method would have an entry denoting that the type double is reachable in ≥ 2 lookups using a .?*f query with the next lookup being one of p1 or p2 while it is reachable in ≥ 1 lookup using a .?*m query with the next lookup being one of GetLength(), p1, or p2.
Avoid computing type-incorrect completions
If the possible valid types for the completions were known, then the type reachability index would be more useful; otherwise results of every type have to be generated anyway for completeness. At the top level, the context will often provide a type unless the expression being completed is the initial value for a variable annotated only as var. On the recursive step of the algorithm, the possible types may not be known or may not be precise enough to be useful; there are methods that take multiple arguments of type Object, so even knowing one of the argument types does not narrow down the possibilities for the rest. On the other hand, binary operators and assignments are relatively restrictive on which pairs of types are valid, so enumerating the types of the completions for one side could significantly narrow down the possibilities for the other side.
Grouping computations by type
Which completions are valid is determined solely by the types of the expressions involved. Hence, instead of considering every completion of every subexpression separately, the completions of each subexpression can be grouped by type after grouping by score to reduce the number of times the algorithm has to check if a given type is valid in a given position. This also allows type distance computations to be done once for all subexpressions of the same types. Any remaining ranking features are computed separately for each completion as grouping by them is no faster than computing their terms of the ranking function.
5. Evaluation
We implemented the algorithm described using the Microsoft Research Common Compiler Infrastructure (CCI) [1]. CCI reads .NET binaries and decompiles them into a language resembling C#. Unfortunately, we were unable to work on actual source code because at the time the experiments were performed, no tools for analyzing the source code of C# programs existed—even if they did exist, open source C# programs are relatively rare.
We performed experiments where our tool found expressions in mature software projects, removed some information to make those expressions into partial expressions, and ran our algorithm on those partial expressions to see where the real expression ranks in the results.
All experiments were run on a virtual machine allocated one core of a Core 2 Duo E8400 3GHz processor and 1GB of RAM.
One minor issue is that any precomputation, specifically abstract type inference, would see the expression we are trying to recreate when in actual practice the expression would not yet exist. To avoid this situation, we re-run abstract type inference for each expression, eliminating the expression and all code that follows it in the enclosing method—we do consider the rest of the program.
We describe three case studies whose significance we have previously discussed in Section 2 and show that the ranking scheme is effective and the algorithm is efficient. After that, we analyze the importance of the individual ranking features in Section 5.4. Finally, we discuss threats to validity in Section 5.5.
5.1 Predicting Method Names
Our first experiment shows that queries consisting of one or two arguments can effectively find methods. We ran our analysis on 21,176 calls across parts of seven C# projects listed in Table 1. We generated queries by finding all calls with ≥ 2 arguments (including the receiver, if any) and giving one or two of the call’s arguments to the algorithm. We evaluated the algorithm on where in the results the algorithm found the correct method. While the correct result as the first choice is ideal, we do not consider it necessary for usefulness since users can quickly skim several plausible results.
Figure 9 shows the results overall and partitioned between static and instance calls. Almost 85% of the time, the algorithm is able to give the correct method in the top 10 choices. An additional 5% of the time, the correct method appears in the next 10 choices out of a total of hundreds of choices on average.
Notably, the algorithm correctly identifies instance calls more often than static calls. This is not too surprising as the search space is much larger for static calls. This might also indicate that the current heuristics prefer instance calls more strongly than they should.
Unfortunately, we cannot algorithmically determine which argument subset a user would use as their search query. Instead, we show that usually for some set of no more than 2 arguments the correct method is highly ranked. Our intuition, which would need a user study to validate fully, is that evaluating our approach
5.2 Predicting Method Arguments
Our second experiment investigated how often arguments to a method could be filled in by knowing their type. Looking at the same method calls as the previous experiment, for each argument in each call, a query was generated with that argument replaced with ?. There were a total of 69,927 arguments across the 21,176 calls. 23,927 were considered not guessable due to having an expression form that our partial expression completer does not generate like an array lookup or a constant value. Figure 13 shows how well our algorithm is able to predict method arguments, with the lower line ignoring the low-hanging fruit of local variables. Over 80% of the time, the algorithm is able to reduce the number of choices a user would have to sift through compared to Intellisense even if the user knew the correct receiver.
Second, the Intellisense results are listed in alphabetic order which is likely easier to skim through than the results from our tool which will be ordered by their ranking scores. The take-away is not that our tool is “better” than Intellisense; they serve different purposes. Instead, we wanted to show that our tool is often able to greatly reduce the number of choices a user would have to sift through compared to Intellisense even if the user knew the correct receiver.
As a caveat, these times do not include running the abstract type inference algorithm. That could take as long as several minutes for a large codebase but can be done incrementally in the background. These times were measured using CCI reading binaries as opposed to getting the information from an IDE’s incremental compiler. How that affects performance is unclear, but any such effects were minimized by memoizing a lot of the information from CCI, so the vast majority of the time was spent in our algorithm.
About 45% of the time, our position is at least 10 higher than it is with Intellisense. Since Intellisense displays at most 10 results at a time, this means it is not initially displayed by Intellisense.
the ranks is oversimplifying the comparison. First, the different tools have different inputs. Our tool does not require the receiver but is helped by being provided a second argument. Second, the Intellisense results are listed in alphabetic order which is likely easier to skim through than the results from our tool which will be ordered by their ranking scores. The take-away is not that our tool is “better” than Intellisense; they serve different purposes. Instead, we wanted to show that our tool is often able to greatly reduce the number of choices a user would have to sift through compared to Intellisense even if the user knew the correct receiver.
Figure 12 shows a similar comparison to the one in Figure 11 except that our algorithm additionally knew the desired return type (or void) and only suggested methods whose return type matched. The assumption of a known return type is not used elsewhere both because, in the context of API discovery, the user may often not know what return type to use, and the var keyword in C# and equivalents in other languages allow a user to omit return types.
Comparison to code completion
Figure 11 compares our ranking algorithm to Intellisense. The y-axes are read as the left side measuring the proportion of calls our system did better on and the right side measuring the proportion of calls Intellisense did better on.
We modeled Intellisense as being given the receiver (or receiver type for static calls) and listing its members in alphabetic order. Intellisense knows which argument is the receiver but is not using knowledge of the arguments. It was considered to list only instance members for instance receivers and only static members for static receivers. Given this ordering, we were able to compute the rank in the alphabetic list of the correct answer. We then subtracted that rank from the rank given by our algorithm, so negative numbers mean our algorithm gave the correct answer a higher rank.
5.2 Predicting Method Arguments
Our second experiment investigated how often arguments to a method could be filled in by knowing their type. Looking at the same method calls as the previous experiment, for each argument in each call, a query was generated with that argument replaced with ?. There were a total of 69,927 arguments across the 21,176 calls. 23,927 were considered not guessable due to having an expression form that our partial expression completer does not generate like an array lookup or a constant value.
Figure 13 shows how well our algorithm is able to predict method arguments, with the lower line ignoring the low-hanging fruit of local variables. Over 80% of the time, the algorithm is able to suggest the intended argument as one of the top 10 choices given out of an average of hundreds of choices.
Use of expressions other than local variables in argument positions is common as shown in Figure 14. Programmers must somehow discover the proper APIs for these expressions: Intellisense
"Choose from the best possible subset of arguments is reasonable because programmers are capable of identifying the most useful arguments (e.g., PreciseLibraryType instead of string or Pair)."
Figure 10 shows that a single argument is often enough for the algorithm to determine which method was desired, in this case defined as putting the method in the top 20 choices. Not shown in the graph is that adding a third argument leads to only negligible improvement in these results; note that even knowing all of the arguments to a method might not be enough to place it in the top 20 choices. Above the bars is the percentage of calls the algorithm is able to achieve. The Intellisense results are listed in alphabetic order which is likely easier to skim through than the results from our tool which will be ordered by their ranking scores. The take-away is not that our tool is “better” than Intellisense; they serve different purposes. Instead, we wanted to show that our tool is often able to greatly reduce the number of choices a user would have to sift through compared to Intellisense even if the user knew the correct receiver.
Figure 12 shows a similar comparison to the one in Figure 11 except that our algorithm additionally knew the desired return type (or void) and only suggested methods whose return type matched.
Comparison to code completion
Figure 11 compares our ranking algorithm to Intellisense. The y-axes are read as the left side measuring the proportion of calls our system did better on and the right side measuring the proportion of calls Intellisense did better on.
We modeled Intellisense as being given the receiver (or receiver type for static calls) and listing its members in alphabetic order. Intellisense knows which argument is the receiver but is not using knowledge of the arguments. It was considered to list only instance members for instance receivers and only static members for static receivers. Given this ordering, we were able to compute the rank in the alphabetic list of the correct answer. We then subtracted that rank from the rank given by our algorithm, so negative numbers mean our algorithm gave the correct answer a higher rank.
Figure 10. Each bar represents all calls analyzed with the number of arguments. The sections of the bar correspond to how many of those arguments the algorithm needed to put the original call in the top 20 results.
Figure 11. Difference in rank between our algorithm and Intellisense by choosing for the best possible subset of arguments is reasonable because programmers are capable of identifying the most useful arguments (e.g., PreciseLibraryType instead of string or Pair).
Figure 10 shows that a single argument is often enough for the algorithm to determine which method was desired, in this case defined as putting the method in the top 20 choices. Not shown in the graph is that adding a third argument leads to only negligible improvement in these results; note that even knowing all of the arguments to a method might not be enough to place it in the top 20 choices. Above the bars is the percentage of calls the algorithm was able to guess using only two arguments, which is high for any number of arguments. The intuition is that most of the arguments are not important, although there are also more opportunities for an argument to be of a rarely used type. The low value for 10 argument calls is due to there being very few such calls and most of them being from a large family of methods which all have the same method signature.
Comparison to code completion
Figure 11 compares our ranking algorithm to Intellisense. The y-axes are read as the left side measuring the proportion of calls our system did better on and the right side measuring the proportion of calls Intellisense did better on.
We modeled Intellisense as being given the receiver (or receiver type for static calls) and listing its members in alphabetic order. Intellisense knows which argument is the receiver but is not using knowledge of the arguments. It was considered to list only instance members for instance receivers and only static members for static receivers. Given this ordering, we were able to compute the rank in the alphabetic list of the correct answer. We then subtracted that rank from the rank given by our algorithm, so negative numbers mean our algorithm gave the correct answer a higher rank.
Speed For 98.9% of the calls analyzed, the query with the best result ran in under half a second, which is fast enough for interactive use.
As a caveat, these times do not include running the abstract type inference algorithm. That could take as long as several minutes for a large codebase but can be done incrementally in the background.
These times were measured using CCI reading binaries as opposed to getting the information from an IDE’s incremental compiler. How that affects performance is unclear, but any such effects were minimized by memoizing a lot of the information from CCI, so the vast majority of the time was spent in our algorithm.
5.2 Predicting Method Arguments
Our second experiment investigated how often arguments to a method could be filled in by knowing their type. Looking at the same method calls as the previous experiment, for each argument in each call, a query was generated with that argument replaced with ?. There were a total of 69,927 arguments across the 21,176 calls. 23,927 were considered not guessable due to having an expression form that our partial expression completer does not generate like an array lookup or a constant value.
Figure 13 shows how well our algorithm is able to predict method arguments, with the lower line ignoring the low-hanging fruit of local variables. Over 80% of the time, the algorithm is able to suggest the intended argument as one of the top 10 choices given out of an average of hundreds of choices.
Use of expressions other than local variables in argument positions is common as shown in Figure 14. Programmers must somehow discover the proper APIs for these expressions: Intellisense
"Choose from the best possible subset of arguments is reasonable because programmers are capable of identifying the most useful arguments (e.g., PreciseLibraryType instead of string or Pair)."
only suggests local variables given an argument position. The “not
guessable” expressions are those that involve constants or computa-
tion like an addition or a non-zero argument method call that could
be guessed by neither our technique nor Intellisense. Our partial ex-
pression language captures more of the expressions programmers
use as arguments including field/property lookups which are rela-
tively common and require browsing to find using Intellisense.
As our experiments are on decompiled binaries and not the orig-
inal source, these arguments may not be exactly what the program-
ner wrote. In particular, expressions might be stored in temporary
variables that they did not write or temporaries they did write might
be removed, putting their definition in an argument position.
Speed Our tool is capable of enumerating suggested arguments in
under a tenth of a second 92% of the time and under half a second
over 98% of the time, which is fast enough for an interactive tool.
5.3 Predicting Field Lookups
Our third experiment determines how often field/property lookups
could be omitted in assignments and comparisons (on either side).
Our corpus includes 14,004 assignments where the target ends
with a field lookup, 7,074 where the source does, and 966 where
both do. For those assignments, Figure 13 shows the rank of the
correct answer when our algorithm was given the assignment with
the final field lookups removed and $\cdot \_m \_m$ added to the end of both
sides of the assignment. The correct answer was in the top 10
choices over 90% of the time when one field lookup was removed,
but only about 59% of the time when a field lookup was removed
from both sides, going up to 75% when considering the top 20
choices. There were a total of dozens of choices on average.
Our corpus includes 620 comparisons where the left side ends
in a lookup, 162 of which end in two lookups; 620 comparisons
where the right side ends in a lookup, 174 of which end in two
lookups; and 125 where both sides end in a lookup. Of those,
Figure 16 shows the ranks our tool gave to the expression in the
target given the query containing the original expression with the
lookups removed and $\cdot \_m \_m$ added to the end of both sides.
The numbers are significantly better than for assignments be-
cause there are fewer possibilities: few types support comparisons.
One lookup can be placed within the top 10 for nearly every in-
stance in our corpus. If we allow 20 choices, then two lookups
where one lookup is on each side can be guessed 89% of the time
while two lookups on the same side can be guessed 85% of the
time if they are on right and 69% of the time of they are on the
left. The discrepancy between the latter two appears to be that com-
parisons against constants are usually written with the complicated
expression on the left and the constant on the right, and the name
matching feature is not helpful for comparisons to constants.
Speed 99.5% of these queries ran in under half a second.
5.4 Sensitivity analysis of ranking function
To see which parts of the ranking function were most important,
we re-ran the experiments with various modified ranking functions.
Each modified version either included only one of the terms or
left out one of the terms, in addition to versions that left out and
included both the type distance term and the abstract type term.
Table 2 shows the data for the proportion of expressions where the
correct answer was in the top 20 choices for different variants of
the ranking function for each of the experiments.
Methods Type distance and abstract type distance are the only
features that matter. Leaving out the namespace and in-scope static
terms seems to make almost no difference. Furthermore, the two
type distance terms separately are both good, with abstract type
distance alone being a little better, but not quite as good as the two
together, confirming that both are useful.
Arguments It seems that only the depth feature seems to matter.
Leaving it out makes the results much worse while leaving any
other term out has almost no effect. In fact, looking at the “$+$d”
column, using just the depth term gives almost exactly the same results as the full ranking scheme.
**Assignments** For just one lookup removed from either side, once again only depth matters, but when a lookup is missing from both sides, the type distance computation becomes important. In fact, in the case of a lookup missing from both sides, leaving out the depth component improves the results. This is not too surprising as there are likely many possible assignments which require adding only one lookup to either side. The interesting part is that apparently these lookups can be distinguished from the proper one by looking at more detailed type information (recall that only assignments which are type correct are even being considered).
**Comparisons** Depth once again seems to be most important. Except on the “2xRight” row, depth appears to be the only significant feature. The different values for that row vary little, indicating that each ranking feature is somewhat useful, but there is little gain from combining them. On average, there were hundreds of type-correct options, so the ranking function is definitely doing something to place the correct option in the top 20.
### 5.5 Threats to validity
As the experiments were run on decompiled code instead of actual source code, they may not apply to how programmers actually write code. Particularly, the decompiled code may have simpler expressions due to a compiler factoring out additional local variables from complex expressions. This did not appear to be the case from looking at code being analyzed as non-trivial expressions were visible like method calls and binary operations in method argument positions. On the other hand, the decompiled code looked different across projects (specifically, some projects had local variables with names like “local0” while others had actual names), so there may be some compiler-dependence involved.
Working on completed projects as opposed to codebases in the process of being developed means that abstract type inference algorithm may have had more information than it would have had in a real development scenario. Note that since the rest of the features work only on the current expression, they are unaffected by the maturity of the codebase. On the other hand, more development likely corresponds to more APIs existing in the codebase which likely corresponds to more APIs existing in the codebase which matures code examples from web searches.
### 6. Related Work
Prospector[10] is perhaps the closest related work. With Prospector, as discussed in Section 2.5, a user makes a query for a conversion from one type to another and gets what the authors call a “jungloid” which is a series of operations including method calls, field lookups, and downcasts from examples in the code. That paper noted that shorter jungloids tend to be more likely to be correct and also that jungloids that cross package boundaries are less likely to be correct, both of which are ideas used by our ranking function.
PARSEWeb[17] performs the same task as Prospector except it mines code examples from web searches.
InSynth[6] also produces expressions for a given point in code using the type as well as the context to build more complicated expressions using a theorem prover. InSynth’s ranking algorithm...
is based on machine learning from examples. It, like Prospector, differs from our work in that it generates expressions from scratch with no input from the programmer to guide it. Their evaluation was on small snippets of Java example code translated to Scala which is difficult to compare to our evaluation on mature C# projects.
Typsy searches for APIs by generating expressions involving any number of method and constructor calls and field lookups given a list of arguments, a return type, and a library package to search within. Typsy will only return expressions with all arguments filled in, so it will generate expressions to construct any missing arguments for methods it finds. The expressions are ranked by their size similar to the depth term in our system, although our depth term does not count the number of method and constructor calls because it will not generate new ones not specified by the programmer.
API Explorer supports queries both for methods taking a given argument and for how to construct a value of a given type. When querying for methods, a keyword can also be provided, so the results are filtered to contain only methods with synonyms of that keyword in the name. The ordering of the results uses a computation similar to our type distance feature. Both types of queries can be expressed in our partial expressions language, except we do not have a way to filter by keywords, and the version used for our experiments does not generate constructor calls when asked for an unknown method.
Strathcona and XSnippet both use context to produce queries which may be helpful to the programmer. In a similar vein, CodeBroker performs searches for APIs based on the documentation of the method currently being written in order to recommend APIs the user may not even be aware of.
Little and Miller propose a system using “keyword programming” to generate method calls where the user gives keywords and the system generates a method call that includes arguments that have most or all of the keywords. Their system attempts to be closer to natural language than ours at the cost of a lower success rate.
Hou and Fletcher recommend various ways of filtering and sorting APIs to show the most relevant choices first. Their system is mainly based on manual annotations of APIs as well as considering how often an API is used. Their work is complementary as it could be used to filter out irrelevant methods from our results.
Searching for functions by type has been recommended for functional programming languages. Those proposals differ in that the type signature alone, along with modifications to, for example, handle both curried and uncurried functions, tends to be sufficient for a search. In imperative languages with subtyping, inexact matches are more likely to be meaningful and side-effects make it more likely that many options have the same type.
For discovery of entire modules at once, specification matching can search by specification. Semantics-based code search similarly searches based on specifications including tests and keywords but additionally may make minor modifications to the code to fit the details of the specification.
SNIFF returns snippets matching natural language queries by mining multiple examples from existing code, matching them based on the documentation of the APIs they use, and combining them based on their similarities to eliminate the usage-specific parts of the snippets. Unlike our algorithm, this technique requires the API being searched to be well-documented.
Matcher handles API discovery at a different scale: given two types, it generates the glue code to connect those two types by generalizing examples from existing code.
Program sketching is a form of program synthesis where the programmer writes a partial program with holes and provides a specification the solution must satisfy. Our technique is similar but considers only a single expression at a time and avoids the need for an explicit specification by using type information to filter the results.
7. Conclusions and Future Work
This paper has shown that type-directed completion of partial expressions can effectively fill in short code snippets that are complicated enough to be difficult to discover using code completion. Furthermore, our ranking scheme is able to sift through hundreds of options to often place the correct answer among the top results.
Future work would be to implement an IDE plug-in and perform a user study to determine if it is useful in real development situations as well as possibly seeing if developers have other ideas for how such a plugin could be used or for similar ideas for lightweight searches. Extending the algorithm to other programming languages is also future work. The features are at least partially tied to C#/Java and will need to be adapted to make sense in other languages.
Acknowledgments
This work was funded by a grant from Microsoft Research. We thank the anonymous reviewers for their valuable feedback.
References
|
{"Source-Url": "http://homes.cs.washington.edu/~djg/papers/pldi12.pdf", "len_cl100k_base": 12335, "olmocr-version": "0.1.49", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 42200, "total-output-tokens": 14003, "length": "2e13", "weborganizer": {"__label__adult": 0.0003647804260253906, "__label__art_design": 0.0002522468566894531, "__label__crime_law": 0.0002498626708984375, "__label__education_jobs": 0.0004987716674804688, "__label__entertainment": 5.167722702026367e-05, "__label__fashion_beauty": 0.00013113021850585938, "__label__finance_business": 0.0001119375228881836, "__label__food_dining": 0.0002741813659667969, "__label__games": 0.00044155120849609375, "__label__hardware": 0.0005450248718261719, "__label__health": 0.0002560615539550781, "__label__history": 0.0001577138900756836, "__label__home_hobbies": 6.61611557006836e-05, "__label__industrial": 0.00021588802337646484, "__label__literature": 0.00023043155670166016, "__label__politics": 0.00018012523651123047, "__label__religion": 0.0003838539123535156, "__label__science_tech": 0.0028705596923828125, "__label__social_life": 7.027387619018555e-05, "__label__software": 0.0034542083740234375, "__label__software_dev": 0.98828125, "__label__sports_fitness": 0.00025844573974609375, "__label__transportation": 0.0003745555877685547, "__label__travel": 0.00017726421356201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61353, 0.01453]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61353, 0.55715]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61353, 0.91789]], "google_gemma-3-12b-it_contains_pii": [[0, 5317, false], [5317, 7531, null], [7531, 13162, null], [13162, 19372, null], [19372, 26455, null], [26455, 29768, null], [29768, 35147, null], [35147, 46443, null], [46443, 50588, null], [50588, 53909, null], [53909, 61353, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5317, true], [5317, 7531, null], [7531, 13162, null], [13162, 19372, null], [19372, 26455, null], [26455, 29768, null], [29768, 35147, null], [35147, 46443, null], [46443, 50588, null], [50588, 53909, null], [53909, 61353, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61353, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61353, null]], "pdf_page_numbers": [[0, 5317, 1], [5317, 7531, 2], [7531, 13162, 3], [13162, 19372, 4], [19372, 26455, 5], [26455, 29768, 6], [29768, 35147, 7], [35147, 46443, 8], [46443, 50588, 9], [50588, 53909, 10], [53909, 61353, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61353, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
853602bbcffe6c8ac6e98e75423553ef470b9303
|
A Metadata Handling API for Framework Development: a Comparative Study
Eduardo Guerra
Computer Science Faculty
Free University of Bozen-Bolzano
Bolzano, Italy
guerraem@gmail.com
Phyllipe Lima
National Institute of Telecommunications (INATEL)
Santa Rita do Sapucaí, Brazil
phyllipe@inatel.br
Joelma Choma, Marco Nardes
National Institute for Space Research (INPE)
São José dos Campos, Brazil
{jh.choma70,marconardes}@gmail.com
Tiago Silva
Department of Computer Science
Federal University of São Paulo
São José dos Campos, Brazil
silva.tiago@unicamp.br
Michele Lanza
Faculty of Informatics
University of Lugano
Lugano, Switzerland
michele.lanza@usi.ch
Paulo Meirelles
São Paulo School of Medicine
Federal University of São Paulo
São Paulo, Brazil
paulo.meirelles@unicamp.br
ABSTRACT
Frameworks play an essential role in software development, providing not only code reuse, but also design reuse. Several Java frameworks and APIs such as Spring, JPA, and CDI rely on the use of metadata, mainly defined by code annotations. These frameworks usually use the Java Reflection API to consume code annotations, which only returns the annotations in a given code element. This strategy, however, is far from the needs of a real framework. The goal of this paper is to propose a novel API, named Esfinge Metadata, to assist in the development of frameworks based on metadata and applications based on custom annotations. Being based on annotations itself, this new API uses them to map metadata to class members. We carried out an experiment to evaluate our API and its impact on aspects such as code structure, complexity, and coupling, while also performing a comparison with the direct use of the Java Reflection API. The participants implemented a metadata-based framework based on realistic requirements in a sequence of 10 tasks that took an average of nine hours. As a result, participants that used our API maintained a more stable code evolution, regarding complexity and coupling as opposed to participants using the Java Reflection API, where the code metrics evolution and structure vary greatly.
CCS CONCEPTS
• Software and its engineering → Software development techniques.
KEYWORDS
Framework, Metadata, Meta-Framework, Annotations, Code Metrics, Exploratory Experiment, Java
ACM Reference Format:
1 INTRODUCTION
Modern frameworks use metadata configuration to offer applications a high reuse level and a better adaptation to their needs. These are known as metadata-based frameworks since they process their logic based on the metadata configuration of the classes whose instances they are working with [11]. Highly used Java frameworks such as Spring, Hibernate, and JUnit use code annotations as their primary approach for configuring metadata.
The consumption of code annotations in Java usually make direct use of the Java Reflection API (Application Programming Interface). In this native API, the primary method for metadata retrieval returns the annotations that are configuring a given element. However, this approach is far from the needs of such a framework and may lead to a complex and high coupled code that may compromise its evolution and maintenance. For instance, it is typical for a framework to (i) retrieve all methods or fields with an annotation, (ii) to validate an annotation based on its context, and (iii) to retrieve annotations based on a common annotation that configure its type [11].
The Esfinge Metadata API is an extensible meta-framework for reading and validating annotations, which aims at simplifying and assisting, in particular, the development of metadata-based frameworks. Moreover, any application that defines custom annotations can also use it. The Esfinge Metadata API has features to retrieve and find annotations, and it was developed based on metadata-based framework patterns and best practices [11]. The API was designed to guide developers towards these best practices and provide a stable code evolution, with low complexity and coupling.
This paper aims to propose a novel API approach for metadata reading, processing, and consumption. As such, it provides functionality that assists the development of metadata-based frameworks, as well as applications that use custom annotations. A prior work presented a preliminary version of the Esfinge Metadata API and
performed a demonstrative case study. The API was still under construction and no proper experiment was carried out for evaluation [18].
To answer our novel API, we performed a controlled experiment with two groups of carefully selected developers. One group used our new Esfinge Metadata API, while the other used the Java Reflection API. They both developed a metadata-based framework for mapping application parameters to an annotated class instance, which we named the “target framework”. We divided the experiment into 10 tasks, where each one of them incrementally added functionality to the target framework. The complete experiment took, on average, nine hours of coding.
This paper aims to answer the following research question:
RQ: How does the Esfinge Metadata API provide support to maintain complexity and coupling in the evolution of a metadata-based framework compared to the Java Reflection API?
To answer this question, we executed the experiment and afterward analyzed the repository provided by each participant. We performed a careful code inspection in a qualitative analysis and observed the evolution of well-established software code metrics. All our findings and conclusions were obtained based on this code inspection, rather than statistical and numerical analysis.
From the results, we highlight the following finding. The usage of the Esfinge Metadata API provides a more consistent behavior in the evolution of coupling and complexity metrics, guiding metadata-based framework development to a more predictive way towards the best practices.
2 METADATA IN THE CONTEXT OF OBJECT-ORIENTED PROGRAMMING
The term “metadata” is used in a variety of contexts in the computer science field. In all of them, it means data referring to the data itself. When discussing databases, the data are the ones persisted, and the metadata is their description, i.e., the structure of the table. In the object-oriented context, the data are the instances, and the metadata is their description, i.e., information that describes the class. As such, fields, methods, super-classes, and interfaces are all metadata of a class instance. A class field, in turn, has its type, access modifiers, and name as its metadata. When a developer uses reflection, it is manipulating the metadata of a program and using it to work with previously unknown classes [6, 11].
2.1 Code Annotations
Some programming languages provide features that allow custom metadata to be defined and included directly on programming elements. This feature is supported in languages such as Java, through the use of annotations [12], and in C#, by attributes [4]. A benefit is that the metadata definition is closer to the programming element, and its definition is less verbose than external approaches, such as using an XML file. Also, the metadata is being explicitly defined in the source code as opposed to code convention approaches. Some authors call the usage of code annotations as attribute-oriented programming since it is used to mark software elements [20, 23].
Annotations are a feature of the Java language, which became official on version 1.5 [12] spreading, even more, the use of this technique in the development community. Some base APIs, starting in Java EE 5, like EJB (Enterprise Java Beans) 3.0, JPA (Java Persistence API) [13], and CDI (Context and Dependency Injection), use metadata in the form of annotations extensively. This native support to annotations encourages many Java frameworks and API developers to adopt the metadata-based approach in their solutions.
The Java language provides the Java Reflection API to allow developers to retrieve code annotations at runtime. It is also used to retrieve other information about the class structure, such as its fields, methods, and constructors. Additionally, developers may invoke methods, instantiate classes, and manipulate field values.
2.2 Java Reflection API to Consume Code Annotations
The Java language offers means for developers to consume code annotations through the Java Reflection API. Using the AnnotatedElement interface, implemented by reflection classes that represent code elements (such as the classes Method, Field and so forth), developers have access to methods such as isAnnotationPresent() and getAnnotation(). The first one verifies if an annotation is present on a give code element, and the latter returns the desired annotation [6].
Using the Java Reflection API, the developer must write explicit code to read metadata and retrieve code annotations individually. Developers cannot recover all annotations from a method, or a field, or even a class using a single call. The search must be executed iteratively. Hence, for complex metadata reading, using the Java Reflection API, the code could get complicated and create barriers to allow evolution. With this approach, the developer is not guided into using known best practices for metadata reading [9].
3 ESFINGE METADATA API
The Esfinge Metadata API is an open-source meta-framework developed to ease and support the process of metadata reading. It also functions as an API, and a preliminary version was published on [18] with no proper experiment, only a demonstration.
We believe the API is more suitable for metadata-based frameworks development since the Java Reflection API has only two main methods to access annotations. The first one checks if a specific annotation is present on a code element, the second retrieves an annotation from an element. Both of these methods are insufficient for the needs of developers. Hence they need to create much verbose code to retrieve the necessary data.
Our research group designed the API based on recurrent solutions found inside frameworks to read metadata from applications. They are documented as patterns on a previous work [9]. Using the API to read metadata is not limited to frameworks using these patterns. However, the developer will be guided towards them, just as MVC frameworks tend to do the same.
The core pattern is the “Metadata Container”. It introduces a class role called MetadataContainer, whose instance represents metadata retrieved at runtime. Figure 1 presents the pattern’s basic diagram.
The class MetadataContainer is responsible for storing metadata read from annotations at runtime. The FrameworkController asks the Repository for metadata of a given target class. If it was
We wish to read the metadata using the Esfinge Metadata API. The annotations presented on this list are just for the "Metadata Container" pattern is central for the proposed API. An annotation schema is defined as a set of associated annotations that belong to the same API. An annotation-based API usually uses a group of related annotations that represent the set of metadata necessary for its usage.
To demonstrate how to use this API, consider the class on Figure 2. It is annotated with @Annotation1(name="Player") and both private fields are annotated with @Annotation2(attr="attr1"). We wish to read the metadata using the Esfinge Metadata API.
To read the metadata of the class Player, consider the class on Figure 3. It contains a class using the Esfinge Metadata API. It is functioning as a class metadata container to store metadata from annotations used on the example code on Figure 2. Further, the class FieldContainer on Figure 4 is working as a field metadata container. This structure is following the “Metadata Container” pattern.
To read the metadata wherever it may be located. The MetadataReader should handle all peculiarities of the annotation schema and strategies for metadata definition, as well as it should return the MetadataContainer ready to be used by the FrameworkController.
Since this is a recurrent practice in several frameworks, we assume that storing metadata in a regular class when reading a complex annotation schema is an excellent general design. Therefore the “Metadata Container” pattern is central for the proposed API.
For further details, refer to the official website of the Esfinge Metadata API
[9]
Figure 1: Basic structure of the Metadata Container pattern
not yet retrieved, the Repository invokes the MetadataReader to fetch it wherever it may be located. The MetadataReader should handle all peculiarities of the annotation schema and strategies for metadata definition, as well as it should return the MetadataContainer ready to be used by the FrameworkController.
Since this is a recurrent practice in several frameworks, we assume that storing metadata in a regular class when reading a complex annotation schema is an excellent general design. Therefore the “Metadata Container” pattern is central for the proposed API.
To demonstrate how to use this API, consider the class on Figure 2. It is annotated with @Annotation1(name="Player") and both private fields are annotated with @Annotation2(attr="attr1"). We wish to read the metadata using the Esfinge Metadata API.
To read the metadata of the class Player, consider the class on Figure 3. It contains a class using the Esfinge Metadata API. It is functioning as a class metadata container to store metadata from annotations used on the example code on Figure 2. Further, the class FieldContainer on Figure 4 is working as a field metadata container. This structure is following the “Metadata Container” pattern.
To demonstrate how to use this API, consider the class on Figure 2. It is annotated with @Annotation1(name="Player") and both private fields are annotated with @Annotation2(attr="attr1"). We wish to read the metadata using the Esfinge Metadata API.
To read the metadata of the class Player, consider the class on Figure 3. It contains a class using the Esfinge Metadata API. It is functioning as a class metadata container to store metadata from annotations used on the example code on Figure 2. Further, the class FieldContainer on Figure 4 is working as a field metadata container. This structure is following the “Metadata Container” pattern.
The classes on Figures 4 and 3 use some annotations provided by the Esfinge Metadata API. The following list gives a brief understanding of some of the framework annotations, so interested developers and researchers may have a grasp of how the Esfinge Metadata API works. The annotations presented on this list are just a small sample of the functionalities and capabilities offered by the Esfinge Metadata API.
```
@Annotation(name="Player")
public class Player {
@Annotation2(attr="attr1")
private int field1;
@Annotation2(attr="attr2")
private int field2;
}
```
Figure 2: Simple class with metadata to be read
The classes on Figures 4 and 3 use some annotations provided by the Esfinge Metadata API. The following list gives a brief understanding of some of the framework annotations, so interested developers and researchers may have a grasp of how the Esfinge Metadata API works. The annotations presented on this list are just a small sample of the functionalities and capabilities offered by the Esfinge Metadata API.
```
@ContainerFor(ContainerTarget.FIELDS)
public class FieldContainer {
@ElementName
@AllFieldsWith(Annotation2.
private String exampleAnnotProp;
}
```
Figure 3: Simple Class Metadata Container
- @ContainerFor(): The container class can store metadata read from fields, methods, classes, enums, etc. This annotation informs the container class what type of code element it will store. When we pass in ContainerTarget.TYPE, we are informing that this class stores metadata from a class or enum. We pass in ContainerTarget.FIELDS to store metadata from a field, and so forth.
- @ElementName: This stores the name of the code element from where we are reading the metadata. In this example the name is "Player", since we are reading the metadata from the class Player. If we were reading metadata from a field, as shown in Figure 4, the @ElementName would be the name of the field, i.e., field1 and field2.
- @AnnotationProperty(): Retrieves the specified property from a given annotation. Observing Figure 3, line 11, we want to retrieve from inside @Annotation1 the value stored on the parameter "name". As shown on the code of Figure 2, line 1, this value is "Player".
- @AllFieldsWith(): This is done to retrieve metadata on fields inside the class. We specify what annotation we are looking for, and it searches for the fields that contain those annotations. In the code on Figure 3, line 8, we are searching every field that contains the annotation @Annotation2. Looking at Figure 2 the fields are "field1" and "field2". This annotations also has a version for methods, @AllMethodsWith(), i.e., it will search for methods with a given annotation.
Figure 5 shows how the containers are being used to read metadata from the class Player. We first create the AnnotationReader and the method readingAnnotationsTo() returns the container. It has two parameters; the first is the class with the metadata to be read, i.e., the (Player) class. The second parameter is the class that
will store the metadata that was read, i.e., the (PlayerMetadataContainer) class. Afterward, the container is populated with metadata that can be accessed through getter methods. The output of running this code is presented on Figure 6.
```java
public class Main {
public static void main(String args[]){
AnnotationReader reader = new AnnotationReader();
PlayerMetadataContainer container = reader.readingAnnotationsTo
(Player.class,
PlayerMetadataContainer.class);
System.out.println(container.getElementName());
System.out.println(container.getExampleAnnotProp());
for(FieldContainer fContainer : container.getFieldMetadata()){
System.out.println(fContainer.getAttr());
}
}
}
```
Figure 5: Reading Simple Metadata

Figure 6: Output code
As seen in this example, the developer does not have to write Reflection code directly and has an intuitive way of retrieving metadata. The developer can map fields decoratively to receive information about specific annotations or to retrieve all annotations from methods, fields, and classes. By using this API, the developer is guided into using good practices to recover metadata, even if unaware. The creation and mapping of the class in the role of the metadata container can seem unnecessarily complicated to retrieve data of a simple set of annotations. Still, for a more complicated metadata schema, the gain in terms of maintainability might worth it.
4 EVALUATING METADATA-BASED FRAMEWORK DEVELOPMENT API
In this section, we present the methodology used to evaluate the Esfinge Metadata API. We begin discussing the research question that guided our work. Then we show how our experiment was carried out in terms of the participants’ selection and how the target framework was divided into tasks, where each task added new functionality to the framework. To analyze our data, we performed a careful code inspection with the aid of source code metrics and also the time spent on each task.
4.1 Research Questions
The goal of this experiment is to analyze APIs for code annotation reading for the purpose of exploring with regard to object-oriented metrics from the viewpoint of experienced and skilled Java developers, in the context of development and evolution of metadata-based frameworks [2]. We focus this study on the following research question:
RQ: How does the Esfinge Metadata API provide support to maintain complexity and coupling in the evolution of a metadata-based framework compared to the Java Reflection API? To answer this question, we performed a historical analysis and observed how object-oriented code metrics values evolved during the development. We analyzed well-established metrics such as Number of Methods (NOM) and others from the CK suite (as described in Section 4.2.4). Regarding these metrics, our hypothesis is composed of two parts. First (i), the complexity should be lower in codes that used our Esfinge Metadata API since some logic is being executed through annotations reading and processing. As for the Java Reflection API, similar rules are supposed to be implemented, using imperative code. Second (ii), the coupling should be lower in codes that used our Esfinge Metadata API if we do not consider the coupling to annotations. That is because several links should be bound by metadata configuration and not by method calls.
4.2 Experimental Design
From a practical point of view, we cannot measure an API’s impact during the development of a small framework. We conducted an exploratory experiment to overcome this challenge and observe how API usage influences code evolution. The required time for implementation was much longer than other controlled experiments that last, on average, 110 minutes [14]. Due to this implementation time, it is not viable for the participants to implement all the features in a continuous period. The division of the experiment in tasks allowed the participants to perform it in small portions, being able to take a break between them.
<table>
<thead>
<tr>
<th>API</th>
<th>Participant</th>
<th>Time Spent</th>
<th>Execution</th>
</tr>
</thead>
<tbody>
<tr>
<td>Esfinge Metadata API</td>
<td>P1</td>
<td>6 days (342 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Esfinge Metadata API</td>
<td>P2</td>
<td>5 days (810 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Esfinge Metadata API</td>
<td>P3</td>
<td>4 days (735 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Esfinge Metadata API</td>
<td>P4</td>
<td>8 days (773 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Esfinge Metadata API</td>
<td>P5</td>
<td>2 days (318 min)</td>
<td>Correct</td>
</tr>
<tr>
<td></td>
<td>Group Average</td>
<td>5 days (613 min)</td>
<td>-</td>
</tr>
<tr>
<td>Reflection</td>
<td>P6</td>
<td>11 days (1110 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Reflection</td>
<td>P7</td>
<td>12 days (472 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Reflection</td>
<td>P8</td>
<td>21 days (611 min)</td>
<td>Incorrect</td>
</tr>
<tr>
<td>Reflection</td>
<td>P9</td>
<td>1 days (389 min)</td>
<td>Correct</td>
</tr>
<tr>
<td>Reflection</td>
<td>P10</td>
<td>6 days (350 min)</td>
<td>Correct</td>
</tr>
<tr>
<td></td>
<td>Group Average</td>
<td>10.2 days (586 min)</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>Average</td>
<td>7 days (545 min)</td>
<td>-</td>
</tr>
</tbody>
</table>
We provided an automated test suite to ensure that a given behavior is implemented at the end of each task. Thus, the task is considered complete only after the tests are passing. Afterward, the participant should commit the code to the repository. Given the nature of this experiment and the time spent executing the
tasks, each participant remotely performed the experiment. We
modeled our tests with a blackbox approach, considering only input
and desired output. Hence the tests did not consider the internal
structure used by the participants to develop their target framework.
During the selection of the participants, we observed that the
execution time of tasks varied greatly between them. Hence we con-
cluded that a careful analysis of time would not be very meaningful
to our experiment.
In the following subsections, we describe the design of our ex-
periment based on the recommendations of Ko
\textit{Participants Selection and Training}. We initially recruited 47
professional developers with at least three years of Java experience.
The demographic data was gathered to understand better their level
of expertise, background, and experience with the required tools.
With this information, we were able to decide which participants
were qualified to be in our experiment.
To select the participants, we applied a test to assess their knowl-
edge of Java Reflection. We invited them to develop a short program
in which the participants would have to demonstrate their skills
in advanced programming techniques through reflection and code
annotations. As a selection criterion, they would have to implement
the activity correctly and in less than one hour. As a result, 10 par-
ticipants completed the exercise successfully and agreed with the
terms of the study. In short, we submitted the candidates through a
rigorous selection process and selected ones with suitable program-
ning skills. Once the selected participants agreed to participate in
the study, they all signed a consent form.
During the recruitment stage, all the candidates watched a set of
video lectures on Java Reflection API, Code Annotations, Apache
BeanUtils, and metadata-based frameworks to align the knowledge
needs for the experiment. Later, after the group’s assignment, the
participants of the second group – the one required to use the
Esfinge Metadata API – received further training by dedicated
video lectures about our Esfinge Metadata API.
As the participants executed the experiment, they filled a diary
where they made comments and personal notes/opinions. We did
not consider this, however, when performing the code analysis,
since the information we needed was in the provided code.
Finally, this research was funded, and we were able to reward
the participants. At the end of the experiment, we also debriefed
the participants by explaining (i) what exactly the study was inves-
tigating; (ii) why the research was necessary; (iii) how we were
going to use the data; and that (iv) we were going to spread the
results as soon as we were finished analyzing the data.
\textit{Procedure}. Firstly, we created a GitLab repository for each
participant with the initial configuration already set up. All these
repositories belong to a group
\textit{A different author of this paper executed the experiment using
both approaches after the experiment was entirely carried out, with
every participant handling their source code in the repository. He
provided a reference source code that we used for the qualitative
analysis. This verification was done through mining the partici-
pants’ repositories and carefully observing the source code and its
evolution.}
\textit{Tasks}. According to Sjoberg \textit{et al.}, one of the challenges
in controlled experimental design is the trade-off between realism
and control. The task design is at the heart of this trade-off, as tasks
represent the essence of realistic and messy software engineering
work.
One aspect is to consider what features the target framework
will contain and how they will be broken down into tasks for the
participants to execute. From previous research outcomes, our group
was able to identify common characteristics of metadata-based frameworks and used such knowledge to prepare
the tasks to have good feature coverage.
These frameworks validate the metadata inserted in the pro-
gramming elements before they are processed to execute custom
behavior. For instance, some annotations can only be configured
on specific element types, or the values of the attributes may have
some restrictions. As such, there are tasks where the participants
will execute routines that validate metadata.
Metadata reading and processing are also two common features
present in metadata-based frameworks. The first is about identi-
fying the code annotation and the code element. The second is
regarding executing the behavior. The target framework developed
by the participants also contained such tasks. Finally, there was
also a task about the introduction of an extension point and others
that impacts the framework control flow. With this, we believe that
the target framework has the same characteristics and features that
are implemented in a real one.
In practice, the participants implemented a metadata-based framework that maps the command-line parameter array received in the main() method to a JavaBean class. This mapping is done through metadata configurations, i.e., using annotations. The features of this framework were organized into tasks that tackle common features of a metadata-based framework. Following is a list describing the ten tasks.
1. **Mapping Boolean Properties**: Verify if a parameter is present on the command-line.
2. **Mapping String Properties**: Store the String attribute passed after a parameter.
3. **Mandatory Parameters**: Verify if a parameter marked as mandatory is present on the command line. If not, an error occurs.
4. **Mapping Numeric Properties**: Store the numeric attribute passed after a parameter.
5. **Validating Text Properties**: Validate the string attribute passed on the command line.
6. **Validating Numeric Properties**: Validate the number attribute passed on the command line.
7. **Supporting Composite Classes**: Provide functionality to map command-line attributes to encapsulated classes.
8. **Annotation Extension**: Add an extension point to create custom annotations.
9. **Supporting Parameter Lists**: Stores a list of attributes, both numeric and textual, passed on the command line.
10. **Supporting Dates**: Store the date attribute passed after a parameter.
The participant should perform these tasks strictly in the specified order and not read the subsequent tasks before finishing the current one. Each experiment task contains (i) a textual description of the feature to be developed; and (ii) a set of classes that consist of automated tests to check the correctness of the implemented feature.
Finally, the target framework tasks were also designed to represent realistic functionality that would be implemented for retrieving command-line parameters. Nonetheless, they were not based on features present in any of the APIs, emulating the development of a real-world metadata-based framework.
### 4.2.4 Qualitative Analysis with Source Code Metrics
Source code metrics are used to retrieve information from software and assess its characteristics. They help summarize particular aspects of software elements, detecting outliers in large amounts of code. They are valuable in software engineering since they enable developers to keep control of complexity, making them aware of the abnormal growth of specific system characteristics. To effectively take advantage of metrics, they should provide meaningful information and not just numerical values [16].
We used object-oriented code metrics to analyze the complexity and coupling of the source code from the developed target framework. Respectively, these metrics are from the CK suite [3], such as Weight Method Count (WMC) and Coupling Between Objects (CBO). We also use the Number of Methods (NOM) metric.
### 5 DATA ANALYSIS
In this section, we present the quantitative and qualitative analysis of the data collected from the experiment to answer our research question. We monitored the evolution of some selected software metrics as the participants were developing the framework. For the qualitative analysis, we performed an inspection of the source code developed by the participants to extract information about their use of both Java Reflection and our Esfinge Metadata API.
As mentioned in Section 4.2, we recruited and trained ten participants. However, participant P8, as presented in Table 1, did not complete the experiment correctly. As such, we excluded P8 from the analysis. Therefore, the final sample has nine participants: four for the Java Reflection Group and five for the Esfinge Metadata Group.
We analyzed how three well-established software metrics behaved during the evolution of the target framework by both approaches designed for the experiment. These metrics are WMC (Weight Method Class), NOM (Number of Methods), and CBO (Coupling Between Objects). We designed the development of the target framework into ten tasks, and at the end of each task, we extracted these metrics values. We present graphs that show how these metrics behaved in the next sub-sections, and we use them to analyze the experiment further.
#### 5.1 Complexity
The tool used to extract values for WMC has implemented it as McCabe’s Complexity, i.e., counting the number of branch instructions in a class. We observe in Figure 7 that the Esfinge Metadata Group has larger WMC values. However, we also notice that these participants evolve in a similar pattern when compared to the Java Reflection Group. We expected this greater value since to use the API developers are required to write getters and setters to populate the MetadataContainer class, as part of the MetadataContainer design pattern. Developers on the Java Reflection Group, although it was mandatory to use the design pattern mentioned earlier, could take another route during the development. We also know that every single method, regardless of its complexity, adds a number to the WMC count. As such, we are purely looking at this number might not be a true measure of complexity.
To complete the complexity analysis, we also looked at the Number of Methods (NOM) metric. The graph in Figure 8 presents how the NOM metric evolved during the development. This graph shows that the Esfinge Metadata Group created more methods, roughly twice the Java Reflection Group, which is in agreement with the higher WMC number presented in Figure 7.
The code evolution from two participants, P6 and P10, represented as dashed blue lines on both Figures 7 and 8 presented an abnormal value of WMC metric. However, observing Figure 8, we notice that these two participants had practically a constant value for NOM. This metric behavior suggests that these methods were constantly growing to accommodate the new features of the framework. WMC values were growing from the complexity of these methods rather than the addition of new methods.
From this analysis, we plotted a new graph that is the ratio of WMC per NOM, as presented in Figure 9. Thereby, we observed how the participants P6 and P10 has a curve with much higher values than all other participants, confirming they have created
highly complex methods. Moreover, all participants from the ours Group present lower values of this ratio, which confirms that even though a higher number of methods, their complexity is inferior. This information was not clear, only analyzing the WMC graph in Figure 7. With this analysis complete, it becomes clear why we included the NOM metric in this section. Although it does not measure complexity, it was used as a normalization factor for the WMC values.
5.2 Coupling
We calculated the CBO metric as Fan-Out, i.e., how many external classes a specific class refers too. Observing Figure 10, we notice that the Esfinge Metadata group has higher values and, therefore, presents more upper coupling. By analyzing two participants of the Java Reflection Group, P7, and P9, we observed unexpected CBO values. The latter presents a decrease in its CBO value after completing Task #8, and the former shows an abrupt growth on the CBO value after the final task's conclusion.
During code inspection, it was not explicit why P9 had a decrease in its value. It was subtle the reason that caused this behavior. An important observation is that this participant was the only one in the Reflection Group that implemented the MetadataContainer design pattern as expected. This behavior means storing the metadata in a container class for later analysis. It is interesting to observe because its CBO value approximates that of the Esfinge Metadata Group, suggesting that this design pattern presents a higher coupling factor.
For this reason, P9 had separate classes responsible for metadata reading of a specific data type. During most of the development, an abstract class was used as the superclass for metadata reading classes, but, during Task #8, P9 switched to an interface. During the refactoring process of these classes, some became less coupled, which resulted in a lower CBO value overall.
As for participant P7, he was not implementing the pattern correctly MetadataContainer, i.e., he was not storing metadata in a container class. On the last task, however, he performed a significant refactoring of the code. In short, he created different classes to read and process the metadata according to its type, hence the CBO value had an abrupt growth.
Given that the Esfinge Metadata API is a metadata-based framework, it relies heavily on code annotations, which is considered when calculating the CBO metric. We altered the CBO calculation of our metric extraction tool and generated a new graph in Figure 11.
This graph shows how the CBO evolved without considering code annotations. As expected, the CBO values for the Esfinge Metadata Group had a decrease, lower than P9, for most of the development, and P7, after the significant refactoring. The two developers from the Java Reflection group that stayed below are P6 and P10. As seen in the WMC analysis, these two participants did not implement the MetadataContainer design pattern correctly. They created large and complex methods to avoid separating the functionality of metadata reading and processing. The complexity of their methods outweighs the lower coupling values they presented since the produced code shows lower readability and more effort to maintain.
Overall, from Figure 11, the Esfinge Metadata Group presents a more similar growth pattern, and it is more homogeneous than the Reflection Group. This behavior is a reflection of having a design pattern that is mandatory when using the Esfinge Metadata API. Developers using pure Java Reflection API have to build this architecture themselves, and as reinforced in this CBO analysis, may divert.
Another analysis is to observe how the CBO metric evolved as the number of classes evolved, i.e., normalizing the CBO value by the number of classes. This observation is similar to the analysis performed on how the WMC metric evolved as the NOM evolved presented in Figure 9. Figure 12 presents the normalized CBO graph. From this figure, it is clear that the Esfinge Metadata Group has more coupled classes. However, this graph also reinforces they have, overall, more homogeneous growth. However, participant P4 shows an abrupt growth on commit seven, surpassing other participants. This behavior indicates that the CBO is growing more rapidly than the number of classes, which suggests high coupling in the framework’s classes. After code inspection, one reason for this growth was the use of unnecessary Esfinge Metadata API annotations for validation, since they have no effect where it was placed. Using just the CBO graph in Figure 10 this observation is not clear. To analyze the normalized CBO without considering annotations, we generated the graph in Figure 13. From this, we see that most developers on the Esfinge Metadata Group have very similar CBO values, while the Reflection Group is more scattered. This factor is yet another confirmation that the CBO value from
the Esfinge Metadata Group is strongly related to code annotations. It also has the API enforcing the use of the MetadataContainer pattern leads towards a homogeneous code even from different developers.
6 DISCUSSION
Answering our RQ (How does the Esfinge Metadata API provide support to maintain complexity and coupling in the evolution of a metadata-based framework compared to the Java Reflection API?), we observed how three metrics – WMC, NOM, and CBO – evolved during the evolution of the target framework, dividing the analysis into two parts: complexity and coupling.
We were expecting that the complexity for participants using our Esfinge Metadata API would be lower, and the analysis concluded that. We used the WMC metric to measure the complexity, but as shown and discussed, purely analyzing its values would not suffice, since simple access methods contribute to the metrics values. To further investigate the complexity, we normalized the WMC value per NOM. Thus, we were able to identify that methods from the Esfinge Metadata API Group were less complex than methods created by the Java Reflection Group. Moreover, this was a consequence of having the MetadataContainer pattern being implemented correctly by the Esfinge Metadata API Group since the API also guides the developers to use best practices.
For the coupling analysis, we used the CBO metric. The expected result was that the overall coupling would be lower for the Esfinge Metadata API Group if coupling to code annotations were not considered. The analysis showed that the group using Esfinge Metadata API has higher CBO value, i.e., more coupled classes. What was observed is that developers from the Reflection Group that did not use the MetadataContainer pattern correctly had low values for CBO. However, they had more complex methods. Developers who did implement the pattern successfully had higher coupling values, including both Esfinge Metadata API and Java Reflection Group. Hence we conclude that the pattern has a high coupling factor. When code annotations were removed from the calculation, the CBO values for the Esfinge Metadata API Group dropped roughly fifty percent, while it stayed stable for the Java Reflection Group. This behavior shows that the coupling for the Esfinge Metadata API Group has a substantial contribution from code annotations, which means the coupling is due to metadata configuration and not method calls. We conclude that using a metadata approach to implement the MetadataContainer pattern increased the coupling factor.
Overall, our Esfinge Metadata API allowed developers to have a steady evolution of the code while developing the target framework. The main reason is that our API guides the developers in using best practices, precisely, the MetadataContainer pattern. Although participants from the Java Reflection API group also had to use this pattern, it was still possible to diverge and create more complex code. This behavior became apparent during the code inspection phase.
There is a learning curve required to use our Esfinge Metadata API, and although it does not require developers to directly deal with reflection code, they still need to have a firm grasp of the involved concepts. During our inspection, we observed that codes using our API were much cleaner and readable when compared with code directly using the Java Reflection API. This is the main goal of our API, that is, to guide developers towards best practices when implementing metadata-based frameworks or code annotations-based solutions. Creating such kinds of solution does not necessarily mean less effort.
7 THREATS TO VALIDITY
In this section we present the threats to validity of our work following the guidelines proposed by [24].
• Conclusion Validity: Our findings were based on manual code inspection, therefore our own coding skills and knowledge of Java Reflection might have affected our conclusions.
• Internal Validity: Initially, the participants received the same training through a set of video lectures on the topics addressed by the experimental study. We applied an exercise to evaluate each participant. Thus, we distributed them in balanced groups in terms of their performance. The Esfinge Metadata API group received further training to learn about this new API, which also potentially reinforced their knowledge about reflection code and techniques.
• Construct Validity: The Esfinge Metadata API guides the developers towards best practices, while the Java Reflection API does not. Hence, developers using Java Reflection had nothing forcing them to keep following these practices, which may have led to low quality code.
• External Validity: The experiment was conducted remotely by the participants in their own environment. They were also responsible for managing their execution time. Some developers might have had a more adequate environment than others, or less interruption during the experiment.
8 RELATED WORK
We exhaustively searched and did not find other solutions of APIs for metadata reading in this context. However, we have related works about studies involving annotated code and metadata-based frameworks. Yu et al. [25] perform a large-scale and empirical study about Java annotation on 1,094 open-source Java projects hosted on GitHub. The authors presented 10 novel empirical findings about Java annotation usage, annotation evolution, and annotation impact. For instance, the authors show that annotations are actively maintained, and most of their changes are consistent with other code changes.
Regarding annotation definition, Rocha and Valente [19] investigated how annotations are used in open-source Java systems. The authors analyzed 106 open-source projects from Qualitas Corpus project database [22], from which 65 projects used annotations. Only the number of annotations and their type was considered in this study. In some of the evaluated systems, a high density of annotations was detected, indicating a possible misuse. Some other data extracted from this study also revealed that more than 90% of the annotations are in methods, and framework annotations are the most used ones.
Alba [1] performed a study regarding legibility on annotated code. The author used a questionnaire to present two similar codes
that represented different approaches expressing the same semantics, where developers should choose the most legible one. The questionnaire was answered by more than a hundred developers and had 27 questions focusing on the usage of annotations. The study pointed out that annotated code is perceived as more legible than the unannotated one. Besides that, the usage of annotation idioms [8] can improve annotation readability and context where the annotation was used has an influence on the perception of legibility.
9 CONCLUSION
In this paper, the main contribution is the proposal of a novel API approach to support the development of metadata-based frameworks, as well as applications based on custom annotations. The proposed API provides features based on frameworks needs, such as (a) support to search annotations in other code elements related to the target code element; (b) mapping for class metadata and annotation attributes; (c) chain processing of methods and field metadata; (d) support for the implementation of an extensible metadata schema; and (e) extension point that allows the creation of new metadata reading annotations.
We conducted an experiment that compared our Esfinge Metadata API with the Java Reflection API, evaluating the effects of their usage under various aspects related to software quality and development practices, such as code complexity and coupling. As a result, our Esfinge Metadata API allowed developers to have a more stable evolution of the code while developing the target framework. The detailed code inspection revealed evidence that the proposed API guides the developers into using best practices, not necessarily with less effort. Although participants from the Java Reflection API group were also instructed to use a similar structure, the experiment revealed that in some cases, the developer could diverge to add accidental complexity, ending up with a higher coupling.
As future work, we intend to add new features in our Esfinge Metadata API, especially to enable the support for code conventions and external metadata configuration. We also plan to carry out other studies about the usage of the proposed API, such as evaluating it from the Developer Experience (DX) [5, 15] point of view and by using it in the development of projects.
ACKNOWLEDGMENT
We would like to thank the support granted by Brazilian funding agencies CAPES (Higher Education Improvement Coordination) and FAPESP (São Paulo Research Foundation, grant 2014/16236-6 and 2019/12743-4).
REFERENCES
|
{"Source-Url": "https://www.inf.usi.ch/lanza/Downloads/Guer2020a.pdf", "len_cl100k_base": 9638, "olmocr-version": "0.1.50", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 30577, "total-output-tokens": 12027, "length": "2e13", "weborganizer": {"__label__adult": 0.0003736019134521485, "__label__art_design": 0.00027251243591308594, "__label__crime_law": 0.00026798248291015625, "__label__education_jobs": 0.0010442733764648438, "__label__entertainment": 4.4286251068115234e-05, "__label__fashion_beauty": 0.00014257431030273438, "__label__finance_business": 0.0001418590545654297, "__label__food_dining": 0.00029969215393066406, "__label__games": 0.0003695487976074219, "__label__hardware": 0.0004930496215820312, "__label__health": 0.00035881996154785156, "__label__history": 0.0001767873764038086, "__label__home_hobbies": 7.724761962890625e-05, "__label__industrial": 0.0002579689025878906, "__label__literature": 0.00018703937530517575, "__label__politics": 0.0001862049102783203, "__label__religion": 0.0004229545593261719, "__label__science_tech": 0.0032291412353515625, "__label__social_life": 9.608268737792967e-05, "__label__software": 0.0033702850341796875, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.0002906322479248047, "__label__transportation": 0.0004062652587890625, "__label__travel": 0.00020432472229003904}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53576, 0.01881]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53576, 0.5024]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53576, 0.90366]], "google_gemma-3-12b-it_contains_pii": [[0, 4680, false], [4680, 11091, null], [11091, 17703, null], [17703, 23258, null], [23258, 28161, null], [28161, 34401, null], [34401, 36300, null], [36300, 39314, null], [39314, 45609, null], [45609, 53576, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4680, true], [4680, 11091, null], [11091, 17703, null], [17703, 23258, null], [23258, 28161, null], [28161, 34401, null], [34401, 36300, null], [36300, 39314, null], [39314, 45609, null], [45609, 53576, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53576, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53576, null]], "pdf_page_numbers": [[0, 4680, 1], [4680, 11091, 2], [11091, 17703, 3], [17703, 23258, 4], [23258, 28161, 5], [28161, 34401, 6], [34401, 36300, 7], [36300, 39314, 8], [39314, 45609, 9], [45609, 53576, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53576, 0.04839]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
9105841055d6085140a06aaa1e254beb48ef74d3
|
Strongly sequential and inductively sequential term rewriting systems
Michael Hanus\textsuperscript{*} Salvador Lucas\textsuperscript{†} Aart Middeldorp\textsuperscript{†}
Abstract
The concept of definitional tree by Antoy serves to introduce control information into the bare set of rules of a constructor-based term rewriting system (TRS). TRSs whose rules can be arranged into a definitional tree are called inductively sequential. By relying on the existence of such a definitional tree, an optimal rewriting strategy, the outermost-needed strategy is defined. Optimality was proved w.r.t. the Huet and Lévy's theory of needness. In this paper, we prove that strongly sequential and inductively sequential constructor-based TRSs coincide. We also show that outermost-needed rewriting only reduces strongly needed redexes.
Keywords: definitional trees, needness, strong sequentiality, term rewriting, declarative programming.
1 Introduction
For orthogonal TRSs, the best normalizing strategy which avoid unnecessary reductions is needed rewriting \cite{Huet-Lévy}. Needed rewriting only considers needed redexes, i.e., redexes which are contracted (themselves or some residual) in every normalizing derivation. Unfortunately, it is undecidable whether a redex is needed. Strongly sequential redexes approximate needed redexes. However, reduction of strong redexes is costly to implement \cite{Hermanns}, and some efforts have been done to simplify the (strongly) needed reduction process.
Definitional trees \cite{Antoy} allow us to define optimal strategies both in rewriting \cite{Antoy} and narrowing \cite{Baldax}. A definitional tree consists of branches on the values of particular arguments and the rules of the TRS.
\textsuperscript{*}Informatik II, RWTH Aachen, D-52056 Aachen, Germany, hanus@informatik.rwth-aachen.de. Work partially supported by DFG (under grant Ha 2457/1-1) and Acción Integrada.
\textsuperscript{†}DSIC, U.P. de Valencia, Camino de la Riaza s/n, Apdo. 22002, E-46071 Valencia, Spain, slucas@dsic.upv.es. Work partially supported by EEC-ILC grant ERBCHRXCT940024, Bancaixa (Banca Hispano-Europea grant), Acción Integrada (HAC-1997-0073) and CICYT (under grant TIC95-0433-C03-03).
\textsuperscript{‡}Institute of Information Sciences and Electronics, University of Tsukuba, Tsukuba 305-8573, Japan, am@ics.is.tsukuba.ac.jp.
Example 1.1 Consider the following rules:
\begin{center}
\begin{align*}
\text{first}(0,x) & \to \square \\
\text{first}(s(x),y::z) & \to y::\text{first}(x,z)
\end{align*}
\end{center}
We give a graphic representation of the definitional tree for the function \text{first} (Figure 1). The first branch is done on the first argument \(x_1\) with alternative patterns 0 and \(s(x)\), where a further branch on \(x_2\) (with only one alternative) is necessary for the latter pattern.
\begin{center}
\begin{tikzpicture}
\node (root) {\text{first}(0,x_0)};
\node[below left of=root] (l) {\text{first}(s(x),x_2)};
\node[below right of=root] (r) {\text{first}(s(x),y::z)};
\node[below right of=l] (rl) {y::\text{first}(x,z)};
\draw[->] (root) -- (l);
\draw[->] (root) -- (r);
\draw[->] (l) -- (rl);
\end{tikzpicture}
\end{center}
Figure 1: Definitional tree for the function \text{first}
A function \(f\), defined by rules of a TRS \(R\) is inductively sequential if there exists a definitional tree \(P\) containing all rules defining \(f\). \(R\) is inductively sequential if all defined symbols are inductively sequential.
Recently, definitional trees and inductively sequential TRS became important for declarative programming languages since they model lazy functional languages with pattern matching and are an adequate basis to implement optimal evaluation strategies for functional logic languages \cite{Baldax}. Moreover, they can be easily extended to more general classes of TRS \cite{Baldax}.
The relevance of inductively sequential TRSs for declarative programming languages raised the question about their relationship to the classical concept of strong sequentiality. In \cite{Baldax}, the question was raised whether the classes of strongly sequential and inductively sequential constructor-based TRSs are the same. In this paper we formally show that the two classes coincide. Furthermore, we generalize the notion of a definitional tree to deal also with non-constructor-based TRSs. This allows us to compare definitional trees to other structures used to implement strong sequentiality, like index trees and forward-branching index trees \cite{Huet-Lévy,Horrocks}, and the matching dag of Huet and Lévy \cite{Huet-Lévy}.
A definitional tree determines a rewriting strategy, namely the outermost-needed strategy. We prove that...
this strategy is an index reduction strategy, i.e., it only selects strong indices for reduction. Since we can use the properties of strong indices in constructor-based TRSs, our proof is easier than the one in [1].
In Section 2, we review the technical concepts used in the remainder of the paper. In Section 3, we introduce definitional trees. Section 4 explores the relation between strongly sequential and inductively sequential TRSs. Section 5 compares to other approaches.
2 Preliminaries
This section introduces our main notations (see [5, 8] for full definitions). Given a partial order ≤ on a set \( A \) and \( a \in A \), \( a^+ = \{ b \in A \mid a \leq b \} \) is the upward set associated with \( a \). \( a \models b \) means \( a \notin b \) and \( b \notin a \).
\( V \) denotes a set of variables and \( \Sigma \) denotes a set of function symbols \( \{ f_1, \ldots, f_n \} \), each with a fixed arity given by a function \( ar : \Sigma \to \mathbb{N} \). We denote the set of terms by \( T(\Sigma, V) \). A \( k \)-tuple \( t_1, \ldots, t_k \) of terms is denoted by \( t \), where \( k \) will be clarified by the context.
The set of variables appearing in a term \( t \) is denoted by \( \Var(t) \).
Terms are viewed as labeled trees in the usual way. Occurrences \( u, v, \ldots \) are represented by chains of positive natural numbers used to address subterms of \( t \). Occurrences are ordered by the standard prefix ordering: \( u \leq v \) if \( \exists w \text{ such that } v = u.w \). The empty occurrence is denoted by \( e \). \( O(t) \) denotes the set of occurrences of \( t \). The subterm at occurrence \( u \) of \( t \) is denoted by \( t_u \). The term \( t \) with the subterm at the occurrence \( u \) replaced with \( \alpha \) is denoted by \( t[u]_\alpha \). The symbol labeling the root of \( t \) is denoted by \( \root(t) \).
A rewrite rule is an ordered pair \( (l, r) \), written \( l \to r \), with \( l \in \Gamma_\Sigma(V) \), \( r \notin \Gamma_\Sigma(V) \) and \( \Var(r) \subseteq \Var(l) \). A rewrite rule is called a left-hand side (lhs) of the rule and \( r \) the right-hand side (rhs).
A TRS is a pair \( R = (\Sigma, R) \) where \( R \) is a set of rewrite rules. A left-linear TRS is a TRS where every lhs is a linear term. An orthogonal TRS is a left-linear TRS without overlapping rules, i.e., given a rule \( l \to r \), there is no non-variable occurrence \( u \in O(l) \) such that \( t_u \) unifies with a \( \text{lhs} \) \( l' \) of a rule \( l' \to r' \) in the TRS (where \( l \to l' \) and \( l \to r' \) are different in case of \( u = e \)).
A term \( t \) rewrites to a term \( s \), written \( t \to_R s \), if \( t_u = \sigma(l) \) and \( s = t[\sigma(r)]_\alpha \), for some rule \( l \to r, u \in O(t) \) and substitution \( \sigma \). \( O_2(t) = \{ u \mid O(t) \} \) \( \exists \sigma \to_R r \). \( \sigma \) with \( t_u = \sigma(l) \) is the set of rewrite indices in \( t \).
Given a TRS, we split the signature into the disjoint union \( \Sigma = \Sigma_r \cup \Sigma_f \) of symbols \( c \in \Sigma_r \), called constructors, having no associated rule and symbols \( f \in \Sigma_f \), called defined functions or operations, which are defined by some rule \( f(\tilde{u}) \to r \). Each rule \( f(\tilde{u}) \to r \) in a constructor-based TRS or constructor system (CS) must satisfy \( f \in \Sigma_f \) and \( \delta \in T(\Sigma, V)^{ar(f)} \).
3 Definitional trees
We generalize the notion of (partial) definitional tree (pdt) by using its declarative definition (see [2]). To represent unknown parts of a term \( t \) we use the symbol \( \Omega \). Terms in \( T(\Sigma, \Omega) \) are called \( \Omega \)-terms. To discuss about unknown portions of expressions, we use the ordering ≤ on \( \Omega \)-terms given by: \( \Omega \leq t \) for all \( t \in T(\Sigma, \Omega) \), \( x \leq x \) for all \( x \in V \), and \( f(\tilde{u}) \leq f(\tilde{u}') \) if \( t_i \leq s_i \) for \( I \leq i \leq ar(f) \). In this way, \( t \leq s \) means “\( t \) is less or equally defined than \( s \)”. \( O_2(t) = \{ u \mid O(t) \} \) \( t_\omega = \Omega \) is the set of occurrences of \( \Omega \) in \( t \).
A definitional tree of a finite set of incomparable \( \Omega \)-terms \( S \subseteq T(\Sigma, \Omega) \) with pattern \( \pi \in T(\Sigma, \Omega) \) is a non-empty, ordered set \( P \) of \( \Omega \)-terms having the following properties:
- There is a minimum element which is the pattern of the pdt: \( \min(P) = \pi \) (minimum property).
- The maximal elements are the elements of \( S \): maximal(\( P \) \( = S \) (leaves property).
- \( \pi' \in P \setminus S \), there is a unique \( \pi'' \in P \setminus S \), \( \pi'' < \pi' \), such that there is no \( \pi''' \in T(\Sigma, \Omega) \) with \( \pi'' < \pi''' < \pi' \) (parent property).
- Given \( \pi' \in P \setminus S \), there is an occurrence \( u \in O_2(\pi'(x)) \) (called the inductive occurrence), and symbols \( f_1, \ldots, f_n \in \Sigma \) with \( f_i \neq f_j \) for \( i \neq j \), such that for all \( \pi_1, \ldots, \pi_n \) which are immediately below \( \pi' \), \( \pi_i = \pi'[f_i(\tilde{u})]_u \) for all \( 1 \leq i \leq n \) (induction property).
These properties entail \( S \subseteq P \subseteq \pi \). Given a TRS \( R = (\Sigma, R, \Sigma_f, R) \), a redex scheme of \( R \) is a \( \Omega \)-term of a rule \( l \to r \) where all variables are replaced by \( \Omega \). Let \( L_2(R) \) be the set of redex schemes of \( R \). Since we deal with orthogonal TRSs, we assume that a bijective function \( \rho : L_2(R) \to R \) associates the rule which corresponds to each redex scheme. A preorder of a redex scheme \( l \) is an \( \Omega \)-term \( \pi \) such that \( \pi \leq l \). Let \( L_2^\omega(R) = \{ \pi \mid \exists l \in L_2(R) \text{ with } \pi < l \} \). For \( f \in F \), let \( L_2^\omega(R) = \{ l \in L_2(R) \mid \root(l) = f \} \). \( \pi \) is called inductively sequential if there exists a definitional tree \( P_f \) which is a pdt of \( L_2^\omega(R) \) with pattern \( f(\tilde{u}) \). \( \pi \) is called inductively sequential if all defined symbols \( f \in F \) are inductively sequential. An inductively sequential TRS
\[ \text{In the original definition of definitional trees, only constructor symbols are allowed.} \]
can be viewed as a set of definitional trees, each defining a function symbol. By using a representation function \( \text{pdt} \) of a set \( S \subseteq L_0(\mathbb{R}) \) with pattern \( \pi \) as a term \( \text{pdt}(\mathcal{P}) \) as follows:
\[
\text{pdt}(\mathcal{P}) = \text{rule}(\rho(\pi)) \quad \text{if} \quad \mathcal{P} = \{ \pi \} = S.
\]
\[
\text{pdt}(\mathcal{P}) = \text{branch}(\pi, u, \text{pdt}(\mathcal{P}_1), \ldots, \text{pdt}(\mathcal{P}_n)) \quad \text{if} \quad \mathcal{P} \quad \text{is not a singleton, where} \quad \pi = \text{min}(\mathcal{P}), \quad u \quad \text{is the inductive occurrence of} \quad \pi, \quad f_1, \ldots, f_n \in \Sigma, \quad f_i \neq f_j \quad \text{if} \quad i \neq j, \quad \text{and, for all} \quad i, \quad 1 \leq i \leq n, \quad \mathcal{P}_i \quad \text{is a pdt with pattern} \quad \pi_i = \pi[f_i(\Omega)]_u \quad \text{of the set} \quad S_i = S \cap \pi_i^+.\]
**Example 3.1** Consider the program of Example 1.1. Then (we use \( \Omega \)'s instead of variables),
\[
\text{branch}(\text{first}(\Omega, \Omega), 1),
\]
\[
\text{rule}((\text{first}(0, y) \to \square)),
\]
\[
\text{branch}((\text{first}(s(\Omega), \Omega), 0), 2),
\]
\[
\text{rule}((\text{first}(s(x), y::z) \to y::\text{first}(x, z)))
\]
is a definitional tree for the function \( \text{first} \) (Figure 1).
### 4 Strong sequentiality and inductively sequential TRSs
Regarding normalization strategies, the main result of Huët and Lévy [7, 9] is the following: reduction of needed redexes is normalizing for orthogonal TRSs. In general, the occurrences of such needed redexes are undecidable, but Huët and Lévy define a computable approximation, the (strong) indices. To obtain such an approximation, they use \( \Omega \)-terms.
To calculate indices a function \( \omega \) is used. It is defined by means of a reduction relation \( \rightarrow_\Omega \) [9]: \( C[l] \rightarrow_\Omega C[l'] \) if \( l \neq \Omega \) and there exists \( l \in L_0(\mathbb{R}) \) such that \( t \downarrow l \), i.e., there exists an \( \Omega \)-term \( s \) such that \( t \leq s \) and \( l \leq s \). The relation \( \rightarrow_\Omega \) is confluent and terminating (see [7, 9]).
Let \( \omega(t) \) be the \( \rightarrow_\Omega \)-normal form of \( t \). Instead of the usual definition of index, based on the notion of sequential predicate, we use an equivalent, simpler characterization (see [7, 9]).
**Definition 4.1** Let \( t \in T(\Sigma \cup \{ \Omega \}, V) \) and \( u \in O_0(t) \). Let \( \bullet \) be a fresh constant symbol, and \( t' = t[\bullet]_u \). Then \( u \) is an index of \( t \) iff \( \omega(t')_u = \bullet \) (sometimes we write \( \bullet \in \omega(t') \) for short). The set of indices of \( t \) is denoted by \( I(t) \).
**Proposition 4.2** ([9]) If \( u.v \in I(t[\Omega]_u) \) and \( v \in I(s) \), then \( \text{pdt}(t[\Omega]_u \times v) = \square \).
**Proposition 4.3** ([9]) If \( u \in I(t) \) and \( t \leq t' \), then \( u \in I(t'[\Omega]_u) \).
An \( \Omega \)-normal form is an \( \Omega \)-term \( t \) such that \( O_\mathcal{R}(\pi) = \emptyset \) and \( O_\mathcal{R}(t) \neq \emptyset \). Strongly sequential TRSs are defined as follows.
**Definition 4.4** ([8]) An orthogonal TRS is strongly sequential if every \( \Omega \)-normal form has an index.
When considering CSs, things are simpler.
**Proposition 4.5** ([9]) An orthogonal CS \( \mathcal{R} \) is strongly sequential if \( \forall \pi \in L_0^+(\mathbb{R}) \setminus \{ \Omega \}, I(\pi) \neq \emptyset \).
We use the following property of indices in CSs.
**Proposition 4.6** ([9]) Let \( \mathcal{R} \) be an orthogonal CS. Let \( u \in I(t) \) and \( s \) such that \( \text{root}(s) \in \mathcal{F} \) and \( v \in I(s) \). Then \( u.v \in I(t[s]_u) \).
A strategy which always reduces redexes pointed by indices is called index reduction.
**Theorem 4.7** ([7]) Index reduction is normalizing for orthogonal, strongly sequential TRSs.
### 4.1 Inductive sequentiality of strongly sequential TRSs
Let \( t \in T(\Sigma \cup \{ \Omega \}), t^{< \downarrow}_\mathcal{R} \) is the set of terms which are greater than \( t \): \( t^{< \downarrow}_\mathcal{R} = \{ s \in T(\Sigma \cup \{ \Omega \}) \mid t \downarrow s \} \). Given \( u \in O_0(t) \), \( t^{< \downarrow}_\mathcal{R} \) is the set of terms which are smaller than \( t \) and whose subterm at occurrence \( u \) is not \( \Omega \): \( t^{< \downarrow}_\mathcal{R} = \{ s \in T(\Sigma \cup \{ \Omega \}) \mid t \downarrow u \wedge u \in O(s) \wedge s_u \neq \Omega \} \).
Given a set of terms \( S \subseteq L_0(\mathbb{R}) \) and an occurrence \( u \) of \( \omega(s) \) for all \( s \in S \), we define the equivalence relation \( \equiv_u \) by \( s \equiv_u s' \iff \text{root}(s_u) = \text{root}(s'_u) \), i.e., the terms have the same symbol rooting the subterm at the occurrence \( u \).
In the remainder of the paper, given \( \Omega \)-terms \( \pi \) and \( l \in \pi^+ \) and an occurrence \( u \in O(\pi) \), we define \( \Pi(l, \pi, u) = \pi^+_u \cap l^{< \downarrow}_\mathcal{R} \). The function \( \text{nodes} \) builds a \( \text{pdt} \) for a given function definition:
\[
\text{nodes}(S, \pi, u) =
\]
\[
\text{if} \quad S = \{ l \} \quad \text{and} \quad \Pi(l, \pi, u) = \emptyset \quad \text{then}
\]
\[
\text{rule}(\rho(l))
\]
\[
\text{else} \quad \text{let} \quad \pi' = \min(\cup_{l \in S} \Pi(l, \pi, u))
\]
\[
w' \in I(\pi')
\]
\[
\{ S_1, \ldots, S_n \} = S' \equiv_u w'
\]
in
\[
\text{branch}(\pi', w', \text{nodes}(S_1, \pi', u'), \ldots, \text{nodes}(S_n, \pi', u'))
\]
**Lemma 4.8** Let \( \pi \in T(\Sigma \cup \{ \Omega \}), u \in O_0(\mathcal{R}) \) and \( S \subseteq \pi^+ \), such that, \( \exists f \in \Sigma, M \in S, \text{root}(l_u) = f \) and there exists \( l \in S \) with \( l^{< \downarrow}_\mathcal{R} \neq \emptyset \). Let \( \Pi_S = \cup_{l \in S} \Pi(l, \pi, u) \). Then, \( \min(\Pi_S) = \pi[f(\Omega)]_u \).
Proof. Let $\pi' = \pi[f(\bar{\bigcirc})]_u$. Clearly, $\pi' \in \pi^<_\bigcirc$ and it is minimal in $\pi^<_\bigcirc$. Let $l \in S$ be such that $l \notin \bigcirc$. Clearly, $\Pi(l, \pi, u) \neq \emptyset$ because, since $l \in \pi$, $l \notin \bigcirc$ and $l \notin u$, we have that $\pi' \in l \bigcirc u$. Therefore, $\pi'$ is minimal in $\Pi(l, \pi, u)$. Let $\pi'' \in \Pi(l, \pi, u)$. Since $\text{root}(l \bigcirc u) = f$ and $\text{root}(\pi'' \bigcirc u) \neq \emptyset$, it must be that $\text{root}(\pi'' \bigcirc u) = f$. Thus $\pi'' \leq \pi''$. Since $\pi''$ is arbitrary, it follows that $\Pi(l, \pi, u)$ has a minimum element $\min(\Pi(l, \pi, u)) = \pi'$. This follows for every $l \in S$ with $l \bigcirc u \neq \emptyset$ and the elements $l \in S$ with $l \bigcirc u = \emptyset$ do not introduce new elements in $\Pi_S$, we obtain $\min(\Pi_S) = \pi'$.
The height $h$ of a finite ordered set is the number of elements $a$ of the largest strict chain $a = a_1 < a_2 < \cdots < a_n = b$ going from a minimal element $a$ to a maximum element $b$. We define $h = 0$ if the set is empty.
Then, we can prove the following result.
**Theorem 4.9** Let $\mathcal{R}$ be an orthogonal, strongly sequential TRS. Then, for all defined symbols $f$, $\text{nodes}(L^I_0(\mathcal{R}), \Omega, \epsilon)$ is a definitional tree.
**Proof.** We consider a generic call $\text{nodes}(S, \pi, u)$ under the restrictions $\pi \in T(\Sigma \cup \{\Omega\})$, $u \in O_3(\pi)$, and $S \subseteq \pi \cap L_0(\mathcal{R})$ non-empty and such that $\exists f \in \Sigma, \forall l \in S, \text{root}(l \bigcirc u) = f$. First, we prove that $\text{nodes}$ builds a $\mathcal{P}$ for $S$ with pattern $\pi[f(\bar{\bigcirc})]_u$. Given $l \in S$, let $h_l$ denote the height of $\Pi(l, \pi, u)$. We proceed by induction on the height $h_S = \max_{l \in S}(h_l)$ of $\Pi_S = \cup_{l \in S}\Pi(l, \pi, u)$.
$h_S = 0$: Note that $h_S = 0$ implies that, for all $l \in S$, $h_l = 0$, i.e., $\Pi(l, \pi, u) \neq \emptyset$ for all $l \in S$. Moreover, orthogonality implies that $S = \emptyset$. Otherwise, since for all (distinct) $l \neq l' \in S$, we have $\text{root}(l \bigcirc u) = \text{root}(l' \bigcirc u) = f$, it holds that $\pi[f(\bar{\bigcirc})]_u \leq l$ and $f(\bar{\bigcirc})]_u \leq l'$. Orthogonality implies that $\pi[f(\bar{\bigcirc})]_u \leq l$. This means that $\Pi(l, \pi, u) \neq \emptyset$, a contradiction. Therefore, we are in the if part of nodes and the conclusion is immediate.
$h_S > 0$: Since $h_S > 0$ implies that there is $l \in S$ with $h_l > 0$, this means that $\Pi(l, \pi, u) \neq \emptyset$ for this $l$. Hence, we are in the else part of nodes. By definition of $\Pi(l, \pi, u)$, we have $l \bigcirc u \neq \emptyset$. Then, by Lemma 4.8, $\pi'$ in the algorithm is correctly defined as $\pi' = \min(\Pi_S) = \pi[f(\bar{\bigcirc})]_u$. Since $\pi' \ll l$ and $l \in L_0(\mathcal{R})$, by orthogonality, $\pi'$ is an $\Omega$-normal form. By strong sequentiality, there exists $u' \in I(\pi')$. Strong sequentiality ensures that, for each $l \in S$, $l \bigcirc u' \neq \emptyset$, i.e., $\text{root}(l \bigcirc u') = g_l \in \Sigma$. Otherwise, $u'$ is not an index, since $\pi'[\cdot]_{u'}$ can be refined to a redex of $l$, and hence $u' \in \omega(\pi') \neq \emptyset$. Since $\pi' \ll l$, the height $h_l$ of $\Pi(l, \pi', u')$ is less than $h_l$ for each $l \in S$. Thus, we apply the LH.: each $\mathcal{P}_i = \text{nodes}(S_i, \pi', u')$, $1 \leq i \leq n$, is a $\mathcal{P}$ for $S_i$ with pattern $\pi_i' = \pi'[g_i(\bar{\bigcirc})]_{u'}$, where $g_i$ is the common symbol at occurrence $u'$ of each $l \in S_i$. Then, $\mathcal{P} = \text{branch}(\pi', u', \text{nodes}(S_1, \pi', u'), \ldots, \text{nodes}(S_n, \pi', u'))$ immediately satisfies the minimum and leaves property. By minimality of each $\pi_i'$ in $\mathcal{P}_i$, and by the definition of $\mathcal{P}$, it satisfies the parent and induction properties too.
Now we apply nodes to the arguments $L^I_0(\mathcal{R}), \Omega, \epsilon$ in the hypothesis and we obtain the desired result.
The previous definition of $\text{nodes}$ was closer to our definition of a $\mathcal{P}$ as a kind of ordered set which simplified the proofs. However, using the previous results, we can give a more readable version of the algorithm. Remember that $\rho(\pi)$ associates with $\pi \in L_0(\mathcal{R})$ the rule $l \rightarrow r$ such that $\pi$ is a redex scheme of $l$.
\[
\begin{align*}
\text{nodes}(S, \pi, u) = \\
\text{if } S = \{\pi\} \text{ then } \text{rule}(\rho(\pi)) \\
\text{else let } f = \text{root}(l \bigcirc u) \text{ for some } l \in S \\
\pi' = \pi[f(\bar{\bigcirc})]_u \\
u' \in I(\pi') \\
\{S_1, \ldots, S_n\} = S/\equiv_{u'} \\
in \text{branch}(\pi', u', \text{nodes}(S_1, \pi', u'), \ldots, \text{nodes}(S_n, \pi', u')) \\
\end{align*}
\]
**4.2 Strong sequentiality of inductively sequential TRSs**
**Proposition 4.10** Let $\mathcal{P}_f$ be a $\mathcal{P}$ for the function $f$ of a CS. Then every inductive occurrence $u$ in a branch node $\text{branch}(\pi, u, \mathcal{P})$ of $\mathcal{P}_f$ satisfies $u \in I(\pi)$.
**Proof.** Let $\mathcal{P}_f = \text{branch}(\pi, u, \mathcal{P})$. Note that $u \in O_3(\pi)$. By contradiction: Since we consider CSs, if $u \notin I(\pi)$, then $\pi'[\cdot]_{u'} \uparrow l$ for some redex scheme $l$ in $\text{maximal}(\cup_{\mathcal{P} \in \mathcal{P}} (\mathcal{P} \uparrow l))$. Since $\pi \ll l$, this means that the pattern $\pi'$ of $\mathcal{P}$, the $\mathcal{P}$ in $\mathcal{P}$ which contains $l$, verifies $\text{root}(\pi'[\cdot]_{u'}) = \emptyset$, contradicting the definition of a $\mathcal{P}$, since it must be that $\text{root}(\pi'[\cdot]_{u'}) \in \Sigma$.
This result does not hold for arbitrary $\mathcal{P}$s.
Example 4.11 Consider the orthogonal TRS
\[
\begin{align*}
f(g(h(x), a), y) & \rightarrow x & c & \rightarrow a \\
g(x, b) & \rightarrow g(h(x), a)
\end{align*}
\]
Partial definitional trees for \( f \) are drawn in Figure 2.
The inductive occurrence 1.1 is not an index in the pattern \( f(g(\Omega, \Omega, \Omega)) \) of the first pdt. By using nodes, we obtain the second definitional tree for every inductive occurrence is an index.
Theorem 4.12 Let \( R = (\Sigma, R) \) be an inductively sequential CS. Then, \( R \) is strongly sequential.
Proof. From Proposition 4.5, we prove by contradiction that every proper prefix \( \Omega < p < l \) of a redex scheme \( l \) has an index. Assume \( I(p) = \emptyset \).
Let \( \Omega < \pi_1 < \cdots < \pi_n < l \) be the chain of patterns in the branch nodes of a pdt for the function \( f = \text{root}(p) \) which contains \( l \). It is not possible to have a \( \pi_j, 1 \leq j \leq n \) such that \( p \leq \pi_j \). Otherwise, by Proposition 4.10 and Proposition 4.2, \( p \) also has an index. Thus, \( \pi_i \parallel p \) for some \( i, 1 \leq i \leq n \). Let us consider the maximal \( \pi \in \{\pi_1, \ldots, \pi_n\} \) such that \( \pi \leq p \) and \( \pi \leq \pi_i \). \( \pi \) exists, because \( \pi_1 = f(\bar{\Omega}) \), and \( \Omega < f(\bar{\Omega}) \leq p < l \). Let \( u \) be the inductive occurrence for the branch node with pattern \( \pi \). By Proposition 4.10, \( u \in I(\pi) \).
We have \( p_v = \Omega \). Otherwise, since \( p < l \) and \( \text{root}(t_w) = \text{root}(p_v) \), there is \( \pi' > \pi \) such that \( \pi' \leq p \) and \( \pi' \leq \pi_i \), thus contradicting the maximality of \( \pi \). By Proposition 4.3, \( u \in I(p) \).
This theorem does not hold for general strongly sequential TRSs, as the following example shows.
Example 4.13 Consider the following TRS which is not strongly sequential (from [7]):
\[
\begin{align*}
f(g(a, x), f(b, y)) & \rightarrow x & g(d, d) & \rightarrow d \\
f(g(x, a), f(c, y)) & \rightarrow x
\end{align*}
\]
\( f \) and \( g \) admit definitional trees, and nodes can build them, because every redex scheme has some index.
Theorems 4.9 and 4.12 entail our main result.
Theorem 4.14 An orthogonal CS is strongly sequential iff it is inductively sequential.
4.3 Outermost-needed reduction
A definitional tree determines a rewriting strategy, namely the outermost-needed rewriting strategy:
Definition 4.15 ([9]) The (partial) function \( \varphi \) takes arguments \( t = f(t) \), \( f \in F \) and a pdt \( P \) such that \( \min(P) \leq t \), and yields a redex occurrence \( u \in O_P(t) \):
\[
\begin{align*}
\varphi(t, P) = \\
\varepsilon & \quad \text{if } P = \text{rule}(\alpha) \\
\varphi(t, P) & \quad \text{if } P = \text{branch}(\pi, u, P_1, \ldots, P_n) \\
& \quad \text{and } \min(P_i) \leq t \text{ for some } i \\
u \cdot \varphi(t_{\bar{v}}, P_\bar{v}) & \quad \text{if } P = \text{branch}(\pi, u, P_1, \ldots, P_n), \quad (\ast) \\
& \quad \text{root}(t_{\bar{v}}) = g \in F, \text{ and } P_\bar{v} \text{ is a definitional tree for } g.
\end{align*}
\]
Note that, dealing with CSs, the second and third cases are disjoint. This is because if \( \text{root}(t_{\bar{v}}) = g \in F, \) then since \( \pi \leq \min(P_i) \) for all subpdt \( P_i \) of \( P = \text{branch}(\pi, u, P_1, \ldots, P_n) \), it is not possible to have \( \min(P_i) \leq t \) since \( \text{root}(\min(P_i)) \in C \). We show that \( \varphi \) is equivalent to index reduction.
Theorem 4.16 Let \( R \) be an inductively sequential CS and \( u = \varphi(t, P) \). Then \( u \) is an index of \( I(\Omega)_u \).
Proof. Induction on the number of visited definitional trees. In the case base (\( n = 1 \)), \( u = \varepsilon \) and the conclusion easily follows. Otherwise (\( n > 1 \)), the occurrence \( u \) can be split up into \( u = u \circ v \), where \( v \) is an occurrence of the pdt \( P \) and \( w \) has been used to reduce \( t_w \) and, because \( R \) is a CS, \( \text{root}(t_w) \in F \), with \( v \) the inductive occurrence for some pattern in a branch node of \( P \). By Proposition 4.10, \( v \in I(\pi) \).
Since \( \pi \leq t \), by Proposition 4.3, \( v \in I(\Omega)_u \). Then, by I.H., \( w \in I(t_w, \Omega)_{\bar{v}} \) and the conclusion follows by Proposition 4.6.
Theorem 4.9 suggests that definitional trees can be used with general strongly sequential TRSs. The outermost-needed strategy, as given in Definition 4.15, cannot be used to successfully evaluate a term in general (i.e., non-constructor-based) TRSs. For instance, consider the TRS in Example 4.11, \( t = f(g(x, b), y) \) and let \( P_f \) be a pdt for the function \( f \) if we try to compute \( \varphi(t, P_f) \). Then \( \varphi(t, P_f) = \varphi(t, P_f) \) are undefined, i.e., the strategy cannot proceed. This can be solved by changing (\( \ast \)) in Definition 4.15 as follows: \( \varphi(t, P_f) = u' \cdot v \) if \( P_f = \text{branch}(\pi, u, P_1, \ldots, P_n) \), \( \text{root}(\pi_{\bar{v}}) \neq \text{root}(t_{\bar{v}}) \), \( f' \in F \), for all \( j, 1 \leq j \leq n; \pi' = \pi[f'({\bar{\Omega}})]_u, \) and \( u' < u' \leq u \) is the minimal occurrence such that \( \pi'_{\bar{v}} \) is compatible with some redex scheme, \( P_{\bar{v}} \) is a definitional tree for \( g = \text{root}(\pi'_{\bar{v}}) \), and \( \varphi(t_{\bar{v}}, P_{\bar{v}}) = v \).
This works well when considering CSs (it is equivalent to Definition 4.15). However, this does not ensure that \( \varphi \) is index reduction when considering general TRSs. This can be clarified by comparing the strategy with the standard Huet and Lévy procedure, as discussed in the following section.
5 Definitional trees and matching dags
To implement normalization strategies without lookahead, the matching dags (directed acyclic graphs) of Huet and Lévy can be used with any strongly sequential TRS. Simpler structures are the index trees of Strandh [11] which have been proved equivalent to matching dags by Durand [6]. An index tree is a finite state automaton which has, in addition to the usual transfer function, also a failure function. The set of final states is $L_0(R)$. Non-final states are index points, pairs $(\pi, u)$, where $\pi \in L_0(R)$, and $u$ is an index of $\pi$ and both satisfy some special conditions (see [6]). The initial state is $(\Omega, e)$. The transfer function, written $\delta(s, f)$, yields a new state of the automaton, given a state $s$ and a function symbol $f$: $\delta((\pi, u), f) = \langle \pi[f(\overline{\pi})]_u, v \rangle$ (or just $\delta((\pi, u), f) = \pi[f(\overline{\pi})]_u$ if $\pi[f(\overline{\pi})]_u \in L_0(R)$). The failure function, $\phi$, is $\phi(s) = s'$ iff $s'$ is an immediate failure point of $s$. Failure points are states of the automaton which are expected to deal with a failing partial matching, by resuming the matching of a subterm of the currently inspected term. In the most general definition of an index tree, some states may not be reachable from the initial state $(\Omega, e)$ via transfer transitions (using $\delta$) only. Thus, only the failure function can provide access to these nodes of the tree. Orthogonal TRSs which can be given such an index tree are called bounded TRSs. Durand proves that the class of bounded TRSs and strongly sequential TRSs coincide. The proof is given by showing that there is an immediate failure point to the corresponding matching dag of Huet and Lévy and the index trees of Strandh.
Strandh defines the forward-branching index trees, for which all states of the index tree can be reached via the transfer function $\delta$ from the initial state.
We provide a simple connection between index trees and definitional trees: transitions $\delta((\pi, u), f_1) = \langle \pi[f_1(\overline{\pi})]_u, v_1 \rangle, \ldots, \delta((\pi, u), f_n) = \langle \pi[f_n(\overline{\pi})]_u, v_n \rangle$ can be written as branch$(\pi, u, P_1, \ldots, P_n)$, where the pattern of each $P_i$ is $\pi_i = \pi[f_i(\overline{\pi})]_u$. Each initial transition $\delta((\Omega, e), f) = \langle f(\overline{\Omega}), u \rangle$ can be seen as the starting point of the pdt for the function $f$. When considering forward-branching index trees, the correspondence is even closer. However, pdts are not equivalent to the previous structures. For instance, consider the bounded TRS (from [6])
$$f(g(x, a), a) \rightarrow a \quad g(b, b) \rightarrow a$$
and the pdts in Figure 3.
The patterns and inductive occurrences of these pdts are taken by following the index tree for the TRS, as given in [6]. Of course, if we do not do this, we cannot ensure that the composition of the occurrences considered for the partial matchings (which are indices of the corresponding predeceses) is an index. This means that, even if we use nodes, that always select (arbitrary) indices for inductive occurrences, we cannot ensure index reduction. But we have more involved situations. For instance, if we reduce $t = f(g(\Delta_1, \Delta_2), a)$, where $\Delta_1, \Delta_2$ are redexes, it is not difficult to see that $\varphi$ (modified) reduces the redex $\Delta_1$ which is not a needed redex. This is because, when we fail in matching $f(g(\Omega, a), a)$ (we underline the last considered occurrence, 1.2) against our term, we try to reduce $g(\Delta_1, \Delta_2)$ and we must jump to a pdt for $g$, in order to continue the matching. If we have the first pdt (recall that, in our strategy, only one pdt is available), then we choose to reduce $\Delta_1$. However, $\Delta_1$ is not needed in the whole context, since $f(g(\bullet, \Omega), a) \rightarrow_\Omega \Omega$. With an index tree, the failure function selects the other pdt for $g$, which properly continues the matching tasks by looking at the occurrence 2 of $g(\Delta_1, \Delta_2)$. This is consistent with the situation before the jump.
The modification of $\varphi$ would work if we consider forward branching TRSs (because they do not have such additional nodes) and we use pdts having the same pattern and inductive occurrences as the corresponding forward-branching index tree. The previous TRS is not forward-branching. However, even with such modifications, we loose efficiency, because, having a very simple definition of the failure function (we always jump to the root node of a new pdt), we would read more than once some symbols. Therefore, it seems that there is no advantage in using pdts with general TRSs.
References
|
{"Source-Url": "https://www-ps.informatik.uni-kiel.de/~mh/papers/IPL98.pdf", "len_cl100k_base": 10782, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 37368, "total-output-tokens": 12397, "length": "2e13", "weborganizer": {"__label__adult": 0.0004150867462158203, "__label__art_design": 0.0006604194641113281, "__label__crime_law": 0.0005321502685546875, "__label__education_jobs": 0.0017919540405273438, "__label__entertainment": 0.0001596212387084961, "__label__fashion_beauty": 0.00024330615997314453, "__label__finance_business": 0.0005426406860351562, "__label__food_dining": 0.0005860328674316406, "__label__games": 0.001003265380859375, "__label__hardware": 0.00151824951171875, "__label__health": 0.001010894775390625, "__label__history": 0.0004472732543945313, "__label__home_hobbies": 0.0002061128616333008, "__label__industrial": 0.000995635986328125, "__label__literature": 0.0008378028869628906, "__label__politics": 0.0005083084106445312, "__label__religion": 0.000812530517578125, "__label__science_tech": 0.298828125, "__label__social_life": 0.00013816356658935547, "__label__software": 0.00824737548828125, "__label__software_dev": 0.6787109375, "__label__sports_fitness": 0.000370025634765625, "__label__transportation": 0.0010013580322265625, "__label__travel": 0.00022971630096435547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34975, 0.01427]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34975, 0.73689]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34975, 0.77718]], "google_gemma-3-12b-it_contains_pii": [[0, 4714, false], [4714, 11076, null], [11076, 17074, null], [17074, 22889, null], [22889, 28649, null], [28649, 33431, null], [33431, 34975, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4714, true], [4714, 11076, null], [11076, 17074, null], [17074, 22889, null], [22889, 28649, null], [28649, 33431, null], [33431, 34975, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34975, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34975, null]], "pdf_page_numbers": [[0, 4714, 1], [4714, 11076, 2], [11076, 17074, 3], [17074, 22889, 4], [22889, 28649, 5], [28649, 33431, 6], [33431, 34975, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34975, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
b287e7d9b926d5b45cc85813013da17cc0d5b886
|
Mnemosyne (MNEMOSYNE)
version 1.2
Typeset in \LaTeX{} from SGML source using the DOCBUILDER 3.2.2 Document System.
Chapter 1
Mnemosyne User’s Guide
1.1 Introduction
Mnemosyne is the query language of Mnesia and provides a simple syntax for complex queries. Mnesia is a distributed Database Management System, utilized for telecommunications applications and other Erlang applications which require continuous operation and soft real-time properties. Mnesia is part of the Open Telecom Platform (OTP), which is a control system platform for building telecommunications applications.
1.1.1 Scope and Purpose
This manual is included as a part of the OTP document set. It describes how to use Mnemosyne queries. Programming constructs are described, and numerous programming examples are included to illustrate the use of Mnemosyne.
1.1.2 Pre-requisites
It is assumed that the reader is familiar with system development principles and database management systems. Readers are also assumed to be familiar with the Erlang programming language in general, and the Mnesia application in particular.
1.2 Database Queries
This chapter describes Mnemosyne, the Mnesia database query language, and the syntax, semantics, and rules which apply to Mnesia queries. The following sections are included:
- Mnemosyne - the Mnesia query language
- Evaluating queries
- Mnesia query examples
- Matching
- Generated functions
The following notational conventions are used in this chapter:
1.2.1 Mnemosyne - the Mnesia Query Language
Mnemosyne is the query language and the optimizing query compiler for the Mnesia Database Management System.
General Information about Queries
Database queries are used when more complex operations than just a simple key-value lookup are required on a database. A query can find all records in a table that fulfills a given property. For example, think of a table storing the status of subscriber lines in a telephone exchange. A query in such a table can take the format: “Which subscriber lines are ‘blocked’?”.
A query can also find records on the basis of their relationship to other records in the same table, or in other tables. If the table, which stores subscriber lines, is accompanied by a table, which pairs subscriber numbers with a subscriber line identification, we can modify our previous query and ask: “Which subscriber numbers are ‘blocked’?”. This can be answered by constructing a query, which finds the blocked subscriber line identifications in the subscriber line table, and then finds the associated subscriber number in the table, which pairs subscriber number and subscriber line identifications.
However, the proposed solution may not be the most efficient solution, because it depends on what the tables look like in runtime. In other words, how many records the table contains, and the number of different values stored.
In a situation where there are only a couple of subscriber numbers but a million blocked lines, it would be far more efficient to first find the subscribers and then check if their line is blocked. The query evaluation order depends on how large the tables are compared to each other. The evaluation order also depends on key and other value distribution, and if there are any indices defined (refer to Mnesia Chapter 5: Indexing for more information).
The query compiler resolves the evaluation order. We need only express what we want to do, and the query compiler and query evaluator will determine the best evaluation order. Therefore, we can express the query in the most readable form.
Queries in Mnesia
Queries in Mnemosyne use first order predicate logic (similar to Prolog), but in an syntax suitable for Erlang. The “query list comprehension” used in Mnemosyne is taken from the functional languages community. The advantage over embedded SQL, is that the constructs integrate smoothly with the Erlang language.
To illustrate the Mnemosyne query language, we will show the Erlang code for the subscriber line and subscriber number tables discussed above. We define two tables subscriber and line. Their corresponding record declarations in the file subscriber.hrl are:
```erlang
-record(subscriber, {snb, cost_limit, li}).
-record(line, {li, state}).
```
The query “which subscriber numbers are blocked?” can also be expressed as “which subscribers have lines which are in state ‘blocked’”. This query can be coded as follows:
```
query
[ S.snb || % collect the subscriber number
S <- table(subscriber), % where S is taken from the subscriber table
L <- table(line), % and L is taken from the line table
L.state = blocked, % and the state of that line is blocked
L.li = S.li ] % and L and S uses the same li
end
```
In the example above, the aim is to get an answer from a logical relation. Consider also the following example:
```
query [E.name || E <- table(employee),
E.sex = female]
end
```
This means “the Erlang list of all female employees”. A formulation closer to the list comprehension is: “the Erlang list of all names of E such that E is in the table employee and E’s sex is female”.
Some words have a direct correspondence to the elements in the list comprehension notation:
<table>
<thead>
<tr>
<th>the Erlang list of all</th>
<th>[ ]</th>
</tr>
</thead>
<tbody>
<tr>
<td>such that</td>
<td></td>
</tr>
<tr>
<td>is in</td>
<td><=</td>
</tr>
<tr>
<td>and</td>
<td>,</td>
</tr>
</tbody>
</table>
Table 1.1: Natural Language Translation
Another query component is rules, which can be compared to views in Relational Databases, where the purpose is to define a “virtual table”. This “table” looks like an ordinary table to the user, which means that queries can be formulated on stored data (as well as views). In the subscriber line example, a rule can give the subscriber number and the corresponding line status from both tables, and there is no need to create a third table.
The rule is a definition of how to calculate the records on demand from a query. In Erlang modules, rules are written with the same syntax as the bodies in the query list comprehensions. They are exported and can be used by other modules.
Our subscriber example formulated as a rule would look as follows:
```
branked_subscribers(S, subscriber) :-
S <- table(subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li.
```
This rule can be used in a query in the same manner as a table but with the keyword rule substituted for table.
```
query [ S.snb || S <- rule(branked_subscribers) ] end
```
Query Syntax
Database queries can be included in an Erlang program, but there must be a directive in the Erlang file which informs the compiler about its behavior towards queries. This directive is:
```
-include_lib("mnemosyne/include/mnemosyne.hrl").
```
The high-level syntax of the query list comprehension is:
```
query [ <pattern> || <body> ] end
```
The `<body>` is a comma-separated sequence of:
1. `<logical-variable>` <- table( `<table-name>` [ , `<table-type>` ] )
2. `<logical-variable>` <- rule( `<rule-name>` )
3. `<logical-variable>` <- rule( `<rule-name>` )
4. `<logical-variable>` <- rule( `<module>` : `<rule-name>` )
5. `<logical-variable>` <- `<erlang-list-expression>`
6. `<expression>` `<relop>` `<expression>`
7. `<erlang-test-expression>`
The `<relop>` operators are:
- = for unification
- /= for not unification
- < for less than
- > for greater than
- <= for equal to or less than
- >= for equal to or greater than.
A `<logical-variable>` is written exactly as an Erlang variable. The `<table-name>`, `<table-type>`, `<rule-name>` and `<module>` are atoms. The `<table-name>` and `<table-type>` can also be an Erlang variable. The logical variables are local to a list comprehension and shadows any Erlang variable with the same name.
The `<pattern>` is an Erlang term without function calls. It may contain (bound) Erlang variables and it usually has one or more `<logical-variable>`, since these are used to get data out from the query body and into the produced list.
An `<expression>` is any Erlang expression which may include function calls and `<logical-variable>`. The variant `<erlang-list-expression>` is an `<expression>` which must produce a list where all elements are records of the same type.
The `<erlang-test-expression>` is an `<expression>` which has the values true or false.
Erlang variables are allowed in all variations of `<expression>` and in `<pattern>`. They must be bound in the query list comprehension.
Query Semantics
The constructs used in the Mnemosyne query language have the following meanings:
- **Comma:** The comma, used to separate different body elements, is equivalent to "and". Thus, the body can be viewed as a collection of tests and statements which should be true for each solution which is produced when evaluating the query list comprehension. Refer to subscriber query [page 2] as an example of this.
- **<logical-variable> <- ....** This expression means that the variable is taken from the values in the expression to the right of the arrow. For example, E <- [#e{a=1}, #e{a=2}] says that E takes the values #e{a=1}, or #e{a=2}
- **<-**. These constructs usually generate values. However, if the logical variable is bound it tests that value. If a test fails it means that the query tries another alternative. For example:
```
query [ X.a || X <- [#e{a=1}, #e{a=2}],
X <- [#e{a=3}],
.... ]
end
```
The body means that the field 'a' of X should be 3 and at the same time either 1 or 2. So the list of solutions will always be empty.
The test `<expression> <rellop> <expression>` and the true-or-false returning test `<erlang-test-expression>` simply filters out the solutions. The purpose of the latter test is to provide user defined data tests.
We will next consider the logical variables associated records in an expression like x <- table(a). We have already established the following rules and assumptions:
1. the values stored in tables are records
2. all records in a table must be of the same type
3. by default, the record definition has the same name as the table itself
4. The `<logical-variable>` must have the same record association as the records produced by the right side of the `<-` constructs.
In the example X <- table(a), the associated record of x is a because table a stores records with the name a. Since release 3.4 of Mnesia it has been possible to separate record name and its table type. If the type of the table is different from its name, this can be specified in Mnemosyne using X <- table(Name, Type) where Name is the Name of the table and Type is the record name.
Similar to tables, rules produce or test records. The return type for a rule is by default the name of the rule. Rules can be declared to return other types. This makes it possible to construct a rule for some special cases with a name like blocked_subscriber which still produces or tests subscriber records.
In Erlang we must always tell the compiler which record definition it should use by putting the record name after a hash mark. In general, this is not needed in Mnemosyne since, in most cases, the query compiler can deduce the associated record. That is the reason $s$.li is acceptable instead of the full $s#subscriber.li$. It will not cause an error if the longer version was written, but if we do write the record name it must be the same record name as the one the query compiler deduces. Sometimes the compiler is unable to find the associated record. When this happens, an error message is issued. It is also preferred to write out the type of the associated record for performance reasons. If the associated record is part of a complex constraint, the constraint may be compiled to a function if the type of the associated record is known (explicitly or deducable) at Erlang compile time.
Chapter 1: Mnemosyne User’s Guide
**Note:**
A function used in a query list comprehension must never directly or indirectly:
1. have side effects;
2. access the database neither by a query nor by Mnesia functions;
3. spawn processes, or;
4. send or receive messages.
Rules
A rule is composed of clauses and each clause has the structure:
<head> :- <body>
- The clauses are separated by semicolon, and the rule is terminated by a dot.
- The <head> looks like an Erlang function with one or two arguments, where the first argument is a variable and the second, optional, argument an atom. If there is a second argument, it must be present in all clauses and have the same value.
- The <body> has the same syntax as the <body>. in query list comprehensions [page 4]
- The argument variable of a rule clause has an associated record.
- The default associated record is the name of the rule. This can be changed by declaring the associated record type in the head of the clause:
<rule-name> (<return-var>, <record-name>)
The syntax used in previous mnemosyne versions, by declaring the the associated recordtype with an argtype declaration still works but is depreciated.
**Note:**
The <logical-variable> mentioned in the <head> must also occur in the <body>.
Review the rule example [page 3].
```erlang
blocked_subscribers(S, subscriber) :-
S <- table(subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li.
```
It produces a list of subscriber records. Rules with a single argument return records of the same type as the name of the rule. For example, the following rule produces records of type blocked
```erlang
```
1.2: Database Queries
-record (blocked, {snb, li}).
blocked (X) :-
S <- table (subscriber),
L <- table(line),
L.state = blocked,
L.li = S.li,
X = #blocked{snb=S#subscriber.snb, li=S#subscriber.li}.
1.2.2 Evaluating Queries
The previous sections described how to define queries. This section describes how to evaluate queries.
The principle is simple: query list comprehensions, compile and optimize the query and return a handle. This handle is then passed on for execution:
Handle = query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
AllAnswers =
mnesia:transaction(
fun() ->
mnemosyne:eval(Handle)
end)
There are three ways of evaluating queries. The mnemosyne:eval/1 is the simplest of the three. It takes a handle and returns all solutions. Sometimes we only need to view a few solutions, examine them and possibly get more. Think of an airline routing database: you do not want to know all possible connections between two cities, but usually enough information is given after observing one or two.
Use the cursor with a query evaluation to produce a few solutions only. With a handle we create a cursor by calling mnemosyne:cursor/1. With the cursor we can repeatedly call mnemosyne:next_answers to get more solutions. When an empty list is returned there are no more possible solutions. Delete the cursor with mnemosyne:delete_cursor/1.
Handle = query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
AFewAnswers =
mnesia:transaction(
fun() ->
Cursor = mnemosyne:cursor(Handle),
% now get at least two but not
% more than five solutions:
L = mnemosyne:next_answers(Cursor,2,5),
mnemosyne:delete_cursor(Cursor),
L
end)
A query evaluation can be time consuming, but can be broken up by using the cursor with `setup_query/1` and `init_query/1`:
```
Handle =
query
[ S.snb || S <- table(subscriber),
S.li = none]
end,
QuerySetup = mnemosyne:setup_query(Handle),
AFewAnswers =
mnnesia:transaction(
fun() ->
Cursor = mnemosyne:init_query(QuerySetup),
mnemosyne:next_answers(Cursor, 5, 5)
end),
% Here we may call more init_query-next_answers constructions
% with the same Handle. Note that the query is evaluated from
% "scratch" because of the call to mnemosyne:init_query/1.
mnemosyne:delete_query(QuerySetup)
```
Because of table updates, a query which is compiled and optimized may be incorrect when the handle returns. This can be rectified with the function `mnemosyne:reoptimize/1` which takes a handle, re-optimizes the query and returns a new handle.
### 1.2.3 Query Examples
This section describes an example which illustrates the use of Mnemosyne. The example given is of a simplified local exchange, with AX E-10 exchange as a model. The purpose of this section is to show different constructs in a telecom environment. It should not be taken as a proposed data model for a modern telecom system.
Our telephone example includes the following components, relationships, and events:
- The exchange has a number of subscribers.
- Each subscriber has a subscriber number, which is abbreviated `snb`.
- Each physical line enters the exchange through a line interface card. Lines are abbreviated `li`.
- The `li` has an associated status which indicates if the line is blocked, or available.
- One single table stores the accumulated cost for each subscriber.
**Program Definitions**
We identify three tables:
- `subscriber` with subscriber numbers `snb`, line interface number `li`, and a maximum cost `cost_limit` which must not be exceeded.
- `line` with line interface number `li`, and its `state`.
- account, a table which stores the cost of calls. It has an snb field, and the accumulated cost in cost.
The corresponding record definitions are stored in a file named subscriber.hrl, which has the following record definitions:
```erlang
-record(subscriber, {snb, cost_limit, li}).
-record(line, {li, state}).
-record(account, {snb, cost}).
```
The program file is titled subscriber.erl. It declares the module name subscriber, calls the record definition in subscriber.hrl, and Mnesia query support mnemosyne.hrl.
```erlang
-module(subscriber).
-compile(export_all).
-include("subscriber.hrl").
-include_lib("mnemosyne/include/mnemosyne.hrl").
```
We then create the required tables and load data by entering table definitions into a file named subscriber.tables, which has the following content:
```erlang
% % Subscribers
{subscriber, 1230, 0, none}.
{subscriber, 1231, 0, none}.
{subscriber, 1232, 0, none}.
{subscriber, 1233, 0, none}.
{subscriber, 1234, 100, {li,1}}.
{subscriber, 1235, 200, {li,3}}.
{subscriber, 1236, 150, {li,2}}.
{subscriber, 1237, 0, none}.
{subscriber, 1238, 0, none}.
{subscriber, 1239, 0, none}.
% % Lines
{line, {li,0}, blocked}.
{line, {li,1}, normal}.
{line, {li,2}, normal}.
{line, {li,3}, blocked}.
```
Chapter 1: Mnemosyne User's Guide
%%% Accounts
{account, 1234, 0}.
{account, 1235, 0}.
{account, 1236, 0}.
{account, 1237, 0}.
Program Output
In our program, this file is called with the statement:
mnesia:load_textfile("subscriber.tables")
To retrieve a list of all free subscriber numbers we call the following function in a transaction:
free_subscriber_numbers() ->
mnemosyne:eval(
query [ S.snb || S <- table(subscriber),
S.li = none]
).
The rule too_high_cost/0 locates and returns all subscribers with an accumulated cost that exceeds
their limit:
limit_exceeded(S, subscriber) :-
S <- table(subscriber),
A <- table(account),
A.snb = S.snb,
A.cost > S.cost_limit.
We could find all subscriber numbers of subscribers who have exceeded their cost limit as follows:
Q = query
[ S.snb || S <- rule(limit_exceeded) ]
end
1.2.4 Matching
Mnesia provides the programmer with a method of matching objects against a pattern. This is the Mnesia matching function:
\[
\text{mnesia:match_object(Pattern)} \rightarrow \text{transaction abort | ObjList.}
\]
This function matches Pattern for objects. A Pattern is a tuple with the name (identity) of the table as the first element. The table collates all data retrieved.
In comparison to a list comprehension query, \text{mnesia:match_object} is a low level function. The following two functions both return the same objects; however, the second example uses matching.
\[
f1() \rightarrow
\begin{align*}
Q &= \text{query} \\
& \quad \left[ E \mid E \leftarrow \text{table(employee)}, \\
& \quad \quad \quad E.\text{sex} = \text{female} \right] \\
& \quad \text{end}, \\
F &= \text{fun()} \rightarrow \text{mnemosyne:eval}(Q) \text{ end}, \\
& \quad \text{mnesia:transaction}(F).
\end{align*}
\]
and
\[
f2() \rightarrow
\begin{align*}
\text{WildPat} &= \text{mnesia:table_info(employee, wild_pattern)}, \\
\text{Pat} &= \text{WildPat#employee}\{\text{sex} = \text{female}\}, \\
F &= \text{fun()} \rightarrow \text{mnesia:match_object}(\text{Pat}) \text{ end}, \\
& \quad \text{mnesia:transaction}(F).
\end{align*}
\]
The pattern supplied to the \text{mnesia:match_object/1} function must be a valid record, and the first element of the provided tuple must be a valid table name. The special element \text{'}\_\text{'} matches all the records.
There are advantages in using the Mnemosyne query syntax instead of the \text{mnesia:match_object/1} function:
- The pattern is computed in compile time by the Mnemosyne compiler instead of doing it in run time in the \text{f2/0} function.
- Mnemosyne provides more sophisticated evaluation optimizations based on indices and on statistics from and about the table. Whereas, the optimizations that \text{mnesia:match_object/1} function provides are limited in both scope and number. The \text{mnesia:match_object} function is also performed during run time, which in turn reduces performance.
- The Mnemosyne query syntax is quite compact and makes it easier to express complex queries.
It is also possible to use the match function if we want to check the equality of different attributes. Assume we have the following record definition:
\[
\text{-record(foo, \{a, b, c\}).}
\]
The pattern \{foo, \'$1\', \'$1\', \'\_\'} then extracts all objects of type foo where the first two attributes have the same value.
If the key attribute is bound in a pattern, the match operation is very efficient. The pattern \{foo, 123, \'\_\', elvis\} can be used to extract all objects with key 123, and the last attribute set to the atom elvis. This is the same as extracting all the elvis objects from the result of \texttt{mnesia:read(foo, 123)}, but more efficient.
If the key attribute in a pattern is given as \'\_\', or \'\$1\', the whole foo table must be searched for objects that match. If the table is large, this may be a time consuming operation. This can be remedied with indices (refer to Mnesia Chapter 5: Indexing for more information).
This chapter closes with an example of information extraction from a Company database:
- all employees who have a salary higher than \(X\).
- all employees who work in the \texttt{Dep} department.
The first example demonstrates the query execution with list comprehension notation. The second example illustrates a query coded with a matching function.
The list comprehension based implementation looks as follows:
```erl
get_emps(Salary, Dep) ->
Q = query
[E || E <- table(employee),
At <- table(at_dep),
E.salary > Salary,
E.emp_no = At.emp,
At.dept_id = Dep]
end,
F = fun() -> mnemosyne:eval(Q) end,
mnesia:transaction(F).
```
The data model for the Company database introduced in the Mnesia documentation was designed to facilitate the posting of queries like the one shown above.
To implement the same query by directly searching the database is more complex. The following function does precisely this:
```erl
get_emps2(Salary, Dep) ->
Epat = mnesia:table_info(employee, wild_pattern),
Apat = mnesia:table_info(at_dep, wild_pattern),
F = fun() ->
All = mnesia:match_object(Epat),
High = filter(All, Salary),
Alldeps = mnesia:match_object(Apat),
filter_deps(High, Alldeps, Dep)
end,
mnesia:transaction(F).
filter([E|Tail], Salary) ->
if
E#employee.salary > Salary ->
[E | filter(Tail, Salary)];
true ->
```
12
1.2: Database Queries
filter(Tail, Salary)
end;
filter([], _) ->
[].
filterdeps([E|Tail], Deps, Dep) ->
case search_deps(E#employee.name, Deps, Dep) of
true ->
[E | filter_deps(Tail, Deps, Dep)];
false ->
filter_deps(Tail, Deps, Dep)
end;
filter_deps([], _,_) ->
[].
search_deps(Name, [D|Tail], Dep) ->
if
D#at_dep.emp == Name,
D#at_dep.dept_id == Dep -> true;
true -> search_deps(Name, Tail, Dep)
end;
search_deps(Name, Tail, Dep) ->
false.
The function mnesia:match_object/1 will automatically make use of indices if any exist. However, no
heuristics are performed in order to select the best index, if more than one exists.
As can be seen, the list comprehension provides a more elegant solution.
1.2.5 Matching in Record Fields
There is a difference when matching record fields in a mnesyne list comprehension and in Erlang in
general (for example, a function clause header). The following code returns true for all employee where
emp_id is 312 or 400:
test_employee(#employee{emp_id = 312}) -> true;
test_employee(#employee{emp_id = 400}) -> true;
test_employee(_) -> false.
That is, it does not check other fields of the employee record. Compare that with the following
mnesyne query:
query [E || E <- table(employee),
E <- [#{employee{emp_id=312},
#{employee{emp_id=400}}]]
The query will return all employees from the employee table who's emp_id is either 312 or 400 and have
the other fields set to the default values for an employee. To select all items that have a field set to some
values (disregarding the other fields) the constraint can be put in separate function. For example, select
all employees who's emp_id is either 312 or 400 independently of other fields:
query [E || E <- table(employee),
test_employee(E)]
test_employee(#employee{emp_id = 312}) -> true;
test_employee(#employee{emp_id = 400}) -> true;
test_employee(_) -> false.
If there is only one acceptable value for a record field it is more efficient to write it directly in the query. Select employees whose emp_id is 312:
query [E || E <- table(employee),
E#employee.emp_id = 312]
1.3 Mnemosyne - Release Notes
This document describes the changes made to the Mnemosyne application. The intention of this document is to list all incompatibilities as well as all the enhancements, bugs and adjustments that have been noted for each previous release of Mnemosyne. Each release thus constitutes one section in this document. The title of each section is the Mnemosyne version number.
1.3.1 Mnemosyne 1.2.5
Improvements and new features
None.
Fixed Bugs and malfunctions
- Complex queries failed (looped forever) if there were more than 1000 entries in the table
OTP Id: OTP-3656
Aux Id: Seq-4842
1.3.2 Mnemosyne 1.2.4
Improvements and new features
None.
Fixed Bugs and malfunctions
- Mnemosyne failed to do proper variable substitution in queries with records constructions where a field was assigned the value of variable. The generate code of the failure was not compile-able. OTP id: OTP-3365
- Mnemosyne generated doubled code for record handling, this has been removed.
1.3.3 Mnemosyne 1.2.3
Improvements and new features
None.
Fixed Bugs and malfunctions
- A proper EXIT message is generated if mnemosyne is not started, when evaluating a query.
OTP id: OTP-3197
1.3.4 Mnemosyne 1.2.2
Improvements and new features
None.
Fixed Bugs and malfunctions
- Fixes in documentation.
- Mnemosyne could crash if elements were deleted when mnemosyne scanned a table
OTP id: OTP-3275
Aux Id: Seq 3945
1.3.5 Mnemosyne 1.2.1
Improvements and new features
None.
Fixed Bugs and malfunctions
Mnemosyne have been modified to handle the new exit codes introduced in OTP-R5C.
1.3.6 Mnemosyne 1.1
Some internal things have changed (see below) as well as some new functionality. This means that the queries have to be recompiled.
Improvements and new features
- A new two-argument table generator. Starting from Mnesia 3.4, table names and the associated record type need not to be the same, i.e., there can be multiple tables with the same record type. In Mnemosyne this is specified as a table generator with arity 2. For example, the following uses data from table $a$ with record type $b$.
\[
X \leftarrow \text{table}(a,b)
\]
The old \texttt{table(Name)} still exists and defaults to \texttt{table(Name,Name)}
- Rules that have a return type other than the name of the rule (default), can be declared by using a two-argument rule declaration. The previous way of declaring this (using a special \texttt{argtype} declaration) still works but the new way is preferred.
Fixed Bugs and malfunctions
- It is now possible to use nested records inside Mnemosyne in the same way as in Erlang in general, for example the following is ok inside a query: \((X\#a.\#b.\#c.\#d).\) The inner \#a is not needed if the type of $X$ is known.
- When generating new records in a query the default arguments of the record are properly used, including eventual function calls etc.
Incompatibilities
Some incorrect queries are detected in Erlang compile time rather than during setup / execution in runtime.
The negation operator, \texttt{not}, that was present in earlier versions has been removed. The main reason is that the semantics is unclear in many cases, and almost all questions have no need for a negation. The typical use of negation was something like the following code fragment:
\[
\text{query } [X \mid \]
\[
X \leftarrow \text{table (employee),}
\text{not } X \leftarrow \text{rule (chiefs)} \]
\]
Here, the query variable, $X$, is first bound and then a negation is applied. Usages such as these can often be rewritten by first evaluating the negation in a separate query and then the rest of the query. Assuming the query is evaluated using \texttt{eval} the above could be written:
\[
\text{NegQ = query } [X \mid X \leftarrow \text{rule (chiefs)} \]
\[
\text{NegAns = mnemosyne:eval (NegQ),}
Q = \text{query } [X \mid X \leftarrow \text{table (tab),}
\text{not lists:member (X, NegAns)}],
\text{Ans = mnemosyne:eval (Q)}
\]
Note that the \texttt{not} used above is Erlang's own \texttt{not}, not the (old) Mnemosyne \texttt{not}.
Also note that the above code is not less efficient than the previous versions (that used \texttt{not}) since the whole negation has to be evaluated.
Known bugs and problems
No new ones. See earlier release notes.
1.3.7 Mnemosyne 1.0.1
This release is a minor release and the release notes describes the difference between version 1.0.1 and version 1.0 of Mnemosyne.
Improvements and new features
- The documentation has been enhanced.
Fixed Bugs and malfunctions
No serious ones.
Incompatibilities
None.
Known bugs and problems
No new ones. See earlier release notes.
1.3.8 Mnemosyne 1.0
This is the first release of Mnemosyne as an own application, separate from the Mnesia DBMS Engine. The Mnemosyne application must be used in conjunction with Mnesia 3.0 or later.
Improvements and new features
N.A.
Fixed Bugs and malfunctions
N.A.
Chapter 1: Mnemosyne User's Guide
Incompatibilities
Mnemosyne has been separated from the Mnesia application and this has some minor implications:
- The compiler directive:
\[-include_lib("mnesia/include/mnemosyne.hrl")\].
that was mandatory in all Erlang modules containing embedded Mnemosyne queries has been replaced with:
\[-include_lib("mnemosyne/include/mnemosyne.hrl")\].
During the interim period, both compiler directives will be supported. However, in a future release the backward compatibility directive will be removed from Mnesia.
- The Mnesyne application must be started before any query evaluation may be performed. Earlier, when Mnemosyne was a part of the Mnesia application, Mnemosyne was automatically started as an embedded part of Mnesia, this is not the case anymore. Now Mnemosyne must be started with `application:start(mnemosyne)`, when Mnesia is started.
However, a temporary configuration parameter `embedded_mnemosyne` has been added to Mnesia in order to make it possible to access the automatic start of Mnemosyne. By default `embedded_mnemosyne` is set to `false`, but if it is set to `true` Mnesia will start Mnemosyne as a supervised part of the Mnesia application as it did in previous releases.
Known bugs and problems
- The evaluation of Mnemosyne queries has undefined behavior if they are used in conjunction with nested transactions.
- The evaluation of Mnemosyne queries has an undefined behavior if the involved tables are updated after the cursor has been initiated.
- Mnemosyne queries should not be used on disc-only tables since the optimizer can't handle such tables.
Mnemosyne Reference Manual
Short Summaries
- Erlang Module **Mnemosyne** [page 20] - The query language support for the DBMS Mnesia
**Mnemosyne**
The following functions are exported:
- `all_answers(Cursor) -> Answer`
[page 22] Return all answers from Cursor in a list
- `cursor(Handle) -> Cursor`
[page 22] Create a cursor in preparation for fetching answers
- `cursor(Handle,Nprefetch) -> Cursor`
[page 22] Create a cursor in preparation for fetching answers
- `delete_cursor(Cursor)`
[page 22] Stop the query associated with Cursor
- `delete_query(QuerySetup)`
[page 22] Delete a query setup.
- `eval(Handle) -> Answers`
[page 22] Get all answers from the Handle
- `init_query(QuerySetup) -> Cursor`
[page 22] Quick query initialization
- `init_query(QuerySetup,Nprefetch) -> Cursor`
[page 22] Quick query initialization
- `next_answers(Cursor) -> Answers`
[page 22] Fetch the next answers
- `next_answers(Cursor,Nmin,Nmax) -> Answers`
[page 22] Fetch the next answers
- `reoptimize(Handle) -> Handle`
[page 22] Optimize a query
- `setup_query(Handle) -> QuerySetup`
[page 23] Create a query setup
- `version() -> String`
[page 23] Mnemosyne module version
Queries are used for accessing the data in a Database Management System. The query specifies a relation (possibly complicated) to all of the selected data. This could involve several tables as well as conditions such as ‘<’ (less than), function calls and similar.
Mnesia has two query interfaces which are used together:
- Mnesia, which is this module
- query list comprehensions, an Erlang language construct for the queries
The exact syntax of query list comprehensions are described in a separate section [page 23] of this document.
The query list comprehensions only define the query and the syntax of the solutions to be returned. The actual evaluation is determined by calling different functions with a handle obtained by the list comprehension. For example:
```erlang
-record(person, {name, age}).
Handle = query
[ P.name || P <- table(person) ]
end,
L = mnesia:transaction(
fun() ->
mnemosyne:eval(Handle)
end)
```
The example above matches a list of all names in the table “person” with the variable L. Note the following points:
- Each database table must have a corresponding record declaration.
- A query is declared with
```erlang
query [ <pattern> || <body> ] end
```
where `<pattern>` is an Erlang term without function calls. The notation `P.name` means that `P` is a variable and it has an associated record with a field `name` which we use. The `<body>` is a sequence of conditions separated by commas. In the example, we have `P <- table(person)` which means: “`P` is taken from the table person”.
The whole query could therefore be read as follows: “Make the list of all names of `P` such that `P` is taken from the table person”.
However, the query list comprehension does not return the answers but a handle. This handle is used as an argument for different evaluation functions which do the actual query processing. In the example we used the simplest, `eval/1`, which evaluates the query and returns all the answers.
Some parts of the query must be evaluated in a Mnesia transaction or by utilizing an alternative Mnesia access context. These functions are marked in the function descriptions below.
After obtaining a handle from a query list comprehension, the query can be evaluated in three different ways:
- **A simple all-answer query** as in the example shown above. This function is `eval/1`.
- **Getting the answers in small or large chunks.** The query may be aborted when enough solutions have been obtained. These are called cursors. The functions are `cursor/1`, `cursor/2`, `next_answers/1`, `next_answers/3`, `all_answers/1`, `all_answers/3`, and `delete_cursor/1`.
- **An even more sophisticated cursor version** where the time consuming part of the cursor creation can be done in advance. The functions are `setup_query/1`, `init_query/1`, `init_query/2`, `next_answers/1`, `next_answers/3`, `all_answers/1`, `all_answers/3`, and `delete_query/1`.
Let us reconsider the previous example, this time with cursors. In the following example, we will get just five names without evaluating all of the answers:
```erl
-record(person, {name, age}).
Handle = query
[ P.name || P <- table(person) ]
end,
L = mnesia:transaction(
fun() ->
Cursor = mnemosyne:cursor(Handle),
As = mnemosyne:next_answers(Cursor, 5, 5),
mnemosyne:delete_cursor(Cursor),
As
end)
```
The third way of evaluating a query is by a further division of the query process. The `cursor/1` function is now split into two. The reason for this is that we can set up the query when there is plenty of time and initialize it when answers are needed quickly. As in the previous example, we will get just five names:
```erl
-record(person, {name, age}).
Handle = query
[ P.name || P <- table(person) ]
end,
QuerySetup = mnemosyne:setup_query(Handle),
L = mnesia:transaction(
fun() ->
Cursor = mnemosyne:init_query(QuerySetup),
mnemosyne:next_answers(Cursor, 5, 5)
end),
% Here we may call more init_query-next_answers constructions
% with the same Handle
mnemosyne:delete_query(QuerySetup)
```
Exports
all_answers(Cursor) -> Answer
Returns all remaining answers from the query identified by Cursor. It can be applied after next_answers to obtain all answers that are left.
Note: This must be evaluated inside a transaction.
cursor(Handle) -> Cursor
cursor(Handle,Nprefetch) -> Cursor
Sets up a query for evaluation and starts an answer pre-fetch. Nprefetch gives the number of answers to pre-fetch and must be greater than 0. The default value is 1. A pre-fetch is the first part of a query evaluation. It is placed in a separate process which may on some occasions speed up the subsequent collection of answers.
Note: This must be evaluated inside a transaction.
delete_cursor(Cursor)
Deletes the Cursor and associated query evaluation.
Note: This must be evaluated inside a transaction.
delete_query(QuerySetup)
Deletes a query setup.
eval(Handle) -> Answers
Starts a query evaluation according to the Handle and collects all answers in one operation.
Note: This must be evaluated inside a transaction.
init_query(QuerySetup) -> Cursor
init_query(QuerySetup,Nprefetch) -> Cursor
Performs the last short step in starting a query from QuerySetup. Nprefetch defines the number of answers to pre-fetch as in cursor/2. The default value is 1.
Note: This must be evaluated inside a transaction.
next_answers(Cursor) -> Answers
next_answers(Cursor,Nmin,Nmax) -> Answers
Fetches the next answers from the query evaluation identified by Cursor. At least Nmin and at most Nmax answers are collected. If less than Nmin answers are returned; for example, 0, there are no more answers. If enough answers are not available, but more are expected, the functions wait for them.
Note: This must be evaluated inside a transaction.
reoptimize(Handle) -> Handle
Re-optimizes a query. Queries are always optimized, but the optimization takes into account the dynamic table statistics like size, attribute distribution etc. If a table has changed after obtaining the Handle from a query list comprehension, the query execution plan will no longer be appropriate (although semantically correct). This function will rearrange the execution plan according to the current statistics from the database.
setup_query(Handle) -> QuerySetup
Creates a query setup, that is, performs most of a query evaluation without actually initiating the actual evaluation.
version() -> String
Returns the current module version.
List Comprehension
There must be a directive in the Erlang file telling the compiler how to treat queries. This directive is:
-include_lib("mnemosyne/include/mnemosyne.hrl").
A list comprehension consists of:
query [ <pattern> || <body> ] end
The <pattern> is a description of the terms that are returned by a query. Details of how to obtain the actual values in the <pattern> is given by the <body>.
The <pattern> is an Erlang term without function calls. It typically has one or more variables from the <body> which are instantiated for each answer produced. Every element in the returned list is composed by instantiating this <pattern> and then adding it to the answers.
The <body> takes a sequence of goals separated by ",". The possible goals are:
- <logical-variable> <- table( <table-name> [ , <table-type> ] )
- <logical-variable> <- rule( <rule-name> )
- <logical-variable> <- rule( <module> : <rule-name> )
- <logical-variable> <- erlang-list-expression
- <expression> <relop> <expression>
- <erlang-test-expression>
A <logical-variable> is written exactly as an Erlang variable. The <table-name>, <table-type>, <rule-name> and <module> are atoms. The <table-name> and <table-type> may be an Erlang variable which must be bound at runtime. The logical variables are local to a list comprehension and shadows any Erlang variables with the same name.
An <expression> is any Erlang expression which may include function calls and <logical-variable>. The variants <erlang-list-expression> is an <expression> which must produce lists where all elements are records of the same type. The <logical-variable> must have the same associated record. The
<erlang-test-expression> is an <expression> which only has the values true or false.
Erlang variables are allowed in all variants of <expression> and in <pattern>. They must always be bound in the query list comprehension.
Logical variables is local to a query list comprehension and have an associated Erlang record. The associated record can in most cases be inferred by the query compiler. Therefore, the normal notation for the field \( f_1 \) in variable \( x \) is just \( x.f_1 \). The query compiler notifies when it cannot deduce the corresponding record. The explicit form is \( X#r.f_1 \) as in ordinary Erlang. If the type of the record is not deducable at Erlang compile time, it is more efficient to use the explicit form as a help to the compiler. A variable receiving values from a table will have the record with the same name as the table.
Erlang variables are allowed in <expression> and in some places as described above. They must always be bound in the query list comprehension.
Errors in the description are reported as exceptions in the Erlang standard format as follows:
\[
{\text{error, \{Line, Module, Msg\}}}
\]
The descriptive English text is returned by calling
\[
\text{Module:format_error(Msg)}
\]
**Note:**
A function used in a query list comprehension must never directly or indirectly:
1. have side effects
2. access the database either by a query or by Mnesia functions
3. spawn processes
4. send or receive messages
**Rules (Views)**
A rule (or view) is a declaration of how to combine data from sources as a kind of "subroutine". Assume that we have the following query list comprehension:
```erlang
query
[ Employee || Employee <- table(employee),
Employee.department = sales ]
end
```
This retrieves a list of all sales employees. This could be formulated in the following rule:
```erlang
sales(E, employee) :-
E <- table(employee),
E.salary = sales.
```
The employee declaration in the head of the rule forces the rule argument to associate the employee record. If we omit the declaration, then the associated record would be the rule name, in this case sales. Note that the syntax used in previous versions of Mnemosyne by using an separate argtype declaration still works, but the above method is preferred.
The sales rule may now be used in a query list comprehension:
```
query
[ SalesPerson || SalesPerson <- rule(sales) ]
end
```
The SalesPerson is an employee record because of the declaration of the rule above. Another example lists the names of all female sales people:
```
query
[ SalesPerson.name || SalesPerson <- rule(sales),
SalesPerson.sex = female ]
end
```
The rule must have one argument when used. Although the declaration of a rule looks similar to an ordinary function, no function of that name is constructed. Hence the name of the rule can be used for another function. All rules are automatically exported so they could be referred in other modules by the usual notation module:name. After the :-, there is the usual <body> as in the query list comprehension.
### Generated Functions
When compiling queries some extra (hidden) functions are automatically generated and exported. Thus, there cannot be other functions with the same name and arity within the module. Three such generated functions exist. They are:
- `MNEMOSYNE QUERY/2`
- `MNEMOSYNE RECFUNDEF/1`
- `MNEMOSYNE RULE/1`
List of Tables
1.1 Natural Language Translation ................................................. 3
Index of Modules and Functions
Modules are typed in this way. Functions are typed in this way.
all_answers/1
mnemosyne, 22
next_answers/3
mnemosyne, 22
cursor/1
mnemosyne, 22
reoptimize/1
mnemosyne, 22
cursor/2
mnemosyne, 22
setup_query/1
mnemosyne, 23
delete_cursor/1
mnemosyne, 22
version/0
mnemosyne, 23
delete_query/1
mnemosyne, 22
next_answers/3
mnemosyne, 22
eval/1
mnemosyne, 22
next_answers/1
mnemosyne, 22
init_query/1
mnemosyne, 22
next_answers/2
mnemosyne, 22
init_query/2
mnemosyne, 22
mnemosyne
all_answers/1, 22
cursor/1, 22
cursor/2, 22
delete_cursor/1, 22
delete_query/1, 22
eval/1, 22
init_query/1, 22
init_query/2, 22
next_answers/1, 22
next_answers/3, 22
reoptimize/1, 22
setup_query/1, 23
version/0, 23
next_answers/1
mnemosyne, 22
|
{"Source-Url": "http://erlang.org/documentation/doc-5.3/pdf/mnemosyne-1.2.5.pdf", "len_cl100k_base": 11329, "olmocr-version": "0.1.53", "pdf-total-pages": 34, "total-fallback-pages": 0, "total-input-tokens": 65471, "total-output-tokens": 13319, "length": "2e13", "weborganizer": {"__label__adult": 0.00023317337036132812, "__label__art_design": 0.00015223026275634766, "__label__crime_law": 0.00016891956329345703, "__label__education_jobs": 0.0004982948303222656, "__label__entertainment": 6.842613220214844e-05, "__label__fashion_beauty": 7.921457290649414e-05, "__label__finance_business": 0.0003993511199951172, "__label__food_dining": 0.0001983642578125, "__label__games": 0.0006160736083984375, "__label__hardware": 0.0007333755493164062, "__label__health": 0.00011545419692993164, "__label__history": 0.0001322031021118164, "__label__home_hobbies": 4.5180320739746094e-05, "__label__industrial": 0.0002923011779785156, "__label__literature": 0.0001652240753173828, "__label__politics": 0.0001289844512939453, "__label__religion": 0.00022470951080322263, "__label__science_tech": 0.007720947265625, "__label__social_life": 4.506111145019531e-05, "__label__software": 0.0242156982421875, "__label__software_dev": 0.96337890625, "__label__sports_fitness": 0.00014126300811767578, "__label__transportation": 0.00023758411407470703, "__label__travel": 0.00010156631469726562}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46287, 0.02542]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46287, 0.68749]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46287, 0.84842]], "google_gemma-3-12b-it_contains_pii": [[0, 35, false], [35, 116, null], [116, 116, null], [116, 116, null], [116, 1480, null], [1480, 4250, null], [4250, 6473, null], [6473, 8444, null], [8444, 11785, null], [11785, 13438, null], [13438, 15250, null], [15250, 17206, null], [17206, 18454, null], [18454, 19333, null], [19333, 21685, null], [21685, 23879, null], [23879, 25624, null], [25624, 27026, null], [27026, 27787, null], [27787, 30336, null], [30336, 30968, null], [30968, 32609, null], [32609, 33800, null], [33800, 35774, null], [35774, 37898, null], [37898, 39669, null], [39669, 41981, null], [41981, 43908, null], [43908, 45385, null], [45385, 45385, null], [45385, 45486, null], [45486, 45486, null], [45486, 46287, null], [46287, 46287, null]], "google_gemma-3-12b-it_is_public_document": [[0, 35, true], [35, 116, null], [116, 116, null], [116, 116, null], [116, 1480, null], [1480, 4250, null], [4250, 6473, null], [6473, 8444, null], [8444, 11785, null], [11785, 13438, null], [13438, 15250, null], [15250, 17206, null], [17206, 18454, null], [18454, 19333, null], [19333, 21685, null], [21685, 23879, null], [23879, 25624, null], [25624, 27026, null], [27026, 27787, null], [27787, 30336, null], [30336, 30968, null], [30968, 32609, null], [32609, 33800, null], [33800, 35774, null], [35774, 37898, null], [37898, 39669, null], [39669, 41981, null], [41981, 43908, null], [43908, 45385, null], [45385, 45385, null], [45385, 45486, null], [45486, 45486, null], [45486, 46287, null], [46287, 46287, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46287, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46287, null]], "pdf_page_numbers": [[0, 35, 1], [35, 116, 2], [116, 116, 3], [116, 116, 4], [116, 1480, 5], [1480, 4250, 6], [4250, 6473, 7], [6473, 8444, 8], [8444, 11785, 9], [11785, 13438, 10], [13438, 15250, 11], [15250, 17206, 12], [17206, 18454, 13], [18454, 19333, 14], [19333, 21685, 15], [21685, 23879, 16], [23879, 25624, 17], [25624, 27026, 18], [27026, 27787, 19], [27787, 30336, 20], [30336, 30968, 21], [30968, 32609, 22], [32609, 33800, 23], [33800, 35774, 24], [35774, 37898, 25], [37898, 39669, 26], [39669, 41981, 27], [41981, 43908, 28], [43908, 45385, 29], [45385, 45385, 30], [45385, 45486, 31], [45486, 45486, 32], [45486, 46287, 33], [46287, 46287, 34]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46287, 0.00674]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
12c1301f5583f1cc89b748214bbc9bb1f37d4ce6
|
Engineering Management
Field Project
Enterprise Feedback Survey Tool
By
Akram Dalaq
Sprint Semester 2008
An EMGT Field Project report submitted to the Engineering Management Program and the Faculty of the Graduate School of The University of Kansas in partial fulfillment of the requirements for the degree of Master of Science.
_____________________________
Linda Miller
Committee Chairperson
_____________________________
Herbert Tuttle
Committee Member
_____________________________
Tim Wilcoxon
Committee Member
Date Accepted:
Acknowledgments
I would like to thank my family, my wife Shawna and both my boys Ubaydah and Siraj for their patience and support throughout the time I spent attending the EMGT program.
Also, many thanks to project committee chair Linda Miller for your support throughout this program. Your help and guidance in assisting with this project and all classes since I started is truly and greatly appreciated. I would like to thank committee member Tim Wilcoxon and Herb Tuttle for their feedback and accepting to be on my field project committee.
I would like to thank my company for first supporting me to accomplish my goals towards completing my Masters Degree in Engineering Management.
Executive Summary
Many corporations in the United States are continuously expanding and improving their ability to gather customer feedback and incorporate the feedback into their business processes.
It’s fairly easy to obtain reliable feedback within small, specialized teams with clearly defined roles and objectives. It becomes more difficult in larger IT organizations or those with complex relationships to gain such essential information needed to continue improving and prosper. That brings the need for IT organizations to explore comprehensive feedback solutions to provide accurate results.
Information Technology (IT) Feedback project lifecycle must consist of how to designing the Feedback Survey web tool, assign data collection responsibilities to groups that are in the best position to collect the information, specify reporting mechanisms and templates, and define policies such as system access.
This paper will explore issues in effective feedback system, discuss the enormous benefits of having the right feedback solution in place, and illustrates how the Feedback Survey system enables the implementation of a comprehensive Enterprise Feedback Survey program for IT organizations, utilizing the Internet as a way of delivery.
To determine the response of certain specialists within IT organization, it was decided to conduct a pilot survey to selective Network Operations team members. This is just a pilot survey that had not been conducted prior to the creation of the Feedback Survey system in the paper. Details of this pilot survey are discussed in this paper.
# Table of Content
Acknowledgments........................................................................................................... 2
Executive Summary........................................................................................................ 3
Table of Exhibits............................................................................................................. 5
Chapter One - Introduction ................................................................................................. 6
Chapter Two - Literature Review ....................................................................................... 8
What is Feedback System? ......................................................................................... 8
Importance and Features of Feedback ........................................................................ 8
Effect of feedback on people and performance .......................................................... 9
Effect of feedback on learning and performance ...................................................... 10
Effect of feedback on Top and Low performers....................................................... 10
Self-consistency and Self-affirmation theories......................................................... 12
Getting Feedback from knowledgeable Source ........................................................ 13
Impact of Feedback on public image........................................................................ 13
Ways people react upon receiving feedback............................................................. 14
Chapter 3 – Development of the Tool............................................................................... 17
Feedback Survey System for IT Organizations ........................................................ 17
Determine Information Needs................................................................................... 17
Development Process (DP)....................................................................................... 18
Figure 1 ......................................................................................................................... 20
Response Analysis and Reporting ........................................................................... 20
Design the Feedback tool Structure ........................................................................ 21
Determine the Issue................................................................................................... 22
Structure Design........................................................................................................ 22
Determine Target Customers.................................................................................... 22
Instrument Design and Testing ................................................................................. 22
Implementation Tasks............................................................................................... 23
Reporting Results...................................................................................................... 23
Functional Considerations ............................................................................................ 24
Feedback Methods .................................................................................................... 24
Effective Communications Management.................................................................. 24
Development Support ............................................................................................... 25
Business Process Integration..................................................................................... 25
Technology Considerations .......................................................................................... 26
Ease of Deployment and Maintenance .................................................................... 26
Centralized System Administration ........................................................................ 26
Self-installed or Hosted Solution.............................................................................. 26
Chapter Four - Conducting Actual Survey ....................................................................... 28
Survey Method.......................................................................................................... 29
Survey Results .......................................................................................................... 30
Chapter Five - Conclusion ................................................................................................ 32
Recommendation for additional work ...................................................................... 32
References:.................................................................................................................... 34
Appendix A – HTML code gathering survey result ..................................................... 39
Appendix B – HTML Reporting code ............................................................................ 42
Appendix C – HTML Easy-Administrating code......................................................... 44
Appendix D - Meeting Minutes .................................................................................... 47
Meeting Minutes (1) ................................................................................................ 47
Meeting Minutes (2) ................................................................................................ 48
Appendix E – D9858 Sample Survey ........................................................................... 50
Appendix F – D9858 Survey Result ............................................................................. 52
Table of Exhibits
Figure 1: Development Life Cycle .............................................................................. 20
Figure 2: Survey Results Graphic ............................................................................... 31
Chapter One - Introduction
Information Technology (IT) organizations are continuously expanding and improving their ability to gather customer’s feedback and integrate the feedback into their business processes. These processes must be continuously monitored and optimized to suit changing business conditions. The evaluation of many business processes is important and Feedback System is ideally suited for measuring these processes.
An example of a business process is the operation of Information Technology within a company, which is designed to ensure the satisfaction of its main customer Network Operations. IT receives product development requests through normal company project process and acts upon these requests. One way of measuring the performance of the Information Technology is by surveying customers about the quality of the service received. Performance measurement in this case inherently involves feedback management. Feedback System is also important to various other kinds of business processes including Market research, Employee Satisfaction, Performance Reviews and new Product Launch.
The accuracy of such feedback is significantly improved when the Feedback System platform not only facilitates the creation of the right instruments but also provides tools to manage the entire Feedback System lifecycle. IT Web-based forms delivered over the Internet are becoming the preferred means of feedback data collection and are steadily replacing traditional mechanisms such as word of mouth, paper or phone call surveys.
One of the most important new capabilities of the Internet relative to previous mass communication technologies is its multi direction communications. Through the Internet, not only can organizations communicate to the audiences at a low cost, but also for the first time in human history, individuals can make their personal thoughts, reactions and opinion easily accessible to many members of the community within the organization. Perhaps the best-known application of online feedback mechanisms to date has been their use as a technology for building trust in electronic markets (Kollock 1999). The relationship between the company and the customer tends to improve because the company is willing to listen to customers’ issues, concerns and they are willing to take action and improve their processes and the way they do business. This behavior tends to help both parities by improving customer retention, recognizing problems, allocating resources and depending on the situation, coach or reward employees.
Throughout this section, the focus of the literature review revolves around many aspects of feedback: emphasis on the constructive aspect of feedback, customer-focused features as part of any comprehensive feedback system, effect of feedback on individual performance. Other aspects discussed by many authors such as impact of feedback on individual’s learning and performance, relationship between self-esteem and negative feedback and finally how people respond upon receiving a feedback.
Chapter Two - Literature Review
What is Feedback System?
A feedback can be obtained through survey research tool such as web-based data collection forms which collects, analyzes, and reports about business processes. A feedback collection project is itself a process and the different phases of its lifecycle are Design, Implementation, Data Collection, and Analysis and Reporting. Enterprise Feedback System is the core of managing multiple Feedback Collection Projects covering all relevant business processes within group or an organization.
The benefits of Enterprise Feedback System include competitive advantage due to improved market intelligence capabilities, utilization of best practices for performance measurement among all the business operations within the group, more efficient use of resources and ability to obtain a combined view of the performance of all business processes within the group. (Marcus and Curt Coffman 1999).
Importance and Features of Feedback
The literature has exposed a lot of awareness on the making and recording of feedback in the framework of customer service environments in many companies with the focus on the department level.
Overall, receiving complaints and feedback is very important to each organization. It allows each department within the organization to address issues and concerns, and it provides the chance for each organization to consider the quality of services and provide the change to improve learning by providing training as needed to those who need it. According to research, a feedback system is an important tool as it gives individuals the opportunity to raise concerns and voice their highly important comments in regards to
services delivered or not delivered. Feedback systems should focus on the constructive aspect and should not be a defensive response to a situation or a case. Rather it should point to deficiencies to improve the service. The task becomes extremely difficult as some companies tend to perceive feedback as negative vs. constructive feedback. Receiving and handling customer complaint and feedback processes are measured as positive opportunities to promote customer satisfaction and to identify any existing issues in order to provide effective service delivery (Shrauger, 1986).
Feedback systems may include number of customer oriented features that are easily accessible and noticeable to users. It shows how, where, when and to whom complaints can be made. These systems should be simple to operate with resources clearly allocated. Other features should be included such as quickness as it should offer prompt action and speedy resolution. Feedback System should be objective and confidential. It should record complaints at all stages and levels, including actions taken and complainant’s response.
**Effect of feedback on people and performance**
Many experiments have examined the effect of feedback on performance. For example, Emmert (1978) suggested that both morale and performance increased after conducting feedback experimental design. Other studies by Nadler (1980) have determined the impact of feedback system on groups is very effective as long as the over all goal is objective. Becker (1978) also found feedback has positive impact on individuals.
Many articles have been written about feedback and its role in knowledge and how feedback has impact on skill achievement. Most of these studies have conducted
experimental tests examining many features of feedback. Despite the fact that there has been plenty of research on Feedback mechanisms and there impact on people, yet relating feedback to learning is not so clear and with few general conclusions. Most of the research that has been preformed on feedback uses descriptors such as inconsistent, conflicting, and variable to describe the body of feedback findings (Azevedo & Bernard, 1995; Kluger & DeNisi). Many years later the same situation still applies (Baron, 1993).
**Effect of feedback on learning and performance**
Feedback has been widely cited as an important facilitator of learning and performance (Bandura, 1991; Ilgen, Fisher, & Taylor, 1979), but other studies have reported feedback as having either no effect or low effects on learning. As an example “no facilitative effects of feedback on learning” Bangert-Drowns (1991). Some studies demonstrate negative effects of feedback on learning. Other features of feedback have an impact on learning when providing grades and scores demonstrating the student’s standing relative to peers (Butler, 1987). Interrupting a student who is engaged in problem solving with feedback from an external source tend slow down learning (Corno & Snow, 1986). According to this review, feedback could have some negative effects on learning.
**Effect of feedback on Top and Low performers**
With respect to other findings, shows that people will seek feedback as long as there is higher level of uncertainty in terms of performance (Ashford & Cummings, 1983; March & Simon, 1958), Even though it is not easy to find signs of uncertainty in advance. A main factor that influences perceptions of uncertainty is an individual’s performance history. Top performers whom have mastered their job and have great record of good performance
may believe there is no need for any feedback. On the other hand, employees who have low level of performances may perceive greater uncertainty and it would be very helpful for them to know how they did and whether feedback contributing to their improving. Many with poor performance would always welcome less negative feedback and much rather to get positive feedback in order to correct their mistakes and improve their performance. In fact, employees with low performance will work on improving their performance post negative feedback; otherwise, it may result in disciplinary action and may result in termination (Wood & Locke, 1990).
Other views may point to less feedback due to strong performance. A laboratory study found that when participants in the study faced a drop in performance, it decreased the extent to which individuals sought information from others, a type of information equivalent to negative performance feedback (Baron, 1993). This may lead to believe that individuals with success history are less likely to gets feedback if compared with those with low performance past. Most of these individuals may experience a drop in performance every now and then, but they are certain they are able to turn things around within short period.
Pursuing feedback may not necessarily be tied to other aspects of performance and the need for information on certain individuals. Some individuals may measure feedback for its perceived harm–benefit prospect for self. (Ashford & Cummings, 1983). For some seeking to identify their own strength or weakness may misinterpreted this, as they might believe this is one way to prove their lacking ability. If preserving one’s self-image is very important to people, individuals will try to avoid negative feedback, to avoid finding out their poor performance.
Self-consistency and Self-affirmation theories
While there are personal characteristics that are associated with negative feedback avoidance such as anxiety, research stresses self-esteem as a critical variable. Self-esteem refers to one’s appraisal of oneself as worthy and/or efficacious (McClearn, & Knight, 1996).
Some theories have discussed dealing with the relationship between self-esteem and negative feedback orientation. One of these theories is self-consistency theory in which it suggests that people are motivated to maintain certain attitudes about themselves. According to the self-consistency theory; individuals favor feedback that confirms their self-image. Therefore, people seek less negative feedback normally have low opinion of themselves than those who hold themselves in high regard (Shrauger, 1986).
Other theories such as self-affirmation theory discuss how people prefer to see their positive side and avoid any information that brings out their low self-esteem side. Both of these theories suggest that people with high self-esteem prefer positive feedback than negative feedback. However, when it comes to people with low self-esteem, their predictions tend to change. The self-consistency theory suggests that low self-esteem people can be more accepting of negative feedback over positive feedback. Self-affirmation theory maintains that low self-esteem people avoid negative feedback when compared to high self-esteem people. This confirms the self-affirmation theory, indicating that while a self-enhancement theory bias makes people generally more inclined to obtain positive feedback, low self-esteem people also try to avoid negative feedback (Blaine & Crocker, 1993; Spencer, Josephs, & Steele, 1993).
Seeking negative feedback might be interpreted negatively. Other cases Feedback can be interpreted positively. It may be seen as lack of skills or as a sign of motivation to
improve. People that regard their image to be very important to them may limit whom to seek negative feedback from. (Morrison & Bies, 1991). This may result in less people seeking feedback.
**Getting Feedback from knowledgeable Source**
On normal situations, people are more likely to seek feedback from individuals they trust as far as their ability to provide fair feedback as long as they are being knowledgeable of matter and trustworthy. One would really want to avoid feedback from a person who is unfair or is motivated by considerations other than the truth. It really makes no sense to get feedback from individuals who do not know how to evaluate performance correctly and to give useful feedback (Wood & Locke, 1990).
**Impact of Feedback on public image**
Many individuals perceive public image as important aspect and it is very important to them whom to request feedback from. Public image concerns will motivate individuals to seek feedback from individuals with whom they are in good terms with as they tend to more likely to interpret the feedback seeking act favorably. Concerns about public image may also result people to consider other sources before asking for feedback especially those whom are concerned about maintaining a good image. If they believe that feedback request will damage their public image, they will be more likely to ask from someone with less reward power (Morrison & Bies, 1991).
These type of concerns maybe a factor to influence the degree to which those individuals seeking feedback appear to other people. One factor is self monitoring tool, which refers to the level to which individuals are concerned about the public image of their behavior (Snyder, 1975). As a result people may refrain from seeking feedback
despite its prospect of correcting their behavior, particularly from people whom they
don’t have strong relationship.
**Ways people react upon receiving feedback**
There are three different ways people react upon receiving feedback. **Accepting the**
message and making an effort to change within and improve self and or processes. One
other way is by **ignoring the message** while insisting on the current way of doing
business and refusing to make any changes. Or the third final way by **requesting**
additional feedback while continuing on the current way of doing business (cf. Kluger
& DeNisi, 1996).
Let’s discuss on how people react once receive the first type of feedback. How can we
find out whether individuals accepting a feedback message react to it and make changes
or just ignore it? **Goal theory** may have some answers to our question (Locke & Latham,
1990). According to the support of extensive observed work, goal theory suggests that
when people learn of inconsistency between their goals and performance such as negative
feedback and when they are certain of their ability to be successful is low, they are more
likely to lower their obligation to their duty or the goal. Once people consider their role
or task less important to justify their effort, they tend to abandon their task as they feel
abandoning their task will change their role. If self-esteem and self-efficiency are both
low, people tend to behave in defensive mode by the abandoning their task in order to
avoid any feedback. Changing the goal would be another way of abandoning their task.
That is not considered defensive rather change of interest or priorities (Azevedo &
Bernard 1995).
Once people accept the feedback and decide to change the way of doing things, how are they likely to change? Some people choose the working harder approach by spending more time and effort on the task; other people choose the working smarter approach (Wood & Locke, 1990). The content of feedback is how people choose to go one way or another. People are more likely to work smarter than work harder when the feedback provides specific details as to what strategies need to be changed (Kluger & DeNisi, 1996). If that information was not provided, people are more likely work harder by putting more effort in the task.
Rejecting feedback leads to continue with the current way of doing business without the motive to improve. There are two types of rejections. Rejection may be product a narrow focus such as the expertise and the credibility of the source. When the source is neither credible nor liked, individuals may automatically ignore the message. On the other hand, rejection may be the result of an objective analysis of the content of the message leading to the conclusion that the message is untrue. In the process of rejecting the message and persisting with the current course of action, people may also engage attempts to blame others (Taylor, 1988). In other cases, disagreeing with the source in which may not necessarily be defensive in the case of incorrect feedback provided by the source. This is the case often when the source lacks sufficient knowledge of the situation.
The another way people react upon receiving feedback are those whom are uncertain about the validity of feedback. In this case, they neither accept nor reject it. They normally seek additional information and end up delaying reaching the conclusion. To better understand how the performance data were gathered and what standards were applied to arrive at that feedback, they tend to gather additional information from the
same source. In some cases they are unclear as to whether the feedback source is providing solid feedback or whether he can be trusted to give an honest evaluation. In these cases, obtaining feedback from other sources may be critical (Locke, 1990).
Now that we know the different ways in which people respond to feedback, it would be helpful to identify the most appropriate response. If one were to assume that the feedback message is complete and valid, then it would be wise to accept the message and make changes according to their suggestions. However, this assumption is often not made. It is vital for feedback recipients to check the legitimacy of the feedback message. It is mostly vital how recipients handle situations in which the feedback message creates doubts and confusion. Do they reach a conclusion based on questionable data?
Sometimes additional feedback reaches from one or many sources. Some mismatches occur when people accept the message and act on it when the message is incorrect. Others occur when people dismiss the message and persist on the current course of action when the critical message is valid. When the facts are vague because the feedback message point to new leads but does not offer decisive proof, it is suggested that the best response is to neither dismiss nor accept the message.
Chapter 3 – Development of the Tool
Feedback Survey System for IT Organizations
A Feedback Survey System manages multiple Feedback Collection projects. The program must have well defined long-term goals. The goal of a Feedback Survey program is to monitor the IT organization’s relationships with their customers. This monitoring in turn will help in analyzing the data and understanding the organization’s relation with the customer. The IT organization may need to know about the customers’ purchasing patterns and the categories of services does customer prefers. Defining real goals will help the organization in designing a flexible Feedback Survey System that is an essential part of overall business processes, and will contribute considerably to the organization’s success.
Determine Information Needs
Information Technology (IT) organizations perform many tasks. Task performance may be distributed among multiple departments and people. Each broad business process must have its own distinct information needs. The first step to setting up an effective strategy for Feedback Survey is to understand the structure of information needed to complete a feedback. Information collection and management is a time consuming process, and therefore it is best to collect it in a well-organized manner. If multiple departments need the same information, the information must be gathered only once and spread appropriately. Once the structure of informational needs is determined, the logistics of information collection must be understood. Parameters must be defined such the frequency data must be collected and where to be collected from.
In order to identify and verify the root causes of problems and utilize the Feedback Survey tool properly, we must first understand and study the project life cycle phases within the Development Process (DP) used by many IT organizations.
**Development Process (DP)**
The following project life cycle is used by XYZ corporations and these phases are from the XYZ internal Website.
Development Process consists of the following phases.
**Define** encompasses processes that define the strategic intent and concepts that are aligned with the considered goal and it consists of four steps.
- **Intent** facilitates definition of strategic plans needed to guide the enterprise.
- **Ideation** facilitates definition of concepts and aligned with the strategic intent and Domain and Portfolio Evolution Plans.
- **Feasibility** facilitates determination of approach, critical functional impacts, and overall feasibility of concepts.
- **Estimation** facilitates estimation of level of effort (LOE) for prioritization and investment decisions.
**Discover** refers to the processes that discover functional and system requirements in support of the business requirements.
Discover phase encompasses three steps.
- **Project Planning** Includes tailoring of the process, creation of the project schedule, resource assignment, and creation of the IT Project Management Plan.
- **FRM** facilitates identification of functional requirements, supporting business requirements.
• **SRM (Conditional)** facilitates identification of system requirements, supporting functional requirements. This step is **Conditional** if the project has single application impact, or multiple application impact with no code impacted interfaces between them.
**Design** refers to the processes that constitute definition of physical design specifications, which will serve as the basis for development efforts.
Design phase encompasses two steps
- **Design Specification** facilitates creation of inter and intra application physical design specification and the physical information (database) design.
- **Contract** provides an integrated view of the project encompassing scope, cost and schedule for investment decisions.
**Develop** refers to the processes that develop and test application systems (software) according to the specifications detailed in the Design phase. **Refer to Figure 1**
Develop phase encompasses two steps:
- **Application Code and Testing** refers to creation and testing of software (application) according to design specifications
- **Service Build & Test** is the sub-process that manages the effective use of new and changed services throughout the organization by planning, designing, building and testing the hardware and software components prior to release to the live environment
Deploy refers to processes for planning and implementing the activities required to deploy projects from the development to production environment.
Deploy phase encompasses two steps:
- **Release to Production** is the sub-process that manages the effective use of new and changed services throughout the organization by planning and releasing the hardware and software components to the live environment to ensure the deployment of compatible, licensed and appropriate release and to minimize the use of release that do not contribute to business objectives.
**Production Warranty** refers to maintenance support during an agreed-upon timeframe following production migration.
**Response Analysis and Reporting**
After analyzing the Development Process, the most logical phase for error to occur is the Develop phase. The best approach to validate this prediction is to implement a Feedback Survey system and collect valid data. Upon collecting the response data, a statistical tool is needed to analyze specific feedback project, depending on the level of...
data analysis required. For most reports, the ability to generate various types of summary reports provides the insight into the importance of the results. The integration of such data analysis tools within the Feedback Survey System platform provides rapid data analysis capabilities for all users within the organization. Clifton, Donald, Ph.D., and Tom Rath (2004). In cases where further analysis is required, the ability to export of data into Microsoft packages such as Excel [2].
Generating and distribution reports are two of the most time consuming steps of the feedback process. Multiple reports with different levels of detail may need to be distributed to different audiences. For example, group manager may need access to in depth type of reports while the CEO of the company may only require high-level quarterly data. Creating these types of reports may become difficult if the reporting tool is external to the system. Very important time may be lost in data export and preparation before meaningful reports can be generated. Reporting code is shown in Appendix B.
The Feedback Survey System tool allows the creation of multiple Report Definitions for the same survey. Web-based reports can be specified to be real-time or generated and published according to demand.
**Design the Feedback tool Structure**
An effective Feedback Survey tool must define a well-designed process and workflow for ongoing projects. The process must create a design group and assign data collection responsibilities to groups that are in the best position to collect the information, specify reporting mechanisms and templates, and define policies such as system access.
Once the overall Feedback Program is designed, individual feedback collection campaigns are conducted on an ongoing basis.
The next few sections discuss the major tasks in greater detail and address the features within the Feedback Survey system that make it easy to achieve the tasks.
**Determine the Issue**
For each project, the data collection goals must be clearly defined. This is a repetitive process that identifies what issues to investigate, and what questions to ask, and may involve conducting focus group studies and test surveys. Designing feedback systems is a process that can be improved over time.
**Structure Design**
The online Feedback Survey tool allows for convenient structuring of projects through its data collections capabilities. Once the broad issues are determined, the structure of the project must be designed. The project may require the creation of multiple surveys that could be targeted at different population samples. Addison-Wesley Professional (2005).
**Determine Target Customers**
This task identifies the profile of individuals who will be targeted for obtaining responses from. This is one of the most important steps in the planning stage because it will determine the nature and quality of information that will be gathered. The outcome of this step will also determine the sampling techniques that will be used to create the short list of survey recipients. Internal databases provided with the online Feedback Survey tool makes it easy to select appropriate population segments.
**Instrument Design and Testing**
The feedback form and the question elements within the form must be carefully constructed. Effective feedback forms adhere to good survey design guidelines and must be engaging to encourage users to want to participate. It is a good idea to test the
feedback form at least once with small target audience. Testing allows the enhancement of form design and can make the difference between an effective form and wasted effort.
**Implementation Tasks**
Once the survey tool design is complete, population samples must be finalized. The feedback form is then published to a location that is accessible to the target population for the appropriate duration. Communications must be used to alert the target population about the status of the survey. Such communications can include availability notifications, reminder messages and thank you notes. By the time target recipients receive communications about form availability, the feedback form must be made available to collect data. Similarly, once the necessary data is collected, the form must be closed [1].
**Reporting Results**
Feedback Survey reporting system offers data analysis tools including statistical historic data for all questions and responses, the ability to compare questions and cross-reference with other reports. Finally, the ability to export of data into Microsoft packages such as Excel. After the required amount of raw data is collected, the data must be organized and analyzed. Shown in Appendix A the HTML code gathering the result for each survey. Standard statistical analysis techniques shed light on various behavioral patterns and help in recommending courses of action that can influence future behavior.
It is very important to take into considerations the type of technology prior to deploying the Feedback Survey System tool within IT Organizations in order to be most effective. Two areas need to be evaluated when choosing a Feedback Survey; these areas are Functional and technological considerations.
Functional Considerations
Feedback Methods
Core feedback methods deal with the important functions of creating and administering survey research instruments, data collection and analysis, and reporting. Core functional capabilities may be categorized into three areas. These presentation functions such as the ability to support different types of questions, controlling questionnaire page layout and customizing the appearance of the web pages. Behavioral functions such as the ability to check for login authorization prior to responding, routing to different question sets based on responses and real-time error checking to improve validity of responses. Response analysis functions such as the ability to generate statistical tables and different types of graphs, combine data across multiple input fields or questions for cross-tabulation and finally the ability to extract raw response data in industry standard formats for export to dedicated data-analysis tools. Hathaway, Patti. (2005).
Effective Communications Management
As soon as the new Feedback Survey System is ready to go, most new survey tools do not need to be newly designed. Most groups will be able to design their surveys with standard questions that can be reused occasionally. Another important function is the ability to create templates and store them as libraries, to allow copying whole or partial questionnaires easily. The reuse of reliable questions further reduces development time and speedup survey processes, if time is spent to test the questions before the templates are created. The relevance of responses is often lost in many feedback survey systems, due to the delay reaching the customer in time. Therefore, it is very important to speedup deployment capabilities to reach the target customer in timely manner [2].
Improved communications with the target population can increase the response rates and therefore help improve the validity of outcome. The same communication method may not be best possible for different types of audiences. In the case of an internal survey, it is commonly acceptable to send out periodic reminders internal employees as an example, but it may not be acceptable to send out more than one reminder to external customers. It is recommended to send out these reminders to external customers who have not completed the survey rather than sending mass reminder all recipients which may make the process less credible. Following the proper process will improve the outcome of the Feedback Survey System process. Larkin, T.J. and Sandar Larkin. (1994).
**Development Support**
Multiple stakeholders are needed to design different aspects of the tool for larger organizations. Focus groups tasked with designing survey instruments rely on teamwork and multiple discussions as far as design to able to arrive at the best possible solution. Thus, a tool must support collaboration among users to be able to support the overall Feedback Survey System [2].
**Business Process Integration**
Feedback Survey System is most effective when it is integrated with other business processes. This means that the Feedback Survey System Platform must work seamlessly with other entities within each organization. In the Internet era, the web delivery model is the preferred means of inter-process communication as it offers the greatest flexibility and ease of implementation. Comprehensive web-base Feedback Survey System should provide a powerful tool that integrates with back-end systems.
Technology Considerations
Ease of Deployment and Maintenance
In order to support an evolving Feedback Survey System, the tools that support the processes must themselves be built to scale and evolve as needed. One main focus of a tool that is used by multiple designers is the simplicity of deployment and maintenance. Using HTML to implement the Feedback Survey System makes maintenance easy.
A system built within the framework of standard technologies greatly facilitates support and ensures integration with other enterprise infrastructure systems. The new tool supports of industry standard protocols like XML, HTTP, and HTTPS makes it easy to integrate backend systems [3].
Centralized System Administration
System Administration in a multi-user environment is best performed in a centralized manner. This does not imply that IT resources or expertise is needed. Instead, centralized administration means that a single point of control must be established for administering policy-based management of system resources and system access. Project managers, who are in the best position to know which team members need access to various levels of data, can be set up as system administrators; they in turn set up and administer access policies. System administrators also load general data such as system level Address Books, and Library Templates that should not be modified by general end-user. Appendix C shows HTML administrating code.
Self-installed or Hosted Solution
Depending on the needs of the organization, either self installed application or a hosted application service may be appropriate. The self installed and administered
version is ideal for large organizations that need to have full control of the hardware, data, and administration functions.
The hosted solution is ideal for cases when the organization does not wish to commit any resources for hardware and software maintenance, and must ideally have the full power of the locally installed system available to it. In either case, if the organization desires to change its options later, it must be able to do so without loss of service continuity and transfer the entire dataset seamlessly [2].
Chapter Four - Conducting Actual Survey
To determine the response of the customer, it was decided to conduct a survey to selective Network Operations team within XYZ organization. This is just a pilot survey that had not been conducted prior to the creation of the Feedback Survey system in the paper. Details of creation, layout and method of the survey will be discussed in the following sections.
The first step in creating this pilot survey is to determine the information needed for the project and where to get that information. In looking through defects for most projects completed by Information Technology, it appears these issues tend to share some common similarities. This conclusion was as result of reviewing XYZ’s internal ticketing system as well as meeting with the Network Operations management discussing project status. Meeting minutes (1) and (2) shown in Appendix D.
The most important questions common to this project are aimed to address the core functions of this project. These main system requirements are as follow:
- The ability to configure the test and production environments with any gateways connected to IDEAS server.
- The ability for the configuration management system to provide full TL1 command support of network element for commands applicable to configuration management.
- The ability for the configuration management system to provide a graphical view of all network elements.
• The ability to select a node to open a secondary window displaying a graphical representation of the shelf
• The ability to assign a circuit ID to cross connect for all transmission levels when creating a circuit utilizing the ENT-CRS command.
• The ability for the configuration management system to remove a managed object from the circuit database when deleting a circuit using the DLT-CRS command.
• The ability for all development for the network switch to be in the NETeXPERT
• The ability for the alarms from the network element to report in fewer then 4 seconds to the user
• The ability for the commands to easily run with a minimum of steps (one to three steps maximum) required to "build" and execute the commands
• The ability for the command response time to be 2 seconds in order from sent to receive back
• The ability for the Shelf/Node View to represent the shelf for that specific equipment in that node
• The ability to support dynamic circuit changes.
Survey Method
The surveys were administered to several members of the Network Operations whom they directly deal with new software releases and part of User Acceptance Testing. The survey link for the project was emailed to these individuals upon project completion by the IT development team. For a more effective result, it is recommended to conduct several projects surveys upon completion, however due to time limitations and the
infrequency of project roll out, this survey serves as small sample of the intended result. D9858 sample survey shown in Appendix E.
**Survey Results**
All surveys were completed with 100% response rate and the survey results were analyzed by few members of the Information Technology organization. Figure 2 indicates graphical presentation of the result. D9858 survey result shown in Appendix F.
Q1. Would you agree that the ability to configure the test and production environments with any gateways connected to IDEAS server fairly successful?
Q2. Would you agree that the new card on the configuration management system to provide full TL1 command support to support all available network elements?
Q3. Does the configuration management system provide a graphical view of all network elements?
Q4. Does the configuration management system easily allow you to remove a managed object from the circuit database when deleting a circuit using the DLT-CRS command?
Q5. Do alarms from the network element report in fewer then 4 seconds to the user?

In general, it was found that most employees were either neutral or dissatisfied with the ability to configure an environment and connect to element system server. With respect to the new card and the ability to provide full command support to all available network elements, the majority were in agreement that requirement is working as designed. Five employees were neutral and very few disagreed. Similar outcome was provided towards the third question in terms providing graphical view of all network elements. Participants were also similarly in agreement in terms the ability to remove a managed object from the circuit database and whether alarms report in less than 4 seconds. A good number were neutral but the majority disagreed and expressed their dissatisfaction.
**Chapter Five - Conclusion**
Organizations rarely suffer from having too little feedback from the people they serve or do business with. However, they often lack an overall system for managing this feedback. As a result, valuable information is isolated in diverse departmental databases or information collection systems. This leads to managers having only a partial view of their customers, which negatively affects both strategic planning efforts and tactical daily decision-making.
In order to fully realize the benefits, convenience and expanding reach of the Internet, IT organizations must ensure that the tools that support their Feedback Survey System program can support and scale to the requirements of the evolving information age. Implementing such a Feedback Survey System will result in reduced feedback collection costs, improve the quality of market intelligence, and enable the corporation to respond quickly to market changes and thus stay competitive.
**Recommendation for additional work**
Feedback Survey System can be very effective tool but is also very important to adapt the human effect for even more subjective and comprehensive system. IT Managers and throughout their normal day-to-day operations have numerous opportunities to identify strengths and weaknesses of processes, systems or staff. While Survey reviews offer formal process, managers and service matter experts can by far make the greatest impact by searching for defects and doing everything in their power to improve process as well as moral. IT Managers should plan to often spend time each day by observing staff and giving feedback that others appreciate. Perhaps some of the most sensitive feedback managers give to other IT staff and development team will be about their communication
among each others in order eliminate duplicate efforts and wasted resources. The combination of Feedback Survey System process as well as IT management and Service Matter Experts dealing with staff and processes will have the greatest effect towards successful and improved IT organization.
References:
Appendix A – HTML code gathering survey result
```html
<html>
<head></head>
<body background="bg_g.gif">
<p align="center">
<%FormName=Request.QueryString("FormName")
FrmID=Request.QueryString("FrmID")%>
<%
'FormName="Project22"
set dbConn = Server.CreateObject("ADODBConnection")
dbConn.Open "DBQ="&server.MapPath("Mgmt.mdb")&";Driver={Microsoft Access Driver (*.mdb)}; dbConn.mode = 3;"
set rsItem1 = server.createobject("adodb.recordset")
rsItem1.open "Select * from [Form_Table] Where ID="&FrmID&" ", dbConn, 1,3
'=================================================================== Select the form
if NOT rsItem1.EOF Then
'do while NOT rsItem1.EOF
FrmID=rsItem1("ID")
FormName=rsItem1("FormName")
'=================================================================== Get the count
set rsItem = server.createobject("adodb.recordset")
rsItem.open "Select * from [SurvayFormUsed] WHERE FrmID="&FrmID&" ", dbConn
if NOT rsItem.EOF Then
Num_Users=rsItem("Num_Users")
End if
rsItem.Close
set rsItem = Nothing
'=================================================================== End Get the count
%>
</p><br><br>
<p align="center"><font color="#FFFF00" face="Tahoma">Results for the </font><b><font color="#00FF00" face="Tahoma"><%=FormName%></font></b><font color="#FFFF00" face="Tahoma"> survey</font></p>
</div>
</body>
</html>
```
<table border="1" width="450" style="font-family: Tahoma; font-size: 8pt; color: #0000FF; font-weight: bold" id="table1">
<%
set rsItem2 = server.createobject("adodb.recordset")
rsItem2.open "Select Count(CompValue)AS CompCount,CompName,CompValue from [SurvyResults_Table] WHERE FrmID="&FrmID&" group by CompValue,CompName ", dbConn, 1,3 '========== Select the components
do while NOT rsItem2.EOF
CompName=rsItem2("CompName")
CompValue=rsItem2("CompValue")
CompCount=rsItem2("CompCount")
%>
<%
set rsItem3 = server.createobject("adodb.recordset")
rsItem3.open "Select Lable,Name,CtrlValue from [Comp_Table] WHERE Forms_TableID="&FrmID&" AND Name="&CompName&" AND CtrlValue="&CompValue&" ", dbConn, 1,3 '========== Select the components
if NOT rsItem3.EOF Then
Lable=rsItem3("Lable")
End if
rsItem3.Close
set rsItem3 = Nothing
'
'========== to calculate percentage:
perc=FormatNumber((CompCount/Num_Users)*100,0)
%>
<tr>
<td width="0">"&%=Lable%"</td><td>"&%=CompName%"</td><td>"&%=CompCount%"</td><td>"&%=perc%"</td>
</tr>
<%
'For Each objField in rsItem2.Fields
Response.Write objField.Name
"&": "&rsItem2(objField.Name)& "&<BR>"
'next
rsItem2.movenext
loop
rsItem2.Close
set rsItem2 = Nothing
%>
<%
rsItem1.movenext
'loop
End if
rsItem1.Close
set rsItem1 = Nothing
%
</table></div>
<p align="center"><br/>
<font face="Tahoma"><font color="#FFFF00">Number of People used this
survey:</font></font><font color="#00FF00"><b><%=Num_Users%></b></font><font color="#FFFF00">
<% dbConn.Close
set dbConn = Nothing
%
</font><font color="#FFFF00" size="3">
<input type='hidden' name='FrmID' value='<%=FrmID%>'>
<input type='hidden' name='FormName' value='<%=FormName%>'>
</font></font></p>
<p align="center"><font face="Tahoma" color="#00FF00"><a href="Mgmt.asp">
<font color="#FFFF00">Admin</font></a></font></p>
</font></font></font></font></font></font></font></font></font></font></font></font></font></body>
</html>
Appendix B – HTML Reporting code
```html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Management</title>
<% set dbConn = Server.CreateObject("ADODB.Connection")
dbConn.Open "DBQ="&server.MapPath("Mgmt.mdb")&";Driver={Microsoft Access Driver (*.mdb)}; dbConn.mode = 3;"
%>
</head>
<body background="bg_g.gif">
<%'
set rsItem0 = server.createobject("adodb.recordset")
rsItem0.open "Select * from [Form_Table] ", dbConn, 1,3 '======== Select the components
if NOT rsItem0.EOF Then
%>
<div align="center">
<table border="1" width="88%" id="table2">
<tr>
<td align="center" width="33" bgcolor="#008080">
<font face="Tahoma" size="2" color="#FF0000"><a href="FormLayout1.asp"><font color="#00FF00"><span style="text-decoration: none">New</span></font></a></font></td>
<td align="center" width="33" bgcolor="#CCFFCC"><font color="#FF0000" size="2 " face="Tahoma">View</font></td>
<td align="center" width="33" bgcolor="#CCFFCC"><font color="#FF0000" size="2 " face="Tahoma">Edit</font></td>
<td align="center" width="43" bgcolor="#CCFFCC"><font color="#FF0000" size="2" face="Tahoma">Delete</font></td>
<td align="center" width="152" bgcolor="#FFFFCC"><font color="#FF0000" face="Tahoma" size="2">Form Name</font></td>
<td align="center" width="106" bgcolor="#FFFFCC"><font color="#FF0000" face="Tahoma" size="2">Created By</font></td>
<td align="center" bgcolor="#FFFFCC"><font color="#FF0000" face="Tahoma" size="2">Notes</font></td>
</tr>
42
```
```
<tr>
<td align="center" width="33"> </td>
<td align="center" width="33" bgcolor="#00FF00"><a href='FormSurvayResults.asp?FrmId=<%=rsItem0("ID")%>'>View</a></td>
<td align="center" width="33" bgcolor="#FFFF00"><a href='Edit.html?FrmId=<%=rsItem0("ID")%>'>Edit</a></td>
<td align="center" width="43" bgcolor="#FF0000"><a href='DltSurvay.asp?FrmId=<%=rsItem0("ID")%>'>Delete</a></td>
<td align="center" width="152"><%=rsItem0("FormName")%></td>
<td align="center" width="106"><%=rsItem0("CreatedBy")%></td>
<td align="center"><%=rsItem0("Notes_Form")%></td>
</tr>
<%do while NOT rsItem0.EOF %>
<tr>
<td align="center" width="33"> </td>
<td align="center" width="33" bgcolor="#00FF00"><a href='FormSurvayResults.asp?FrmId=<%=rsItem0("ID")%>'>View</a></td>
<td align="center" width="33" bgcolor="#FFFF00"><a href='Edit.html?FrmId=<%=rsItem0("ID")%>'>Edit</a></td>
<td align="center" width="43" bgcolor="#FF0000"><a href='DltSurvay.asp?FrmId=<%=rsItem0("ID")%>'>Delete</a></td>
<td align="center" width="152"><%=rsItem0("FormName")%></td>
<td align="center" width="106"><%=rsItem0("CreatedBy")%></td>
<td align="center"><%=rsItem0("Notes_Form")%></td>
</tr>
<%do while NOT rsItem0.EOF %>
</table>
</div>
</div>
</table>
</div>
</div>
</p align="center"><font face="Tahoma" color="#00FF00"><a href="Mgmt.asp">Admin</a></font>
</p>
</div>
</body>
Appendix C – HTML Easy-Administrating code
```html
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>How many component will your for</title>
</head>
<body style="font-family: Tahoma; font-size: 12pt; text-align:left" background="bg_g.gif">
<p align="center"></p>
<form method="POST" action="FormLayout2.asp">
<div align="center">
<table border="1" width="86%" id="table2">
<tr>
<td align="center" width="244" bgcolor="#FFFFCC"><font color="#FF0000">Form Name</font></td>
<td align="center" width="148" bgcolor="#FFFFCC"><font color="#FF0000">Created By</font></td>
<td align="center" bgcolor="#FFFFCC"><font color="#FF0000">Notes</font></td>
</tr>
<tr>
<td align="center" width="244">
<p align="center"><input type="text" name="FormName" size="34"></td>
<td align="center" width="148">
<input type="text" name="CreatedBy" size="17"></td>
<td align="center">
<input type="text" name="NotesForm" size="42"></td>
</tr>
</table>
</div>
<p> </p>
<div align="center">
<table border="0" width="46%" id="table1" cellspacing="6" cellpadding="0">
<tr>
<td width="348" colspan="3" bgcolor="#CCFFFF">
<font size="2">Select Type and number of Components to be on this FORM</font></td>
</tr>
</table>
</div>
</form>
<p> </p>
</body></html>
```
<table>
<thead>
<tr>
<th>Text box</th>
<th>Check box</th>
<th>Radio</th>
<th>Drop Down List</th>
</tr>
</thead>
<tbody>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
<tr>
<td>--------</td>
<td>-----------</td>
<td>-------</td>
<td>---------------</td>
</tr>
</tbody>
</table>
45
# Appendix D - Meeting Minutes
## Meeting Minutes (1)
Team: Network Operations
Project: D9707
Date: March 10th
Time: 10 AM
Place: 6480 XXX Pkwy 2A600
<table>
<thead>
<tr>
<th>Team Leader: Akram Dalaq</th>
<th>Meeting Facilitator:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Team Members and Other attendees: Hany Fanous</td>
<td>Title</td>
</tr>
<tr>
<td>Mike Austin</td>
<td>Network Purchasing team lead</td>
</tr>
<tr>
<td>Aaron Dye</td>
<td>Network Services Manager</td>
</tr>
<tr>
<td>Brian Carter</td>
<td>Network Operations team lead</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Time:</th>
<th>Agenda Topics:</th>
<th>Person Providing Information</th>
</tr>
</thead>
<tbody>
<tr>
<td>10:00</td>
<td>Introduction of the purpose of the meetings</td>
<td>Akram Dalaq</td>
</tr>
<tr>
<td>10:05</td>
<td>Review Action Items</td>
<td></td>
</tr>
<tr>
<td>10:05</td>
<td>Open Dialogue Questions – Answers</td>
<td></td>
</tr>
</tbody>
</table>
| Q: | What is most important to you? | Q – Akram
A: | On time code delivery, warranty and support as needed | A - Brian |
| Q: | What type of problems you would like avoid | Q – Hany
A: | We would like to be get our issues worked on in timely manner and to be given priority in terms of support | A - Brian |
| Q: | How convenient it is to get in touch with the IT team of the vendors you currently deal with today if you have issues | Q – Akram
A: | It is kind of structure process, they both have online ticketing system with average of 5 days SLA (Service Level Agreement) | A - Brian |
| Q: | I understand that getting some of the projects done through our group has helped you meet you goals for project delivery. How do you rate our | Q – Hany
A: | | A - Brian |
A: It has been good but with some issues. Several issues with the code and delays in fixing these issues. Using the ticketing system as we have 5 days SLA, but sometimes you take longer depending on the issue. These delays impact our ability to move forward which impacting the bottom line and our services by slowing down the process of upgrading switches to reduce drop calls and improve services.
10:30 Items for Next Agenda
- Issues being worked in timely manner
- Tickets past SLA
- Code delivered include many issues
Evaluate Meeting
All positive with goal to improve company services
Meeting Minutes (2)
Team: Development Team Date: March 13th
Project: NetExpert/NetCool Time: 9 AM
Place: 6220 XXX 1C423
Team Leader: Akram Dalaq Meeting Facilitator:
Team Members and Other attendees: Hany Fanous
Darin Reid Supervisor System Development
Cora Papa Senior Developer - SME
Kamran Kasra Developer III
Time: Agenda Topics: Process improvement Akram Dalaq
Review Action Items
- Discuss code delivery delays
- Discuss tickets resolution delays
- Discuss reasons code delivered to customer with issues and possible ways to minimize or eliminate these issues.
10:00 Introduction of the purpose of the meetings: Hany Fanous
Explained to the development team that a meeting took place with our main customer (Network Operations) to try find out reasons projects have been granted to outside vendor vs. our IT. During the meeting it was obvious they have been experiencing some issues and to try to figure out ways to reduce or eliminate these issues may result in re-gain their confidence and increasing the number of projects.
<table>
<thead>
<tr>
<th>10:05</th>
<th>Open Dialogue Questions – Answers</th>
</tr>
</thead>
<tbody>
<tr>
<td>Q: What are the reason behind the delay to some of these project delivered in 2007? A: There has been several instances the development and test environments were not ready for us to start coding, therefore sometimes we had to rush and deliver the code and other times we were unable to get the code ready on time for the customer to perform their testing. Q – Akram A - Cora</td>
<td></td>
</tr>
<tr>
<td>Q: So do you think not having the environment build-out on time may have impact to the number of issues experienced by the customer? A: Absolutely, not have the environment ready on time put our whole team under time crunch to meet the deadline to deploy the code during the scheduled release. Q – Akram A - Cora</td>
<td></td>
</tr>
<tr>
<td>Q: There are many incidents tickets have been resolved passed normal SLA. How do you think we can tackle this issue A: There are quite few reasons why tickets are resolved outside the usual SLA window. We can partially blame it on the environment build out which put the whole team under time constraints, we also have some internal coverage issues, such as people are out on vacation/sick or job Q – Hany A – Kamran</td>
<td></td>
</tr>
<tr>
<td>Q: What plans do we have to address this issue? A: We are aggressively looking into filling these jobs opening by advertising in other states. We will look into bettering managing vacations to provide better coverage. Q – Hany A - Darin</td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>10:30</th>
<th>Items for Next Agenda</th>
</tr>
</thead>
<tbody>
<tr>
<td>• Find out reason behind environment issues</td>
<td></td>
</tr>
<tr>
<td>• Follow up on SLA issues</td>
<td></td>
</tr>
<tr>
<td>• Meeting with the Configuration</td>
<td></td>
</tr>
</tbody>
</table>
**Management team and result**
Evaluate Meeting
Good meeting and open communications. The development team suggested that there might be other external factors such as delays in equipment installations.
---
**Appendix E – D9858 Sample Survey**

*Please fill out the D9858 Project survey.*
- [ ] Strongly Agree
- [ ] Agree
- [ ] Neither agree nor disagree
- [ ] Disagree
- [ ] Strongly Disagree
*Do you agree that the help desk staff were prompt and friendly?*
- [ ] Strongly Agree
- [ ] Agree
- [ ] Neither agree nor disagree
- [ ] Disagree
- [ ] Strongly Disagree
*Do you agree that the notes were accurate and up-to-date?*
- [ ] Strongly Agree
- [ ] Agree
- [ ] Neither agree nor disagree
- [ ] Disagree
- [ ] Strongly Disagree
*Please enter your comments:*
*Name:* [Your Name]
*Email:* [Your Email]
*Phone:* [Your Phone Number]
*Department:* [Your Department]
*Job Role:* [Your Job Role]
Appendix F – D9858 Survey Result
### Survey Results
**Question:** Do start-ups fail the network element report in fewer than 4 seconds to the user?
- Strongly Agree
- Agree
- Neutral
- Disagree
- Strongly Disagree
<table>
<thead>
<tr>
<th>Response</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td>Strongly Agree</td>
<td>20%</td>
</tr>
<tr>
<td>Agree</td>
<td>40%</td>
</tr>
<tr>
<td>Neutral</td>
<td>10%</td>
</tr>
<tr>
<td>Disagree</td>
<td>25%</td>
</tr>
<tr>
<td>Strongly Disagree</td>
<td>15%</td>
</tr>
</tbody>
</table>
**What shift do you work?**
- 1st Shift
- 2nd Shift
- 3rd Shift
<table>
<thead>
<tr>
<th>Shift</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td>1st Shift</td>
<td>50%</td>
</tr>
<tr>
<td>2nd Shift</td>
<td>30%</td>
</tr>
<tr>
<td>3rd Shift</td>
<td>20%</td>
</tr>
</tbody>
</table>
**What is your location?**
- Kansas City
- Kansas
- Boston
<table>
<thead>
<tr>
<th>Location</th>
<th>Percentage</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kansas City</td>
<td>40%</td>
</tr>
<tr>
<td>Kansas</td>
<td>40%</td>
</tr>
<tr>
<td>Boston</td>
<td>20%</td>
</tr>
</tbody>
</table>
Number of participants: **24**
|
{"Source-Url": "https://kuscholarworks.ku.edu/bitstream/handle/1808/3854/Dalaq,%20Akram%20EMGT%20Field%20Project.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 13246, "olmocr-version": "0.1.50", "pdf-total-pages": 53, "total-fallback-pages": 0, "total-input-tokens": 86491, "total-output-tokens": 16816, "length": "2e13", "weborganizer": {"__label__adult": 0.000820159912109375, "__label__art_design": 0.0030193328857421875, "__label__crime_law": 0.0007734298706054688, "__label__education_jobs": 0.2137451171875, "__label__entertainment": 0.000606536865234375, "__label__fashion_beauty": 0.0005693435668945312, "__label__finance_business": 0.03509521484375, "__label__food_dining": 0.0008730888366699219, "__label__games": 0.0017004013061523438, "__label__hardware": 0.004913330078125, "__label__health": 0.0015211105346679688, "__label__history": 0.0012483596801757812, "__label__home_hobbies": 0.0011796951293945312, "__label__industrial": 0.0035724639892578125, "__label__literature": 0.0014896392822265625, "__label__politics": 0.0007472038269042969, "__label__religion": 0.0008111000061035156, "__label__science_tech": 0.1793212890625, "__label__social_life": 0.0007472038269042969, "__label__software": 0.039459228515625, "__label__software_dev": 0.5048828125, "__label__sports_fitness": 0.0005965232849121094, "__label__transportation": 0.0014905929565429688, "__label__travel": 0.0006556510925292969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 70577, 0.02328]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 70577, 0.20291]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 70577, 0.87162]], "google_gemma-3-12b-it_contains_pii": [[0, 537, false], [537, 1228, null], [1228, 2821, null], [2821, 8229, null], [8229, 9071, null], [9071, 10617, null], [10617, 12122, null], [12122, 13824, null], [13824, 15556, null], [15556, 17386, null], [17386, 19205, null], [19205, 21124, null], [21124, 22889, null], [22889, 24573, null], [24573, 26490, null], [26490, 27818, null], [27818, 29463, null], [29463, 30935, null], [30935, 32264, null], [32264, 33330, null], [33330, 35124, null], [35124, 36820, null], [36820, 38564, null], [38564, 40374, null], [40374, 42066, null], [42066, 43716, null], [43716, 44247, null], [44247, 45676, null], [45676, 47085, null], [47085, 48163, null], [48163, 48939, null], [48939, 50728, null], [50728, 51019, null], [51019, 52005, null], [52005, 53106, null], [53106, 54245, null], [54245, 55321, null], [55321, 56149, null], [56149, 57543, null], [57543, 58792, null], [58792, 59504, null], [59504, 61002, null], [61002, 62354, null], [62354, 63695, null], [63695, 64092, null], [64092, 64092, null], [64092, 65596, null], [65596, 66825, null], [66825, 68871, null], [68871, 69825, null], [69825, 69825, null], [69825, 69858, null], [69858, 70577, null]], "google_gemma-3-12b-it_is_public_document": [[0, 537, true], [537, 1228, null], [1228, 2821, null], [2821, 8229, null], [8229, 9071, null], [9071, 10617, null], [10617, 12122, null], [12122, 13824, null], [13824, 15556, null], [15556, 17386, null], [17386, 19205, null], [19205, 21124, null], [21124, 22889, null], [22889, 24573, null], [24573, 26490, null], [26490, 27818, null], [27818, 29463, null], [29463, 30935, null], [30935, 32264, null], [32264, 33330, null], [33330, 35124, null], [35124, 36820, null], [36820, 38564, null], [38564, 40374, null], [40374, 42066, null], [42066, 43716, null], [43716, 44247, null], [44247, 45676, null], [45676, 47085, null], [47085, 48163, null], [48163, 48939, null], [48939, 50728, null], [50728, 51019, null], [51019, 52005, null], [52005, 53106, null], [53106, 54245, null], [54245, 55321, null], [55321, 56149, null], [56149, 57543, null], [57543, 58792, null], [58792, 59504, null], [59504, 61002, null], [61002, 62354, null], [62354, 63695, null], [63695, 64092, null], [64092, 64092, null], [64092, 65596, null], [65596, 66825, null], [66825, 68871, null], [68871, 69825, null], [69825, 69825, null], [69825, 69858, null], [69858, 70577, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 70577, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 70577, null]], "pdf_page_numbers": [[0, 537, 1], [537, 1228, 2], [1228, 2821, 3], [2821, 8229, 4], [8229, 9071, 5], [9071, 10617, 6], [10617, 12122, 7], [12122, 13824, 8], [13824, 15556, 9], [15556, 17386, 10], [17386, 19205, 11], [19205, 21124, 12], [21124, 22889, 13], [22889, 24573, 14], [24573, 26490, 15], [26490, 27818, 16], [27818, 29463, 17], [29463, 30935, 18], [30935, 32264, 19], [32264, 33330, 20], [33330, 35124, 21], [35124, 36820, 22], [36820, 38564, 23], [38564, 40374, 24], [40374, 42066, 25], [42066, 43716, 26], [43716, 44247, 27], [44247, 45676, 28], [45676, 47085, 29], [47085, 48163, 30], [48163, 48939, 31], [48939, 50728, 32], [50728, 51019, 33], [51019, 52005, 34], [52005, 53106, 35], [53106, 54245, 36], [54245, 55321, 37], [55321, 56149, 38], [56149, 57543, 39], [57543, 58792, 40], [58792, 59504, 41], [59504, 61002, 42], [61002, 62354, 43], [62354, 63695, 44], [63695, 64092, 45], [64092, 64092, 46], [64092, 65596, 47], [65596, 66825, 48], [66825, 68871, 49], [68871, 69825, 50], [69825, 69825, 51], [69825, 69858, 52], [69858, 70577, 53]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 70577, 0.0768]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
086467e8e5ca4a8356e7a6b4fa9a72cbda94628f
|
Practical Concurrent and Parallel Programming 4
Peter Sestoft
IT University of Copenhagen
Friday 2016-09-23
Plan for today
• **Performance measurements**
• A class for measuring elapsed wall-clock time
– Mark0-5: Towards reliable measurements
– Mark6-7: Automated general measurements
• Measuring execution time
– of memory accesses
– of thread creation, start, execution
– of *volatile* fields
• Measuring the prime counting example
• General advice, warnings and pitfalls
Ad: Want to be a student programmer?
- **Popular Parallel Programming (P3) project**
- Project goal: To allow spreadsheet users harness the power of multicore computers; or *end-user supercomputing*.
- ITU: Florian and Alexander (PhDs), Peter Sestoft
- AAU: Bent Thomsen, Lone Thomsen, Kim Larsen
- **We need a research programmer!**
- You need these skills:
- Strong C#, OO and functional programming skills
- Disciplined developer
- Understanding of spreadsheets
How long does this method take?
private static double multiply(int i) {
double x = 1.1 * (double)(i & 0xFF);
return x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x * x;
}
• Does an int operation, int-double conversion, and 20 floating-point multiplications
• So takes at least $20 \times 0.4 = 8$ ns
• Tricks used in this code:
– Make result depend on $i$ to avoid caching
– The $i \& 0xFF$ is in range 0—255, avoids overflow
– Multiply $i \& 0xFF$ by 1.1 to make it floating-point
Back-of-the envelope calculations
• 2.4 GHz processor = 0.4 ns/cycle = 0.4 \times 10^{-9} s
• Throughput:
– Addition or multiplication takes 1 cycle
– Division maybe 15 cycles
– Transcendental functions, \( \sin(x) \) maybe 100-200?
• Instruction-level parallelism
– 2-3 integer operations/cycle, only sometimes
• Memory latency
– Registers: 1 cycle
– L1 cache: a few cycles
– L2 cache: many cycles
– RAM: hundreds of cycles – expensive cache misses!
Plan for today
• Performance measurements
• **A class for measuring wall-clock time**
– **Mark0-5: Towards reliable measurements**
– **Mark6-7: Automated general measurements**
• Measuring execution time
– of memory accesses
– of thread creation, start, execution
– of volatile fields
• Measuring the prime counting example
• General advice, warnings and pitfalls
A simple Timer class for Java
- We measure elapsed wall-clock time
- This is what matters in reality
- Can measure uniformly on Linux, MacOS, Windows
- Enables comparison Java/C#/C/Scala/F# etc
```java
public class Timer {
private long start, spent = 0;
public Timer() { play(); }
public double check()
{ return (System.nanoTime()-start+spent)/1e9; }
public void pause() { spent += System.nanoTime()-start; }
public void play() { start = System.nanoTime(); }
}
```
- Alternatives: total CPU time, or user + kernel
- Never use imprecise, slow `new Date().getTime()`
- Q: Reasons to measure total CPU time?
Mark0: naïve attempt
Useless because
- Runtime start-up costs larger than execution time
- Timer resolution too coarse, likely 100 ns
- So result are unrealistic and vary a lot
```
public static void Mark0() {
Timer t = new Timer();
double dummy = multiply(10);
double time = t.check() * 1e9;
System.out.printf("%6.1f ns\n", time);
}
```
5000.0 ns
6000.0 ns
4500.0 ns
Mark1: Measure many operations
public static void Mark1() {
Timer t = new Timer();
Integer count = 1_000_000;
for (int i=0; i<count; i++) {
double dummy = multiply(i);
}
double time = t.check() * 1e9 / count;
System.out.printf("%6.1f ns\n", time);
}
- Measure 1 million calls; better but fragile:
- If count is larger, optimizer may notice that result of multiply is not used, and remove call
- So-called “dead code elimination”
- May give completely unrealistic results
Java compiler and virtual machine
The `javac` compiler is simple, makes no optimizations
The `java` runtime system (JIT) is clever, makes many
Mark2: Avoid dead code elimination
public static double Mark2() {
Timer t = new Timer();
int count = 100_000_000;
double dummy = 0.0;
for (int i=0; i<count; i++)
dummy += multiply(i);
double time = t.check() * 1e9 / count;
System.out.printf("%6.1f ns\n", time);
return dummy;
}
• Much more reliable
Mark3: Automate multiple samples
```java
int n = 10;
int count = 100_000_000;
double dummy = 0.0;
for (int j=0; j<n; j++) {
Timer t = new Timer();
for (int i=0; i<count; i++)
dummy += multiply(i);
double time = t.check() * 1e9 / count;
System.out.printf("%6.1f ns\n", time);
}
```
- Multiple samples gives an impression of reproducibility
Mark4: Compute standard deviation
```java
int count = 100_000_000;
double st = 0.0, sst = 0.0;
for (int j=0; j<n; j++) {
Timer t = new Timer();
for (int i=0; i<count; i++)
dummy += multiply(i);
double time = t.check() * 1e9 / count;
st += time;
sst += time * time;
}
double mean = st/n,
sdev = Math.sqrt((sst - mean*mean*n)/(n-1));
System.out.printf("%6.1f ns +/- %6.3f \n", mean, sdev);
```
• The standard deviation $\sigma$ summarizes the variation around the mean, in a single number
30.3 ns +/- 0.137
Statistics: Central limit theorem
• The average of \( n \) independent identically distributed observations \( t_1, t_2, \ldots, t_n \) tends to follow the normal distribution \( N(\mu, \sigma^2) \) where
\[
\mu = \frac{1}{n} \sum_{j=1}^{n} t_j
\]
\[
\sigma = \sqrt{\frac{1}{n} \sum_{j=1}^{n} t_j^2} - \mu^2
\]
when \( n \) tends to infinity
• Eg with probability 68.3% the "real" result is between 30.163 ns and 30.437 ns
The normal distribution $N(\mu, \sigma^2)$
68.3% of observations in $[\mu-\sigma, \mu+\sigma]$, between blue lines
95.4% of observations in $[\mu-2\sigma, \mu+2\sigma]$, between red lines
```java
int n = 10, count = 1, totalCount = 0;
double dummy = 0.0, runningTime = 0.0;
do {
count *= 2;
double st = 0.0, sst = 0.0;
for (int j=0; j<n; j++) {
Timer t = new Timer();
for (int i=0; i<count; i++)
dummy += multiply(i);
runningTime = t.check();
double time = runningTime * 1e9 / count;
st += time;
sst += time * time;
totalCount += count;
}
double mean = st/n, sdev = Math.sqrt((sst - mean*mean*n)/(n-1));
} while (runningTime < 0.25 && count < Integer.MAX_VALUE/2);
return dummy / totalCount;
```
### Example results from Mark5
<table>
<thead>
<tr>
<th>mean time</th>
<th>sdev</th>
<th>count</th>
</tr>
</thead>
<tbody>
<tr>
<td>100.0 ns +/- 200.00</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>100.0 ns +/- 122.47</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>62.5 ns +/- 62.50</td>
<td>8</td>
<td></td>
</tr>
<tr>
<td>50.0 ns +/- 37.50</td>
<td>16</td>
<td></td>
</tr>
<tr>
<td>46.9 ns +/- 15.63</td>
<td>32</td>
<td></td>
</tr>
<tr>
<td>40.6 ns +/- 10.36</td>
<td>64</td>
<td></td>
</tr>
<tr>
<td>39.8 ns +/- 2.34</td>
<td>128</td>
<td></td>
</tr>
<tr>
<td>36.3 ns +/- 1.79</td>
<td>256</td>
<td></td>
</tr>
<tr>
<td>36.5 ns +/- 1.25</td>
<td>512</td>
<td></td>
</tr>
<tr>
<td>35.6 ns +/- 0.49</td>
<td>1024</td>
<td></td>
</tr>
<tr>
<td>111.1 ns +/- 232.18</td>
<td>2048</td>
<td></td>
</tr>
<tr>
<td>36.1 ns +/- 1.75</td>
<td>4096</td>
<td></td>
</tr>
<tr>
<td>33.7 ns +/- 0.84</td>
<td>8192</td>
<td></td>
</tr>
<tr>
<td>32.5 ns +/- 1.07</td>
<td>16384</td>
<td></td>
</tr>
<tr>
<td>35.6 ns +/- 4.84</td>
<td>32768</td>
<td></td>
</tr>
<tr>
<td>30.4 ns +/- 0.26</td>
<td>65536</td>
<td></td>
</tr>
<tr>
<td>33.1 ns +/- 5.06</td>
<td>131072</td>
<td></td>
</tr>
<tr>
<td>30.3 ns +/- 0.49</td>
<td>262144</td>
<td></td>
</tr>
</tbody>
</table>
Outlier, maybe due to other program activity
Advantages of Mark5
• The early rounds (2, 4, ...) serve as warm-up
– Make sure the code is in memory and cache
• Measured code loop runs at least 0.25 sec
– Roughly 500 million CPU cycles
– Lessen impact of other activity on computer
– Makes sure code has been JIT compiled
• Still, total time spent measuring at most 1 sec
– Because last measurement runs at most 0.5 sec
– and sum of previous times is same time as last one
• because $2 + 4 + 8 + \ldots + 2^n < 2^{n+1}$
• Independent of problem and hardware
Development of the benchmarking method
- Mark0: Measure one call, useless
- Mark1: Measure many calls, nearly useless
- Mark2: Avoid dead code elimination
- Mark3: Automate multiple samples
- Mark4: Compute standard deviation
- Mark5: Automate choice of iteration count
- But need to measure not just multiply!
Plan for today
• Performance measurements
• A class for measuring elapsed wall-clock time
– Mark0-5: Towards reliable measurements
– **Mark6-7: Automated general measurements**
• Measuring execution time
– of memory accesses
– of thread creation, start, execution
– of volatile fields
• Measuring the prime counting example
• General advice, warnings and pitfalls
Mark6: Generalize to any function
```java
public interface IntToDoubleFunction {
double applyAsDouble(int i);
}
static double Mark6(String msg, IntToDoubleFunction f) {
...
do {
...
for (int j=0; j<n; j++) {
...
for (int i=0; i<count; i++)
dummy += f.applyAsDouble(i);
}
}
...
System.out.printf("%-25s %15.1f ns %10.2f %10d\n", msg, ...
} while (runningTime<0.25 && count<Integer.MAX_VALUE/2);
return dummy / totalCount;
```
Example use of Mark6
Mark6("multiply", Benchmark::multiply);
| multiply | 800.0 ns | 1435.27 | 2 |
| multiply | 250.0 ns | 0.00 | 4 |
| multiply | 212.5 ns | 80.04 | 8 |
| multiply | 187.5 ns | 39.53 | 16 |
| multiply | 200.0 ns | 82.92 | 32 |
| multiply | 57.8 ns | 24.26 | 64 |
| multiply | 46.9 ns | 4.94 | 128|
| ... | | | |
| multiply | 30.6 ns | 0.61 | 2097152|
| multiply | 30.0 ns | 0.10 | 4194304|
| multiply | 30.1 ns | 0.15 | 8388608|
Method reference to the function to be measured
public static double Mark7(String msg, IntToDoubleFunction f) {
...
do {
...
} while (runningTime<0.25 && count<Integer.MAX_VALUE/2);
double mean = st/n, sdev = Math.sqrt((sst - mean*mean*n)/
System.out.printf("%-25s %15.1f ns %10.2f %10d\n", ...");
return dummy / totalCount;
}
Mark7("pow", i -> Math.pow(10.0, 0.1 * (i & 0xFF)));
Mark7("exp", i -> Math.exp(0.1 * (i & 0xFF)));
Mark7("log", i -> Math.log(0.1 + 0.1 * (i & 0xFF)));
Mark7("sin", i -> Math.sin(0.1 * (i & 0xFF)));
Mark7("cos", i -> Math.cos(0.1 * (i & 0xFF)));
Mark7("tan", i -> Math.tan(0.1 * (i & 0xFF)));
...
Mark 7 benchmarking results for Java mathematical functions
<table>
<thead>
<tr>
<th>Function</th>
<th>Time (ns)</th>
<th>Frequency (%)</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>pow</td>
<td>75.5</td>
<td>0.43</td>
<td>4194304</td>
</tr>
<tr>
<td>exp</td>
<td>54.9</td>
<td>0.19</td>
<td>8388608</td>
</tr>
<tr>
<td>log</td>
<td>31.4</td>
<td>0.16</td>
<td>8388608</td>
</tr>
<tr>
<td>sin</td>
<td>116.3</td>
<td>0.41</td>
<td>4194304</td>
</tr>
<tr>
<td>cos</td>
<td>116.6</td>
<td>0.33</td>
<td>4194304</td>
</tr>
<tr>
<td>tan</td>
<td>143.6</td>
<td>0.48</td>
<td>2097152</td>
</tr>
<tr>
<td>asin</td>
<td>229.7</td>
<td>2.24</td>
<td>2097152</td>
</tr>
<tr>
<td>acos</td>
<td>217.0</td>
<td>2.46</td>
<td>2097152</td>
</tr>
<tr>
<td>atan</td>
<td>54.3</td>
<td>0.84</td>
<td>8388608</td>
</tr>
</tbody>
</table>
- 2.4 GHz Intel i7; MacOS 10.9.4; 64-bit JVM 1.8.0_11
- So $\sin(x)$ takes $116.3 \text{ ns} \times 2.4 \text{ GHz} = 279 \text{ cycles}$
- approximately
Saving measurements to a text file
• Command line in Linux, MacOS, Windows
```
java Benchmark > benchmark-20150918.txt
```
• In Linux, MacOS get both file and console
```
java Benchmark | tee benchmark-20150918.txt
```
Platform identification
```java
public static void SystemInfo() {
System.out.printf("# OS: %s; %s; %s%n",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"));
System.out.printf("# JVM: %s; %s%n",
System.getProperty("java.vendor"),
System.getProperty("java.version"));
// The processor identifier works only on MS Windows:
System.out.printf("# CPU: %s; %d "cores"%n",
System.getenv("PROCESSOR_IDENTIFIER"),
Runtime.getRuntime().availableProcessors());
java.util.Date now = new java.util.Date();
System.out.printf("# Date: %s%n",
new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(now));
}
```
- **Output information about platform and date:**
# OS: Mac OS X; 10.9.5; x86_64
# JVM: Oracle Corporation; 1.8.0_51
# CPU: null; 8 "cores"
# Date: 2015-09-15T14:36:48+0200
15 September 2015 at 14:36 in UTC+2h
Plan for today
• Performance measurements
• A class for measuring elapsed wall-clock time
– Mark0-5: Towards reliable measurements
– Mark6-7: Automated general measurements
• **Measuring execution time**
– of memory accesses
– of thread creation, start, execution
– of volatile fields
• Measuring the prime counting example
• General advice, warnings and pitfalls
Cost of memory access
- CPU is fast, RAM slow. Solution: caches
![Diagram showing memory hierarchy with CPU, registers, L1 cache, L2 cache, L3 cache, and RAM]
- How measure it: Array access with “jumps”
```java
int k = 0;
for (int j=0; j<33_554_432; j++)
k = arr[k];
```
- Memory footprint equals cycle length
- Fixed number of iterations
Memory speeds ns/access as function of memory footprint (bytes)
Cost of object creation
• First: how long to create an ordinary object?
```java
class Point {
public final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
}
```
```java
Mark6("Point creation",
i -> {
Point p = new Point(i, i);
return p.hashCode();
});
```
• Result on i7, approximately 80 ns
• Q: Why return `p.hashCode()`?
• Computing the hash code takes 3.3 ns
– Q: How can I know that?
Cost of thread creation
- Takes 1030 ns, or 13 x slower than a Point
- So a Thread object must be somewhat complicated
```java
Mark6("Thread create",
i -> {
Thread t = new Thread(() -> {
for (int j=0; j<1000; j++)
ai.getAndIncrement();
});
return t.hashCode();
});
```
Actual work, not run, not measured
What we measure
Cost of thread create + start
- Takes 49000 ns
- So a lot of work goes into setting up a task
- Even after creating it
- Note: does **not** include executing the loop
```java
Mark6("Thread create start",
i -> {
Thread t = new Thread(() -> {
for (int j=0; j<1000; j++)
ai.getAndIncrement();
});
t.start();
return t.hashCode();
});
```
Actual work, mostly not run
What we measure
Cost of thread create+start+run+join
- Takes 72700 ns
- Of this, the actual work is 6580 ns, in loop
- Thus ca. 1080 ns to create; 48000 ns to start; 13000 ns run and join; 6580 ns actual work
- *Never create threads for small computations*
```java
Mark6("Thread create start join",
i -> {
Thread t = new Thread(() -> {
for (int j=0; j<1000; j++)
ai.getAndIncrement();
});
t.start();
try { t.join(); }
catch (InterruptedException exn) { }
return t.hashCode();
});
```
Actual work is done because of join()
Cost of taking a free lock
- Takes 4.5 ns although sometime 20 ns instead
- Both are very fast
- The result of much engineering on the Java VM
- Taking a free lock was much slower in early Java
- Today no need to use “double-checked-locking”, Goetz antipattern p. 349
- Q: Is it possible to measure time to take a lock already held by another thread?
Cost of volatile
```java
class IntArrayVolatile {
private volatile int[] array;
public IntArray(int length) { array = new int[length]; ... }
public boolean isSorted() {
for (int i=1; i<array.length; i++)
if (array[i-1] > array[i])
return false;
return true;
}
}
```
<table>
<thead>
<tr>
<th>Class</th>
<th>Time</th>
<th>Memory</th>
<th>Size</th>
</tr>
</thead>
<tbody>
<tr>
<td>IntArray</td>
<td>3.4 us</td>
<td>0.01</td>
<td>131072</td>
</tr>
<tr>
<td>IntArrayVolatile</td>
<td>17.2 us</td>
<td>0.14</td>
<td>16384</td>
</tr>
</tbody>
</table>
- Volatile read is 5 x slower in this case
- JIT compiler performs fewer optimizations
- Q: Why not make volatile the default?
Volatile prevents JIT optimizations
• For-loop body of `isSorted`, JITted x86 code:
```assembly
0xdff0: mov 0xc(%rsi),%r8d ; LOAD %r8d = array field
0xdfff4: mov %r10d,%r9d ; i NOW IN %r9d
0xdfff7: dec %r9d ; i-1 IN %r9d
0xdfffa: mov 0xc(%r12,%r8,8),%ecx ; LOAD %ecx = array.length
0xdfff: cmp %ecx,%r9d ; INDEX CHECK array.length <= i-1
0xe002: jae 0xe004b ; IF SO, THROW
0xe0004: mov 0xc(%rsi),%ecx ; LOAD %ecx = array field
0xe0007: lea (%r12,%r8,8),%r11 ; LOAD %r11 = array base address
0xe000b: mov 0xc(%r11,%r10,4),%r1ld; LOAD %r1ld = arr[i-1]
0xe0010: mov 0xc(%r12,%rcx,8),%r8d ; LOAD %r8d = array.length
0xe0015: cmp %r8d,%r10d ; INDEX CHECK array.length <= i
0xe0018: jae 0xe006d ; IF SO, THROW
0xe001a: lea (%r12,rcx,8),%r8 ; LOAD %r8 = array base address
0xe001e: mov 0x10(%r8,%r10,4),%r9d; LOAD %r9d = array[i]
0xe0023: cmp %r9d,%r1ld ; IF arr[i] < array[i-1]
0xe0026: jg 0xe008d ; RETURN FALSE
0xe0028: mov 0xc(%rsi),%r8d ; LOAD %r8d = array field
0xe002c: inc %r10d ; i++
```
VolatileArray.java
array volatile
3 reads of array field
2 index checks
• Non-volatile: read `arr` once, unroll loop, ...
```assembly
0xcb9: mov 0xc(%rdi,%r11,4),%r8d ; LOAD %rd8d = array[i-1]
0xcbe: mov 0x10(%rdi,%r11,4),%r10d; LOAD %rd10d = array[i]
0xcc3: cmp %r10d,%r8d ; IF array[i] > array[i-1]
0xcc6: jg 0xd85 ; RETURN FALSE
```
## Full measurements on two platforms
<table>
<thead>
<tr>
<th>Method</th>
<th>Time</th>
<th>Error</th>
<th>Measurements</th>
</tr>
</thead>
<tbody>
<tr>
<td>hashCode()</td>
<td>3.3 ns</td>
<td>0.02</td>
<td>134217728</td>
</tr>
<tr>
<td>Point creation</td>
<td>80.9 ns</td>
<td>1.06</td>
<td>4194304</td>
</tr>
<tr>
<td>Thread's work</td>
<td>6581.5 ns</td>
<td>37.64</td>
<td>65536</td>
</tr>
<tr>
<td>Thread create</td>
<td>1030.3 ns</td>
<td>20.17</td>
<td>262144</td>
</tr>
<tr>
<td>Thread create start</td>
<td>48929.6 ns</td>
<td>320.94</td>
<td>8192</td>
</tr>
<tr>
<td>Thread create start join</td>
<td>72758.9 ns</td>
<td>1204.68</td>
<td>4096</td>
</tr>
<tr>
<td>Uncontended lock</td>
<td>4.1 ns</td>
<td>0.06</td>
<td>67108864</td>
</tr>
</tbody>
</table>
**Intel i7, 2.4 GHz, 4 core**
45 W, Sep 2012, $378
<table>
<thead>
<tr>
<th>Method</th>
<th>Time</th>
<th>Error</th>
<th>Measurements</th>
</tr>
</thead>
<tbody>
<tr>
<td>hashCode()</td>
<td>15.5 ns</td>
<td>0.01</td>
<td>16777216</td>
</tr>
<tr>
<td>Point creation</td>
<td>184.1 ns</td>
<td>0.43</td>
<td>2097152</td>
</tr>
<tr>
<td>Thread's work</td>
<td>30802.5 ns</td>
<td>18.65</td>
<td>8192</td>
</tr>
<tr>
<td>Thread create</td>
<td>3690.2 ns</td>
<td>7.99</td>
<td>131072</td>
</tr>
<tr>
<td>Thread create start</td>
<td>153097.2 ns</td>
<td>11142.30</td>
<td>2048</td>
</tr>
<tr>
<td>Thread create start join</td>
<td>165992.8 ns</td>
<td>3916.62</td>
<td>2048</td>
</tr>
<tr>
<td>Uncontended lock</td>
<td>16.9 ns</td>
<td>0.01</td>
<td>16777216</td>
</tr>
</tbody>
</table>
**AMD 6386 SE, 2.8 GHz, 16 core**
140 W, Nov 2012, $1392
Plan for today
• Performance measurements
• A class for measuring elapsed wall-clock time
– Mark0-5: Towards reliable measurements
– Mark6-7: Automated general measurements
• Measuring execution time
– of memory accesses
– of thread creation, start, execution
– of volatile fields
• Measuring the prime counting example
• General advice, warnings and pitfalls
Measuring TestCountPrimes
```java
final int range = 100_000;
Mark6("countSequential",
i -> countSequential(range));
Mark6("countParallel",
i -> countParallelN(range, 10));
```
- Include Mark6 and Mark7 in source file
- Modified to show microseconds not nanoseconds
- Reduce range to 100,000
- Threads must be join()’ed to measure time
- Else you just measure the time to create and start, not the time to actually compute
### TestCountPrimes results, 10 threads
<table>
<thead>
<tr>
<th>Method</th>
<th>Time (us)</th>
<th>Speedup</th>
<th>Threads</th>
</tr>
</thead>
<tbody>
<tr>
<td>countSequential</td>
<td>11117.3</td>
<td>501.25</td>
<td>2</td>
</tr>
<tr>
<td>countSequential</td>
<td>10969.3</td>
<td>82.93</td>
<td>4</td>
</tr>
<tr>
<td>countSequential</td>
<td>10935.4</td>
<td>52.34</td>
<td>8</td>
</tr>
<tr>
<td>countSequential</td>
<td>10936.0</td>
<td>32.76</td>
<td>16</td>
</tr>
<tr>
<td>countSequential</td>
<td>10970.5</td>
<td>142.69</td>
<td>32</td>
</tr>
<tr>
<td>countParallel</td>
<td>3944.9</td>
<td>764.30</td>
<td>2</td>
</tr>
<tr>
<td>countParallel</td>
<td>3397.5</td>
<td>166.58</td>
<td>4</td>
</tr>
<tr>
<td>countParallel</td>
<td>3218.1</td>
<td>59.62</td>
<td>8</td>
</tr>
<tr>
<td>countParallel</td>
<td>3224.4</td>
<td>62.28</td>
<td>16</td>
</tr>
<tr>
<td>countParallel</td>
<td>3261.4</td>
<td>65.42</td>
<td>32</td>
</tr>
<tr>
<td>countParallel</td>
<td>3379.1</td>
<td>224.53</td>
<td>64</td>
</tr>
<tr>
<td>countParallel</td>
<td>3239.2</td>
<td>111.56</td>
<td>128</td>
</tr>
</tbody>
</table>
- So 10 threads is $10970/3239 = 3.4$ x faster
- What about 1 thread, 2, ..., 32 threads?
Measuring different thread counts
Mark7("countSequential", i -> countSequential(range));
for (int c=1; c<=100; c++) {
final int threadCount = c;
Mark7(String.format("countParallelLocal %6d",
threadCount),
i -> countParallelNLocal(range, threadCount));
}
• Q: Why the final int threadCount = c?
TestCountPrimes results
- One thread slower than sequential
- Max speedup 4.1x
- From some point, more threads are worse
- How choose best thread count?
- Tasks and executors are better than threads, week 5
<table>
<thead>
<tr>
<th>countParallel</th>
<th>1</th>
<th>11887.9 us</th>
<th>513.02</th>
<th>32</th>
</tr>
</thead>
<tbody>
<tr>
<td>countParallel</td>
<td>2</td>
<td>7313.4 us</td>
<td>792.47</td>
<td>32</td>
</tr>
<tr>
<td>countParallel</td>
<td>3</td>
<td>5085.8 us</td>
<td>67.75</td>
<td>64</td>
</tr>
<tr>
<td>countParallel</td>
<td>4</td>
<td>4697.3 us</td>
<td>76.39</td>
<td>64</td>
</tr>
<tr>
<td>countParallel</td>
<td>5</td>
<td>4042.7 us</td>
<td>40.06</td>
<td>64</td>
</tr>
<tr>
<td>countParallel</td>
<td>6</td>
<td>3577.5 us</td>
<td>19.87</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>7</td>
<td>3233.1 us</td>
<td>8.28</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>8</td>
<td>3149.4 us</td>
<td>77.59</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>9</td>
<td>3196.3 us</td>
<td>11.66</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>10</td>
<td>3203.0 us</td>
<td>8.49</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>11</td>
<td>3198.5 us</td>
<td>15.70</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>12</td>
<td>3263.3 us</td>
<td>27.53</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>13</td>
<td>3128.0 us</td>
<td>16.66</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>14</td>
<td>3021.6 us</td>
<td>19.58</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>15</td>
<td>2960.8 us</td>
<td>11.23</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>16</td>
<td>3033.4 us</td>
<td>65.49</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>17</td>
<td>2926.2 us</td>
<td>5.94</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>18</td>
<td>2972.6 us</td>
<td>21.47</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>19</td>
<td>3001.7 us</td>
<td>6.40</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>20</td>
<td>3051.9 us</td>
<td>37.81</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>21</td>
<td>2992.3 us</td>
<td>8.10</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>22</td>
<td>2978.9 us</td>
<td>20.45</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>23</td>
<td>2957.3 us</td>
<td>5.70</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>24</td>
<td>2978.5 us</td>
<td>7.67</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>25</td>
<td>3006.8 us</td>
<td>38.01</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>26</td>
<td>2972.0 us</td>
<td>19.80</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>27</td>
<td>2993.0 us</td>
<td>63.53</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>28</td>
<td>3008.0 us</td>
<td>24.42</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>29</td>
<td>2997.7 us</td>
<td>5.80</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>30</td>
<td>3019.1 us</td>
<td>21.74</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>31</td>
<td>2998.5 us</td>
<td>2.80</td>
<td>128</td>
</tr>
<tr>
<td>countParallel</td>
<td>32</td>
<td>3000.7 us</td>
<td>2.38</td>
<td>128</td>
</tr>
</tbody>
</table>
Making plots of measurements
- Zillions of plotting and charting programs, including Excel, Gnuplot, R, Ploticus, ...
- Always use scatter (x-y) plots, no smoothing
General advice
• To avoid interference with measurements, shut down other programs: mail, Skype, browsers, Dropbox, iTunes, MS Office ...
• Disable logging and debugging messages
• Compile with optimizations enabled
• Never measure inside IDEs such as Eclipse
• Turn off power-savings modes
• Run on mains power, not on battery
• Lots of differences between
– Runtime systems: Oracle, IBM Java; Mono, .NET
– CPUs: Intel i5, i7, Xeon, AMD, ARM, ...
Mistakes and pitfalls
- Windows Upgrade etc may ruin measurements
- Runs at unpredictable times, and is slow
- Some CPUs have a temporary “turbo mode”
- May increase clock speed, will ruin measurements
- Some CPUs do “thermal throttling” if too hot
- May reduce clock speed, will ruin measurements
- Measure the right thing
- Eg when measuring binary search, do not search for the same item repeatedly (notes §11)
- Beware of irrelevant overheads
- For instance random number generation
- (But now you know how to measure the overhead!)
Timing threads à la Goetz & Bloch
• A countdown N-latch is a use-once gate
– When latch.countDown() has been called N times, all threads blocked on latch.await() are unblocked
• Can use it to measure thread wall-clock time
– excluding thread creation and start-up
• But thread start costs seems relevant too...
Timing threads à la Goetz & Bloch
- All threads start nearly at the same time
- Measure excludes thread creation overhead
```java
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored) {
}
}
});
t.start();
}
Timer timer = new Timer();
startGate.countDown();
endGate.await();
double time = timer.check();
```
Throughput versus latency
- Throughput is results per second
- Latency is time to first result
Water pipe analogy:
- Pipe diameter determines throughput, drops/sec
- Pipe length determines latency, time to first drop
We measure inverse throughput, sec/result
This week
• Reading
– Sestoft: Microbenchmarks in Java and C#
– (Optional) McKenney chapter 3
• Exercises week 4 = Mandatory hand-in 2
– Conduct meaningful performance measurements and comparisons, and discuss the results
• Read before next week’s lecture
– Goetz chapters 6 and 8
– Bloch items 68, 69
|
{"Source-Url": "http://www.itu.dk/people/sestoft/itu/PCPP/E2016/lecture04.pdf", "len_cl100k_base": 9408, "olmocr-version": "0.1.50", "pdf-total-pages": 49, "total-fallback-pages": 0, "total-input-tokens": 74952, "total-output-tokens": 10957, "length": "2e13", "weborganizer": {"__label__adult": 0.00033664703369140625, "__label__art_design": 0.0002779960632324219, "__label__crime_law": 0.0002567768096923828, "__label__education_jobs": 0.00270843505859375, "__label__entertainment": 6.258487701416016e-05, "__label__fashion_beauty": 0.0001379251480102539, "__label__finance_business": 0.0002124309539794922, "__label__food_dining": 0.000331878662109375, "__label__games": 0.000667572021484375, "__label__hardware": 0.0013494491577148438, "__label__health": 0.0003643035888671875, "__label__history": 0.0002689361572265625, "__label__home_hobbies": 0.00014495849609375, "__label__industrial": 0.0005483627319335938, "__label__literature": 0.0002048015594482422, "__label__politics": 0.000225067138671875, "__label__religion": 0.0005135536193847656, "__label__science_tech": 0.01416778564453125, "__label__social_life": 0.00013434886932373047, "__label__software": 0.00386810302734375, "__label__software_dev": 0.97216796875, "__label__sports_fitness": 0.0004224777221679687, "__label__transportation": 0.0006041526794433594, "__label__travel": 0.00023698806762695312}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 25537, 0.06836]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 25537, 0.24389]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 25537, 0.66744]], "google_gemma-3-12b-it_contains_pii": [[0, 110, false], [110, 505, null], [505, 984, null], [984, 1526, null], [1526, 1997, null], [1997, 2372, null], [2372, 3019, null], [3019, 3407, null], [3407, 3918, null], [3918, 4063, null], [4063, 4400, null], [4400, 4765, null], [4765, 5309, null], [5309, 5737, null], [5737, 5927, null], [5927, 6523, null], [6523, 7169, null], [7169, 7697, null], [7697, 8010, null], [8010, 8385, null], [8385, 8900, null], [8900, 9452, null], [9452, 10070, null], [10070, 10846, null], [10846, 11069, null], [11069, 12074, null], [12074, 12449, null], [12449, 12798, null], [12798, 12862, null], [12862, 13306, null], [13306, 13692, null], [13692, 14144, null], [14144, 14738, null], [14738, 15096, null], [15096, 15759, null], [15759, 17279, null], [17279, 18596, null], [18596, 18967, null], [18967, 19403, null], [19403, 20347, null], [20347, 20690, null], [20690, 22714, null], [22714, 22880, null], [22880, 23333, null], [23333, 23883, null], [23883, 24201, null], [24201, 24961, null], [24961, 25223, null], [25223, 25537, null]], "google_gemma-3-12b-it_is_public_document": [[0, 110, true], [110, 505, null], [505, 984, null], [984, 1526, null], [1526, 1997, null], [1997, 2372, null], [2372, 3019, null], [3019, 3407, null], [3407, 3918, null], [3918, 4063, null], [4063, 4400, null], [4400, 4765, null], [4765, 5309, null], [5309, 5737, null], [5737, 5927, null], [5927, 6523, null], [6523, 7169, null], [7169, 7697, null], [7697, 8010, null], [8010, 8385, null], [8385, 8900, null], [8900, 9452, null], [9452, 10070, null], [10070, 10846, null], [10846, 11069, null], [11069, 12074, null], [12074, 12449, null], [12449, 12798, null], [12798, 12862, null], [12862, 13306, null], [13306, 13692, null], [13692, 14144, null], [14144, 14738, null], [14738, 15096, null], [15096, 15759, null], [15759, 17279, null], [17279, 18596, null], [18596, 18967, null], [18967, 19403, null], [19403, 20347, null], [20347, 20690, null], [20690, 22714, null], [22714, 22880, null], [22880, 23333, null], [23333, 23883, null], [23883, 24201, null], [24201, 24961, null], [24961, 25223, null], [25223, 25537, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 25537, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 25537, null]], "pdf_page_numbers": [[0, 110, 1], [110, 505, 2], [505, 984, 3], [984, 1526, 4], [1526, 1997, 5], [1997, 2372, 6], [2372, 3019, 7], [3019, 3407, 8], [3407, 3918, 9], [3918, 4063, 10], [4063, 4400, 11], [4400, 4765, 12], [4765, 5309, 13], [5309, 5737, 14], [5737, 5927, 15], [5927, 6523, 16], [6523, 7169, 17], [7169, 7697, 18], [7697, 8010, 19], [8010, 8385, 20], [8385, 8900, 21], [8900, 9452, 22], [9452, 10070, 23], [10070, 10846, 24], [10846, 11069, 25], [11069, 12074, 26], [12074, 12449, 27], [12449, 12798, 28], [12798, 12862, 29], [12862, 13306, 30], [13306, 13692, 31], [13692, 14144, 32], [14144, 14738, 33], [14738, 15096, 34], [15096, 15759, 35], [15759, 17279, 36], [17279, 18596, 37], [18596, 18967, 38], [18967, 19403, 39], [19403, 20347, 40], [20347, 20690, 41], [20690, 22714, 42], [22714, 22880, 43], [22880, 23333, 44], [23333, 23883, 45], [23883, 24201, 46], [24201, 24961, 47], [24961, 25223, 48], [25223, 25537, 49]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 25537, 0.16324]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
f1ca256d561548b78c43339fafbbb28affc05db3
|
Pilot implementation
Hertzum, Morten; Bansler, Jørgen P.; Havn, Erling C.; Simonsen, Jesper
Published in:
Communications of the Association for Information Systems
Publication date:
2012
Document Version
Peer reviewed version
Citation for published version (APA):
Pilot Implementation: Learning from Field Tests in IS Development
Morten Hertzum¹, Jørgen P. Bansler², Erling C. Havn³, and Jesper Simonsen⁴
¹ Roskilde University, Roskilde, Denmark, mhz@ruc.dk
² University of Copenhagen, Copenhagen, Denmark, bansler@diku.dk
³ Technical University of Denmark, Lyngby, Denmark, havn@man.dtu.dk
⁴ Roskilde University, Roskilde, Denmark, simonsen@ruc.dk
Abstract. A recurrent problem in information-systems development (ISD) is that many design shortcomings are not detected during development, but first after the system has been delivered and implemented in its intended environment. Pilot implementations appear to promise a way to extend prototyping from the laboratory to the field, thereby allowing users to experience a system design under realistic conditions and developers to get feedback from realistic use while the design is still malleable. We characterize pilot implementation, contrast it with prototyping, propose a five-element model of pilot implementation, and provide three empirical illustrations of our model. We conclude that pilot implementation has much merit as an ISD technique when system performance is contingent on context. But we also warn developers that, despite their seductive conceptual simplicity, pilot implementations can be difficult to plan and conduct. It is sometimes assumed that pilot implementations are less complicated and risky than ordinary implementations. Pilot implementations are, however, neither prototyping nor small-scale versions of full-scale implementations; they are fundamentally different and have their own challenges, which will be enumerated and discussed in this article.
Keywords: pilot implementation, pilot system, information-systems development, prototyping, socio-technical change
I. INTRODUCTION
It has long been acknowledged that information-systems development (ISD) is a learning process that requires an iterative, incremental approach with feedback loops between successive development stages, such as requirements definition, systems design, coding, test, implementation, and operation [Boehm, 1988; Brooks, 1987; Floyd, 1984; Larman and Basili, 2003]. This insight goes back at least to the 1970s and 1980s when the ideas and concepts behind iterative, incremental, and evolutionary development were first introduced and discussed widely [Larman and Basili, 2003]. In recent years, interest in these ideas has been revived with the rise in popularity of agile methods [Abrahamsson et al., 2003; Williams and Cockburn, 2003]. Even though iterative development approaches have become widely accepted and used, it has proven difficult to obtain sufficiently realistic feedback about system use. For instance, while various prototyping techniques may provide feedback from simulated use in a laboratory environment, they do not provide insight into real user experiences with the system in action [Davis, 1995]. This is problematic, because many flaws in the design of a system and its organizational implementation do not surface until the system is in real use. Furthermore, as Boehm [2000, p. 99] has pointed out, “users may initially feel that they ‘know it’ when they see an initial demo or prototype. But their needs and desires change once they begin operating the system and gain a deeper understanding of how it could support their mission”.
In this paper, we focus on systematic field tests, called pilot implementations, to create a feedback loop from implementation to development in ISD projects with high organizational complexity, innovation
needs, or cost of failure. We define a pilot implementation as a field test of a properly engineered, yet unfinished system in its intended environment, using real data, and aiming through real-use experience to explore the value of the system, improve or assess its design, and reduce implementation risk. Correspondingly, we term the properly engineered, yet unfinished system a pilot system. By subjecting a pilot system to real-use conditions before the system design is finalized a pilot implementation provides developers with feedback on how users actually experience working with the system. Pilot systems have much in common with prototypes, and proponents of a broad definition of prototypes may see pilot systems as a subclass of prototypes [e.g., Floyd, 1984]. We prefer to distinguish pilot systems from prototypes to emphasize that pilot systems are properly engineered and evaluated in their intended environment with real data [Rzevski, 1984]. At the same time, pilot systems are not finalized and are therefore restricted to limited implementation. Pilot implementation is a technique for use in ISD projects; it is neither a full ISD model nor an approach to full-scale implementation.
Pilot implementations are compatible with both plan-driven and evolutionary ISD approaches. In plan-driven approaches [Boehm, 2002; Boehm and Turner, 2004], a pilot implementation near the transition from development to implementation may provide reassurance that current development activities simply need to be finalized or it may show that revision of previous development activities is necessary. In evolutionary approaches [Basili and Turner, 1975; Floyd, 1984; McCracken and Jackson, 1982], which break a project into a series of successively completed subprojects or ‘increments’, experience from use is implicit in each increment and provides feedback important to the planning and content of subsequent increments. While an evolutionary approach reduces the risk of completing development without receiving real-use feedback [Alter, 2001; Boehm, 1988], we contend that an improved understanding of pilot implementations will also benefit evolutionary approaches because it provides a more explicit analysis of the challenges involved in learning from real-use experiences.
Unlike prototyping, pilot implementation is still an under-researched concept. Although many ISD projects have used pilot implementations to evaluate a proposed system’s capabilities and limitations [Lin and Pervan, 2003; Ward et al., 1996], little has been published about what pilot implementations are, why they are considered useful, and how they should be conducted. The purpose of this paper is to discuss the characteristics of pilot implementations in a systems-development context that involves new product development, as opposed to the configuration and implementation of off-the-shelf, so-called COTS, systems. We consider whether and how pilot implementations can extend prototyping from the laboratory to the field. In addition, we will discuss the key issues and challenges associated with conducting pilot implementations in practice. In doing so, we will draw on the existing, but rather sparse, literature on pilot implementation as well as our own experiences from three studies of pilot implementation in the Danish healthcare sector.
The article is structured as follows. First, we cover related work on pilot implementation. Second, we analyze the characteristics of pilot implementation, compare and contrast them with prototyping, and provide a model of the elements that constitute pilot implementations. Third, we elaborate the different elements of pilot implementation with three empirical illustrations. Fourth, we discuss challenges in planning and conducting pilot implementations and identify implications for research and practice.
II. RELATED WORK
Pilot implementation may be a valuable ISD technique if and when real-use feedback is important to the successful completion of development activities and difficult to obtain in other ways. Below, we briefly address the inadequacy of real-use feedback in widespread ISD approaches and then account for related work on the use of pilot implementation to avoid such inadequacy.
Inadequate real-use feedback
Markus [2004] argues that the risk that people will not adopt and use information systems and associated work practices has not been adequately addressed by the research on how to manage ISD projects. Along similar lines, Ward and Daniel [2006] propose an increased focus on real use by incorporating data about the benefits obtained from system use in their project model. They argue that such data are often absent, yet valuable. Thus, it appears that many ISD projects are completed on the basis of limited knowledge about real use of the resulting system. Feedback from real-use experiences is, however, important for several reasons. First, developers and users need a deeper understanding of how the system may support the users’ work and what they require from the system [Boehm, 2000; Rzevski, 1984]. Second, real-use experiences are necessary in order for organizational consequences
and opportunities of the system to emerge, especially in complex organizational settings where systems affect multiple interrelated stakeholder groups [Bossen, 2007; Orlikowski, 1996]. Third, real-use feedback makes it possible to gauge the extent to which envisioned benefits are obtained and potentially make project completion and success dependent on this [Ward and Daniel, 2006].
In his discussion of life-cycle models Alter [2001] divides the ISD life cycle into four phases: initiation, development, implementation, and operation. By mapping various ISD models to these four phases, Alter identifies limited coverage of post-development issues in several of the models, for example the waterfall model [Boehm, 1981]. For the life-cycle model that represents “a typical project that might confront a software development manager” Alter concludes that “this model ends before implementation in the organization begins” [Alter, 2001, p. 27]. This suggests that development activities are informed by little or no real-use feedback.
Agile approaches such as Crystal [Cockburn, 2007], Dynamic Systems Development Method [Stapleton, 1997], and Scrum [Schwaber and Beedle, 2002] emphasize customer collaboration over contract negotiation, responding to change over following a plan, and other similar values. However, agile methods offer little guidance on how to conduct activities that give users a basis for providing feedback [Abrahamsson et al., 2003]. Thus, while agile methods advocate evolutionary development, they appear to lack concrete means of obtaining systematic feedback from the implementation of one release to the development of subsequent releases. A risk of inadequate real-use feedback is therefore also present in agile methods.
Pilot implementation
For our purposes it is important to distinguish between two related, but different, kinds of pilot implementation represented below by Rzevski [1984] and Janson [1986]. Rzevski discusses pilot implementation in relation to ongoing development activities and is an important inspiration for our definition of pilot implementation. Conversely, Janson describes pilot implementation as a post-development activity, which concerns the selection and implementation of standard (i.e., off-the-shelf) systems. This focus on standard systems discords with our focus because it does not involve feedback to development.
Rzevski [1984, p. 362] defines pilot systems by distinguishing them from prototypes: “In contrast to prototypes, pilot systems are computer-based systems properly designed and engineered, and therefore reliable and robust, offering only a small subset of facilities of the system under development. Pilot systems are designed to be gradually extended into full operational systems. Their projected useful life is much longer than that of prototypes.” Like pilot plants in chemical engineering, pilot systems are built to provide opportunities for experimentation and evaluation in a real-world setting while the system is still under development. The purpose of implementing pilot systems— that is, of pilot implementation—is “for both developers and clients to learn from each other and about each other and to incorporate all this knowledge into further parts of the main system” [Rzevski, 1984, p. 362]. That is, pilot implementations are not confined to the development phase but reach into implementation activities to feed real-use experiences back into the ongoing development activities.
Janson [1986] discusses pilot implementation in relation to standard systems and defines its main objective as “allow[ing] the user to verify that a standard software package meets the organization’s information needs, with at most only minor changes” (p. 210). Here, pilot implementation is confined to the implementation phase with its focus on organizational issues. Janson’s supplementary objectives of pilot implementation emphasize this focus by comprising observation of organizational reactions to the pilot system, detection of possible resistance to the system, provision of better training, and formulation of better implementation strategies. Janson defines a pilot system as a scaled-down version that offers a subset of the capabilities present in the full system without sacrificing robustness, completeness, and reliability. These characteristics “make it possible to install the pilot system in its intended environment and enable the user to test the proposed application package using normal data, under regular operating conditions, and at greatly reduced cost” [Janson, 1986, p. 210]. An important aspect of such pilot implementation is that “the pilot system functions under the user’s control” [Janson and Hammerschmidt, 1990, p. 48]. This is seen as contrary to prototypes, where the designer retains control of the situation.
It is notable that neither Rzevski [1984] nor Janson [1986] provide detail about how to conduct pilot implementations. Research on pilot implementation reports a scarcity of such considerations [e.g., Glass, 1997; Pal et al., 2008; Turner, 2005], and we are unaware of research that provides such details for pilot implementations performed while development is still ongoing. For post-development pilot
implementation, Glass [1997] proposes a detailed set of steps intended “to produce sufficient information to allow a decision to be made about the implementation and use of the pilot concept” (p. 87). With this definition pilot implementations, which Glass terms pilot studies, are decoupled from development and involve only a customer organization that considers adopting a system. The post-development focus is also reflected in the proposed set of pilot-study steps, which comprises five main steps: planning (6 sub steps), design (12 sub steps), conduct (4 sub steps), evaluation (10 sub steps), and use (3 sub steps). For example, the design step is entirely about preparing the organization for using the system and about devising ways of obtaining data about its use. None of the 35 sub steps are about fitting the system to the organization or about feeding insights from the pilot implementation back to development. The set of steps was used for retrospectively evaluating more than 20 pilot implementations conducted by a government agency. This empirical evaluation shows the steps to be perhaps too rigorous [Glass, 1997]. Other models for post-development pilot implementation of information systems contain fewer steps but are similar in spirit [e.g., Pal et al., 2008].
Turner [2005, p. 2] talks about pilot studies, which he defines as “part of a larger project or programme, undertaken to improve understanding of the main change or innovation being delivered by the project or programme, thereby reducing the risk and uncertainty associated with the change”. This definition emphasizes two points that appear important to pilot implementations that feed back into ongoing development activities. First, the definition makes the reduction of risk and uncertainty central to pilot implementation. Second, the definition emphasizes that a pilot implementation is conducted in the context of a larger activity. For pilot implementations that feed experiences back into ongoing development activities, this larger activity is the ISD project.
The use of pilot implementations to assess the viability of new technologies prior to full-scale implementation appears to be a common practice [e.g., Babar et al., 2006; Iredale et al., 2002; Liang et al., 2006; Pal et al., 2008; Reed et al., 2004]. Surveys of large Australian and UK organizations report that 81% and 87%, respectively, of respondents conduct pilot implementations when implementing information systems [Lin and Pervan, 2003; Ward et al., 1996]. Just as there is little prescriptive work about how to conduct pilot implementations, especially while development is still ongoing, there is little descriptive work of what pilot implementations look like in practice – focus is instead on the outcome of the pilot implementations. When pilot-implementation methodology is discussed in the literature it is often to acknowledge certain limitations. For example, Reed et al. [2004] acknowledge the limited duration of the pilot implementation as a limitation of their work because it did not allow the novelty of the system to wear off, Liang et al. [2006] acknowledge that the absence of an appropriate baseline against which to compare pilot-implementation results makes the results indirect, and Babar et al. [2006] discuss threats to the representativeness of their pilot-implementation participants.
III. PILOT IMPLEMENTATION AS AN ISD ACTIVITY
We focus on the use of pilot systems while development is still ongoing. Such pilot-system implementation or, for short, pilot implementation is summarized in Table 1 by contrasting it with prototyping.
Characteristics of pilot implementation
Pilot implementations can be performed in manifold ways but involve trying out a system on a restricted scale before finalizing the design of the system. Four characteristics of pilot implementation warrant further clarification: First, pilot systems are by definition not fully developed. In contrast to prototypes, pilot systems have considerable functionality and are sufficiently robust, reliable, and efficient to enable their implementation and use in a real work environment [Rzevski, 1984]. In contrast to releases of system versions, pilot systems are not finalized and must therefore be expected to lack some functionality and to malfunction and break down occasionally. Thus, a pilot system is only suited for limited implementation because it requires special precautions.
Second, a pilot implementation is limited in scope and time. One or a few sites are selected for the pilot implementation, and the experiences gained at these sites inform the subsequent development and implementation activities. Ideally, a pilot implementation should be long enough for learning curves to flatten, new work procedures to stabilize, and the effects of the use of the pilot system to materialize. Jurison [1996] finds that effects at the level of individual users can be observed within 6-8 months whereas effects at the organizational level may take a year to materialize. Concomitantly, a pilot
implementation must be short enough to fit within an ISD project. This tension may necessitate brief pilot implementations in some situations.
Third, a pilot implementation is conducted in the intended use environment using real data but it is part of an ISD project. As the pilot system is not yet fully developed and it is only used at some sites, the use of the pilot system may entail certain restrictions, for example in interactions with sites that are not part of the pilot implementation. Such restrictions may be handled through careful explanation of the purpose of the pilot implementation or through temporary interventions such as simulations. The timing of pilot implementations involves balancing the size and nature of the restrictions imposed on the pilot implementation against the desire for early feedback from real use of the system. By defining pilot implementations as a technique for use in ISD projects, this feedback is to inform development as well as implementation.
Fourth, pilot implementations are conducted to learn about the fit between the system and its use environment and thereby to explore the value of the system, improve or assess the system design, and reduce implementation risk. Importantly, the purpose is to support the ISD project. That is, if the pilot system succeeds in supporting users in accomplishing their work, this is primarily valuable as feedback to the project about the quality of the system and only secondarily because it improved real work during the pilot implementation. More specifically, the purpose of a pilot implementation can be any of the following:
- To evaluate the usefulness and usability of a system in order to inform a decision about whether to continue the development of the system
- To improve the system design based on user feedback, experience from practical use, and performance measures such as productivity or quality data
- To identify necessary or desirable changes in the work organization and processes in which the system will be embedded
- To become aware of unanticipated change that emerges from using the pilot system and may call for preventive action to avoid unwanted change or supportive action to sustain desired change
- To provide input for formulating implementation strategies and plans, on the basis of users’ reactions to the pilot system.
The major purpose, then, of a pilot implementation is to learn about how the system performs in a real environment and how users appropriate and use the system. Pilot implementations provide a means for developers and users to explore the affordances of the system and experiment with its integration into and transformation of existing practice. Experiences from these activities are fed into the finalization of the technical development of the system and into preparing full-scale organizational implementation.
**Pilot implementation versus prototyping**
The purpose of prototyping is, partly, to traverse a design space and thereby create knowledge about the final design and, partly, to manifest design ideas in concrete artefacts [Budde et al., 1992; Lim et al., 2008]. This purpose resembles that of pilot implementation but contrary to pilot implementation prototyping does not normally involve experience with the prototype in real use. For example, Beynon-Davies et al. [1999, p. 108] note that “the use of the word prototype tends to suggest the tentative nature of this artefact. It is early, unfinished or a model of something”. In the early stages of the development phase, prototypes may support the communication between designers and users by visualizing alternative system solutions and thereby facilitating discussion of initial ideas and the clarification of requirements. In the later stages of the development phase, users may try out a prototype to evaluate the proposed functionality and identify shortcomings in the design. However, the tentative nature of prototypes entails that they can mostly be explored and tried out in an environment separated from real use, for example in a usability laboratory. There are, thus, limitations to the kinds of learning that can be achieved by experimenting with a prototype prior to real use.
In contrast, pilot implementation involves that a system is installed and used in its intended environment, though for a limited period only. The resulting feedback can provide crucial guidance during subsequent development activities because the use of the system in its intended environment allows for emergent changes to surface and become recognized as drawbacks or opportunities, for users and developers to advance their understanding of the optimal fit between system and organization, and for gauging the preparedness of the organization to assimilate the system. Collectively, these properties of pilot implementation enforce realism. This realism constitutes the primary difference between pilot implementation and prototyping. In this sense pilot implementation can be seen as a supplement to prototyping. Both techniques have an overarching learning objective,
but pilot implementation focuses on learning from real work settings with their organizational context and mundane practicalities, which cannot be recreated in a laboratory. As a result the complications involved in performing pilot implementations differ from those of prototyping. For example, pilot implementation involves organizational adaptations (see below), which are not relevant to prototyping.
The elements of pilot implementation
To describe pilot implementations in more detail we have developed a model of their constituent elements. Figure 1 shows the five interrelated activities that comprise our model of a pilot implementation: planning and design, technical configuration, organizational adaptation, use, and learning. The first four activities are the standard ISD phases of initiation, development, implementation, and operation [Alter, 2001] adapted to the pilot-implementation context; the fifth activity – learning – is the objective that motivates performing the four other activities. Some temporal progression occurs from planning and design through technical configuration and organizational adaptation to use, but these activities do not form a linear sequence. For example, technical configuration and organizational adaptation can to a large extent be performed in parallel, and the pilot system may be modified during the period of its use. Learning goes on in parallel with the four other activities.
During *planning and design*, it is defined what issues the pilot implementation addresses and how they will be studied. This includes determining where and when the pilot implementation will take place, what facilities the pilot system will include, and how lessons learned during the pilot implementation will be collected. This activity corresponds to the planning and design steps in Glass’ [1997] model of pilot implementation. During *technical configuration*, the parts of the system necessary for the pilot implementation are configured to fit the pilot site, data are migrated to the system, and interfaces to the users’ other systems are developed or simulations are set up. This activity involves the technical adjustments necessary to run the pilot implementation; that is, it builds on rather than subsumes the development activities of the full ISD project. During *organizational adaptation*, the pilot site revises work procedures to align with the system, trains users in the system and the revised procedures, and possibly assigns extra staff to duplicate work according to normal procedures or maintain other safeguards against breakdown. As for technical configuration, organizational adaptation is directed toward the pilot site and builds on the implementation activities of the full ISD project. While technical configuration and organizational adaptation are absent in Glass’ [1997] model of pilot implementation, they resemble main steps in, for example, Wulf and Rohde’s [1995] process of integrated organization and technology development. During *use*, the system is applied at the pilot site, and information is collected about the issues addressed by the pilot implementation. This involves striking a balance between making the system just another part of normal procedures and, at the same time, maintaining a special focus on the system as an object under evaluation. While some evaluation information can be collected automatically and unobtrusively, for example data about system response times, other information must be obtained from users, including information about any unanticipated consequences of introducing the system and associated organizational changes. Finally, the four above-mentioned activities spawns opportunities for *learning*. More specifically, this includes opportunities for learning about a system and its use when it is employed (a) over a period of time, (b) for a realistic span of tasks, (c) to be handled by users with realistically diverse backgrounds and workloads, (d) in collaboration with the multiple, interrelated organizational units involved in the use of the system, and (e) in a technological environment with realistic hardware, network bandwidth, and data load.
Pilot implementations can be seen as opportunities for learning from failure [Scott and Vessey, 2000] in settings devised to limit the consequences of failure. Surveys of why pilot implementations are conducted show a consistent focus on learning but no preference for learning from failure. Ward et al. [1996] find that among the surveyed UK organizations pilot implementations are mainly conducted to evaluate technologies prior to full deployment, to understand better what benefits might be attained, and to learn how benefits might actually be realized. These aims were stated by 48%, 38%, and 40%, respectively, of the organizations that conducted pilot implementations. In a survey of Australian organizations, the same aims were stated by 71%, 53%, and 52%, respectively, of the organizations conducting pilot implementations [Lin and Pervan, 2003]. Learning from pilot implementations is complicated by differences in the involved people’s background and interests. Gallivan and Keil [2003] show that the communication between users and developers in situations such as pilot implementations is fragile and may miss crucial opportunities for learning. Moreover, some users may withhold their opinion about a system or even try to derail pilot implementations by means of counter-implementation strategies [Keen, 1981]. Others may be overly positive, for example because they welcome a change or do not use the pilot system enough to encounter its limitations.
IV. THREE EMPIRICAL ILLUSTRATIONS
To exemplify the complications of pilot implementations we provide three empirical illustrations. The illustrations concern pilot implementations of information systems in different parts of the healthcare sector, ranging from general practitioners over municipal healthcare centres to hospital wards. We chose pilot implementations in healthcare because electronic health records are currently being developed and implemented at considerable cost in hospitals across Europe and North America [Haux et al., 2004]; because the healthcare sector is an organizationally complex domain [LeRouge et al., 2007]; because many efforts to introduce electronic health records encounter adoption barriers [Sobol et al., 1999]; and because pilot implementations are, therefore, highly relevant in this context. For reasons of brevity each of the illustrations focuses on a subset of the five pilot-implementation elements. While all three illustrations address the planning-and-design element, the first illustration targets learning and use, the second technical configuration, and the third organizational adaptation. Table 2 provides a summary of the empirical illustrations; more information, including detailed information about the methodology used in data collection and analysis, can be found in the references provided for each of the empirical illustrations.
Electronic patient record for a stroke unit
As part of the activities involved in the project tender and bid for a strategically important contract concerning the development of an electronic patient record (EPR), the clinical-process module of the EPR was developed and pilot implemented at the stroke unit of a hospital. The pilot implementation, which we investigated by means of an action-research study [Hertzum and Simonsen, 2008; Simonsen and Hertzum, 2010], lasted five months and culminated in a five-day period of use. The EPR replaced all paper records in the stroke unit and was available on all its computers. To simulate a fully integrated EPR, a ‘back office’ was established and staffed around the clock. Record entries that involved paper transactions with other hospital wards were simulated by having the back office continuously monitor the EPR, identify such entries, mail them in the conventional fashion, wait for the results, and immediately type them into the EPR. Thus, the clinicians at the stroke unit experienced the EPR as if all transactions were fully IT supported. To learn about performance, data for 300,000 patients were migrated to the EPR before its use.
The pilot implementation was conducted to learn about planned changes, which were measured as differences between the prior use of paper records and the pilot use of the EPR. Baseline measurements of the use of paper records were performed a month before the pilot use of the EPR; similar measurements were performed during pilot use. To safeguard against misunderstandings, which might have entailed risk to patient health, the clinicians had around-the-clock access to support staff who knew the EPR well. The EPR had positive effects on team conferences, nursing handovers, and medical ward rounds. Most prominently, mental workload, measured by the NASA task load index [Hart and Staveland, 1988], tended to decrease during team conferences and medical ward rounds.
The changes that occurred during pilot use were, however, not restricted to those planned ahead. Some changes emerged spontaneously as a result of the ways in which the clinicians changed their work practices in face of the EPR. For example, the nurses engaged in a process of collective reading at their handovers, during which the EPR screen was projected on the wall and thereby visible to everybody. The electronic records were inspected by the group of nurses and they collectively participated in interpreting the status and condition of the patients, guided by the nurse team leader. The nurse team leader navigated the EPR and read selected passages aloud to draw attention to them and set a shared flow in their reading. This collective reading was a marked change in the nurses’ work practice. During nursing handovers with paper records the nurse team leader provided an oral report of each patient by scanning the patient’s record and reading key information out loud; patient records were seldom seen by clinicians other than the nurse team leader.
This change in the nurses’ work practice was unanticipated but experienced as positive. Along with the achieved planned changes, it exemplifies the learning that may result from trying out a system in real use. The pilot implementation also led to the realization of a need for a pending-tasks facility in the EPR. During the pilot implementation this need became obviously important, and it was fed back to development as a high-priority facility likely to be valuable in multiple systems. In spite of the short use period, this pilot implementation generated important insights into planned as well as emergent qualities of the EPR.
Workspace system for healthcare centres
Municipal healthcare centres were established in Denmark in 2007 with a special focus on chronic and lifestyle diseases such as diabetes, obesity, coronary heart diseases, and certain forms of cancer. As part of the establishment of the centres a healthcare centre workspace system (HCWS) was developed and scheduled for pilot implementation in three healthcare centres in 2008. The pilot implementation, which we investigated through an action-research study [Barlach and Simonsen, 2008], was planned to include a three-month period during which the HCWS was in use at the three healthcare centres. This period of pilot use was, however, postponed several times and finally cancelled.
When the three-month period of pilot use initially started, the healthcare centres reported that the system had severe performance problems. It was not until the vendor staff responsible for the technical configuration of the HCWS visited the healthcare centres that the severity of these problems became clear to them. Contrary to the usability tests that had been run at the vendor, some drop-down menus suffered delays of about 60 seconds. This necessitated renewed work on the technical configuration of the HCWS and renewed planning of the pilot implementation. It took almost three months to diagnose and solve the performance problem. During this time the healthcare centres gradually lost interest in the pilot implementation and focused increasingly on receiving the improvements of their daily work expected to result from full-scale implementation of the HCWS. The reason it took three months to solve the problem was partly that it was hard to diagnose but mainly that the vendor did not treat it as a high-priority issue.
The HCWS had a three-layer architecture consistent with the ANSI/SPARC standard [Brodie and Schmidt, 1982]: a user-interface layer, a functionality layer with the system’s different functional modules (e.g., a booking module), and a data-model layer consisting of a generic clinical framework. The three layers also represented three different vendor units. The user-interface layer was used by the configurators to build the user interface for the specific customer. The functionality layer served multiple healthcare customers and was maintained by a separate developer group. The data-model layer was maintained by a third developer group and served as a generic development tool potentially for all the vendor’s healthcare customers. This layered architecture and the distributed development organization made the performance problem difficult to handle because it could arise from any of the three layers and from interactions among them. Analysis of the problem and negotiations among the vendor units resulted in a decision to resolve the performance problem in the data-model layer. However, the developer group responsible for the generic clinical framework that constituted the data-model layer assigned higher priority to systems in operation than to a pilot system, and the performance problem was therefore not solved until the next regular release.
This illustrates how the vendor judged the technical configuration of the pilot system as insufficiently important to upset the release plans, which were directed at systems in operation. When the performance problem had been resolved the customer no longer wanted to give priority to the learning objective of the pilot implementation, and the HCWS was instead released for operational use. Two years later the HCWS was in the process of being redeveloped with another clinical framework as its data-model layer.
Electronic pregnancy record
In Denmark, care during pregnancy and childbirth is usually organized as a shared-care arrangement involving the woman’s general practitioner (GP), a midwives’ clinic, and a public hospital. To improve information sharing between the parties and, by implication, improve the continuity of care and the pregnant woman’s participation in her own care, the Danish national e-health portal, sundhed.dk, decided to develop a national electronic Pregnancy Record (ePR) providing web access to pregnancy records wherever and whenever needed. The ePR was supposed to replace an existing paper form – the so-called Pregnancy Record (PR). The PR is commenced at the pregnant woman’s first appointment with her GP, who records her personal details, history, blood pressure and so forth. The record is given to the woman so that she can bring it with her to all subsequent appointments during her pregnancy, including those with the midwife and at the hospital. At each visit, the care provider must record pertinent information concerning diagnostic and treatment decisions in the PR.
After spending more than a year developing the software, conducting technical tests, and testing it for usability on a small number of prospective users, a pilot implementation commenced in October 2005 with the purpose of assessing the usability and usefulness of the application in actual clinical work. The pilot implementation, which we investigated by means of observation and semi-structured interviews [Bansler and Havn, 2010], was planned to last 12 months and involve 10 GPs, one midwives’ clinic,
the department of obstetrics at a public teaching hospital and approximately 100 women. However, in May 2006, after less than seven months, sundhed.dk decided to abort the pilot. The premature ending of the pilot rendered the outcome indeterminate and inconclusive. What had happened?
Despite some teething problems, the organizational adaptation in the general practices and the midwives’ clinic went relatively well. Of course, the ePR had shortcomings, but with practice the users gradually learned to cope with them. At the hospital, however, the implementation failed completely, mainly because the nurses and physicians only used the application sporadically and never became familiar with it. Consequently, they found it difficult to use, and they tended to view it as a nuisance imposed on them by an outside authority. The underlying problem concerned the design of the pilot implementation and the organization of hospital work.
The system developers had deliberately tried to limit the number of pilot users and organize the pilot implementation so that each pilot user would use the system regularly and thus quickly become proficient in using it. For instance, they made sure that all the women participating in the trial were referred to the same few selected midwives (a group of 5 persons) at the midwife’s clinic. However, when it came to the hospital, it proved impossible to organize the pilot implementation so that it would only involve a few physicians and nurses. The organization of hospital work with its demand for continuous around-the-clock operation, rotating shift-work schedules, and many unanticipated events made it impossible to limit participation to a small group of users. For obvious reasons, one could not plan in advance when the participating pregnant women would give birth (or need medical care), and therefore all the physicians and nurses at the obstetrics ward had to be able to access and use the ePR. In other words, all 100+ physicians and nurses had to take part in the pilot implementation.
The project manager recognized that this was a potential problem, but she realized that the only way of solving it would be to increase the number of pregnant women enrolled in the pilot implementation and thereby increase the chances of coming across a woman with an ePR. Given that the hospital manages more than 3500 births per year, the number of women participating in the trial would have had to be increased dramatically (maybe to 1000+ women) to make a real difference. This, in turn, would have required the involvement of far more midwives and GPs (at least 100 more). It would have been exceedingly costly and the project would have begun to look more like a full-scale implementation than a pilot implementation. So, she decided to go ahead as planned and hope the best.
While the ePR aimed to support the multiple organizational interdependencies in care during pregnancy, these same interdependencies made it hard to set an appropriate boundary for the pilot implementation. The failure of the organizational adaptation at the hospital diminished the value of the ePR also to the participating midwives and GPs, because the records were incomplete. As a consequence, the usability and usefulness of the ePR could not be evaluated.
Taken together, the three empirical illustrations show some of the complexities involved in conducting a pilot implementation as part of an ISD project, complexities that stem from the fact that a pilot system – unlike a prototype – must be installed in a real setting and used by real users as part of their everyday work. This implies that the pilot implementation becomes subjected to all the vagaries and complications of organizational life as well as the imperfections and peculiarities of real-life technical systems and infrastructures. Only one of the pilot implementations was successful, the two others failed in the sense that very little could be learned from them, because the pilot system never became integrated into the daily work routine and users never became familiar with its workings. While we consider two of the pilot implementations as failed, it should be noted that we are not assessing whether the overarching ISD projects succeeded or failed. The main cause for the failure of the pilot implementation in the healthcare-centre case was rooted in difficulties with the technical configuration of the pilot system, resulting in severe performance problems. In the pregnancy case, the main cause was related to the organizational adaptation, and more specifically to the around-the-clock organization of hospital work and the associated problems of “sporadic use.” In contrast, meticulous planning and thorough technical and organizational preparations before the actual test period (it took five months to prepare for five days of use) as well as extensive user support and data collection during the test itself characterized the successful stroke case. This approach was time consuming and required a great deal of coordination, follow up, and hard work, but at the same time emphasizes the need for careful attention to all five elements of the pilot-implementation model.
V. DISCUSSION
Pilot implementation involves using a system for real work before the system is finalized and, thereby, provides for learning about how the system may eventually support its users in their work. Learning that is based on such real-use experiences goes beyond what users and developers can learn from prototyping in a laboratory. This makes pilot implementation a relevant ISD technique whenever systems are developed for implementation in complex organizational settings, projects aim to be highly innovative, the cost of system failure is high, or the project might be severely hampered by other aspects of inadequate real-use feedback. In these situations the possible benefits of a pilot implementation appear greater than the challenges that must be faced in conducting pilot implementations. Because these challenges may cause a pilot implementation to fail they are important to researchers as well as practitioners:
First, the learning objective may be contested or considered secondary to other objectives. Pilot implementations should be conceptualized as field tests and consequently be designed to maximize learning [Lancaster et al., 2004; Lauesen, 2002; van Teijlingen and Hundley, 2005]. It may, however, be difficult to maintain clarity about the purpose and importance of a pilot implementation in the midst of all the surrounding activities. Because pilot implementations involve that the pilot system is used for real work, the learning objective is added to the objectives that come with performing the real work. In healthcare settings, the top priority is quality treatment of the patients. In other domains, pilot implementations must similarly be expected to be a subordinate concern. The stroke case illustrates how special precautions, such as around-the-clock presence of support staff, may allow for learning without adverse consequences for the real work. Because the users are typically not observed and supervised throughout a pilot implementation, as they are during prototype tests in a laboratory, it becomes crucially important that the users are themselves committed to the pilot implementation and its learning objective. It is, therefore, an essential task for those who conduct pilot implementations to motivate users and maintain their commitment [Hertzum, 2006]. The learning objective of pilot implementations may, however, also be contested within the vendor organization. The healthcare-centre case, for example, illustrates how the learning objective was considered secondary to the scheduled maintenance of the systems already in operation. The vendor did not prioritize that a successful pilot implementation required shorter response times for technical configuration than the maintenance of operational systems. As a consequence, user commitment had degraded when technical configuration had finally been completed. Our experiences show that unless the learning objective is carefully managed throughout a pilot implementation, it is likely to suffer.
Second, it is nontrivial to define an appropriate scope for a pilot implementation. A pilot implementation is, by definition, conducted in a scaled-down fashion so only some users and organizational entities will be involved. For resource reasons, the scope should be as limited as possible, but at the same time one must ensure that the pilot implementation fulfils its purpose and that the involved users constitute a representative sample from the population [Liang et al., 2006; Pal et al., 2008]. Consequently, a pilot implementation aiming to test the effects of computer use on doctor-patient relations during consultations can be more narrowly scoped than a pilot implementation of a system that encompasses a wider range of users, activities, and organizational entities. In the pregnancy case the failure of the pilot implementation at the hospital can be traced back to an inability to define an appropriate scope. The organization and nature of hospital work made it impossible to limit participation to a small group of clinicians. The alternative of enrolling more pregnant women to ensure that all clinicians at the hospital had sufficient opportunity to work with the system was exceedingly costly because it required involving many more midwives and GPs. The use of a back office in the stroke case to simulate a fully integrated system by means of behind-the-scenes manual work illustrates one way of defining a limited scope for a pilot implementation while at the same time handling the various interactions across the boundary between the pilot implementation and the rest of the hospital. The extent of such organizational adaptations also suggests the amount of planning and resources that may be involved in scoping a pilot implementation.
Third, a pilot implementation is, by definition, temporary and it is important to decide how long it should last. On the one hand, it is desirable to keep the pilot implementation as short as possible because the pilot implementation is itself costly and because “full-scale implementation awaits completion of [the] pilot” [Pal et al., 2008, p. 261] and finalization of the system design. Thus, extra time allocated to the pilot will delay the overall ISD project and result in lost-opportunity costs. On the other hand, organizations normally experience a dip in performance immediately after the introduction of a system because start-up problems have to be overcome, users need to become proficient in using the system, and new work practices have to stabilize. Also, users may feel frustrated and may therefore
be reluctant to adopt the system [Applegate et al., 2009, pp. 313-314]. The pilot implementation should be sufficiently long to overcome this critical period and reach a level of operation that allows for realistic assessment of the system. The five-day period of pilot use in the stroke case was critically brief and dictated by concerns external to the pilot implementation. This left only a very concentrated period for learning to occur. It must also be recognized that the brevity of the pilot implementation contributed substantially to making it feasible to have support staff and a back office available around-the-clock. In the pregnancy case the period of pilot use was longer but much more troubled, and in the healthcare-centre case the period of pilot use never overcame the initial critical period. More work is required to be able to make recommendations about the duration of pilot implementations.
Fourth, pilot implementations are not simply small-scale versions of full implementations. It is sometimes assumed that pilot implementations are less complicated and less risky than normal, full-scale implementations [Pal et al., 2008, p. 264], but the challenges above show that pilot implementations have their own complications. A further complication is that a pilot system is not fully developed; rather, it is being pilot implemented to get feedback for its finalization. Users are therefore likely to experience some malfunctions and breakdowns [Bossen, 2007; Peute and Jaspers, 2007], leading also to increased demands on project management and support staff. The root cause of all these complications is that the purpose of a pilot implementation is not, per se, to implement a system in an organization, thus making a pilot implementation fundamentally different from a full implementation [Glass, 1997]. Instead, a pilot implementation involves that one must plan and design the means by which data and user feedback will be collected, technically configure the system to handle that it is used by only some organizational entities, organizationally adapt these entities to minimize the effects of extraneous factors, and use the system in order to learn about how it matches and affects the organization. This requires, especially during the initial part of the use period, a readiness to respond quickly to emergent needs for user support, system fixes, and organizational adjustments. A pilot implementation constitutes a step between prototyping and actual implementation. Lichter et al. [1994] propose that the transition from prototype to fully implemented system can proceed gradually: “After reaching a certain degree of ‘sophistication,’ the prototype is implemented as a pilot system and enhanced in cycles” and “there ceases to be any strict distinction between the prototype and the application system” (p. 826). In contrast, we argue that pilot implementations have distinct characteristics and challenges that differentiate them from prototyping as well as from normal, full-scale implementation.
VI. CONCLUSION
Pilot implementation is an ISD technique that aims to feed experiences from real use back into development by having users try out a system on a restricted scale before the design of the system is finalized. We have defined a pilot implementation as a field test during which a pilot system is used in its intended environment with real data. Pilot implementations are conducted to learn about how a system may support its users in their work and, thereby, to create information and insight about how to improve the system, adapt the organization, and capture the benefits of introducing the system in the organization. By providing feedback from target-environment use of the system to the ongoing development activities, pilot implementation supplements prototyping, which in most definitions is restricted to the development phase.
As we have pointed out pilot implementations have attracted little research interest and little is, therefore, known about how to conduct and use pilot implementations as vehicles for learning in ISD projects. We suggest that our model of the constituent elements of pilot implementation provides a useful schema for guiding future empirical research on pilot implementation. We will conclude by briefly indicating some urgent research questions:
*Learning* is essential for pilot implementations to succeed in providing useful real-use feedback but is under constant pressure from the need to get the normal work done and a concomitant reluctance to upset production schedules for the sake of a pilot implementation. How is a learning environment created, in which users are motivated to participate, errors are seen as opportunities for organizational learning rather than as grounds for blame and punishment, and data about the effects of using the pilot system are systematically collected and fed back to development?
The *planning and design* of pilot implementations involves defining their boundaries to limit the pilot implementation while at the same time accommodating that the users’ work extends beyond these boundaries, for example through collaboration with organizational entities not involved in the pilot
implementation and through tasks initiated prior to the pilot implementation. How can an appropriate scope and timeframe be defined for a pilot implementation?
*Technical configuration* involves configuring the system for the pilot-implementation site, migrating data to the system, and setting up interfaces to other systems at a time when the system is still unfinished and offers only a subset of its full capabilities. How can this be accomplished through the use of a combination of flexible development tools and simulation techniques?
*Organizational adaptation* involves the establishment of ad hoc organizational arrangements and procedures to integrate the pilot system into the work practices of the organization, while the system is at the same time being configured. How can the interplay between customer and vendor be organized to achieve alignment between the organizational adaptations and the technical configuration?
The use of a pilot system involves extra work and uncertainty for the users, in addition to their normal work, but they must still be able to concentrate on their normal work and perform without increased risk of unacceptable errors. How can compensation, support, and special precautions balance the demands of the users’ normal work against the novelty and unfinishedness of the pilot system?
The questions above call for considerable further research on pilot implementation, including the development of guidelines and methods for practitioners who wish to conduct pilot implementations to supplement the use of prototypes. A specific implication for practice lies in not mistaking pilot implementation for normal implementation. Pilot implementations come with their own challenges and are likely to fail unless these challenges are addressed.
**ACKNOWLEDGEMENTS**
This work was supported, in part, by grants from the Danish Agency for Science, Technology, and Innovation (grant no. 07-024801) and the Danish Council for Strategic Research (grant no. 2106-07-0017). The article is the result of a collaborative effort spanning a period of 18 months. The authors contributed equally to the discussions reflected in the article. All authors contributed to the writing, but the first author wrote the larger part of the article text. Multiple versions of the article have been read and discussed critically by all authors. We gratefully acknowledge Anders Barlach’s leading role in conducting the healthcare-centre case.
**REFERENCES**
Alter, S. (2001) "Which life cycle - Work system, information system, or software?", *Communications of the Association for Information Systems*, (7), pp. 17:01-17:54.
Janson, M., and J. P. Hammerschmidt (1990) "Managing the information systems development process: The case for prototype and pilot systems", Information and Management Sciences, (1)1, pp. 45-62.
<table>
<thead>
<tr>
<th></th>
<th>Prototyping</th>
<th>Pilot implementation</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Purpose ("why?")</strong></td>
<td>To learn about the final design by traversing a design space, manifesting design ideas in concrete artefacts, and testing the fit between a proposed design and the user</td>
<td>To learn about the fit between the system and its context in order to explore the value of the system, improve or assess its design, and reduce implementation risk</td>
</tr>
<tr>
<td><strong>System ("what?")</strong></td>
<td>Prototype, i.e. a model, early design or not yet properly engineered system</td>
<td>Pilot system, i.e. a properly engineered, yet unfinished system</td>
</tr>
<tr>
<td><strong>Setting ("where?")</strong></td>
<td>In the laboratory, i.e. separated from real work</td>
<td>In the field, i.e. during real work but limited to one or a few sites</td>
</tr>
<tr>
<td><strong>Process ("how?")</strong></td>
<td>Demonstrated or tried out in brief sessions simulating real use, with test data and test tasks</td>
<td>Used in its intended environment for a limited period of time, with real data and special precautions against breakdowns</td>
</tr>
<tr>
<td><strong>Time ("when?")</strong></td>
<td>During development when it is feasible to test the system design</td>
<td>During development when it is feasible to test the design and its implementation</td>
</tr>
<tr>
<td><strong>Duration ("how long?")</strong></td>
<td>Short, i.e. typically days or weeks</td>
<td>Long, i.e. typically weeks or months</td>
</tr>
<tr>
<td><strong>Table 2: Summary of the three empirical illustrations</strong></td>
<td></td>
<td></td>
</tr>
<tr>
<td>--------------------------------------------------------</td>
<td></td>
<td></td>
</tr>
<tr>
<td><strong>Electronic patient record for a stroke unit</strong></td>
<td><strong>Workspace system for healthcare centres</strong></td>
<td><strong>Electronic pregnancy record</strong></td>
</tr>
<tr>
<td><strong>Planning and design</strong></td>
<td>Purpose and approach – to learn about planned changes using mainly quantitative methods and emergent changes using qualitative methods. Scope and duration – involved all staff and all patients at one stroke unit for a period of five days of around-the-clock use.</td>
<td>Purpose and approach – to evaluate the clinicians’ perception of using the HCWS and the patients’ perception of the received treatment, by means of questionnaires. Scope and duration – planned to involve all staff and selected patients at three healthcare centres for a period of three months.</td>
</tr>
<tr>
<td><strong>Technical configuration</strong></td>
<td>Main challenges – to design overview displays for selected clinical activities, to interface the EPR to other clinical systems, and to provide access to old patient data. Adopted solutions – overview displays were designed through a series of workshops with clinicians and designers, and considerable resources were spent developing interfaces to and migrating data from existing systems.</td>
<td>Main challenges – to install digital signature software on all computers and ensure correct setup of firewalls, browsers, etc. Experienced problems – early on technical breakdowns were quite common, and the project was unable to react quickly and effectively to solve them.</td>
</tr>
<tr>
<td><strong>Organizational adaptation</strong></td>
<td>Main challenges – to simulate that the EPR was in use across the entire hospital, to safeguard against errors, and to prepare revised work procedures. Adopted solutions – a back office simulated use of the EPR also outside of the stroke unit, support staff was available around the clock, and the staff received training in revised work procedures.</td>
<td>Main challenges – to train and motivate users effectively, to distribute memory cards with private keys to all pilot users at the midwives’ clinic and the obstetrics department. Experienced problems – the project failed to motivate staff at the obstetrics department to participate actively in the pilot, and the around-the-clock organization of hospital work led to “sporadic use”.</td>
</tr>
<tr>
<td><strong>Use</strong></td>
<td>Outcome – the EPR was in pilot use for five intensive days during which it replaced all paper records for all patients at the stroke unit.</td>
<td>Outcome – the pilot was stopped before time, mainly because the implementation failed at the obstetrics department due to organizational factors and lack of commitment from pilot users and management.</td>
</tr>
<tr>
<td><strong>Learning</strong></td>
<td>Outcome – it was documented that the EPR and associated work procedures led to several of the planned changes, additional positive changes unexpectedly emerged, and a long list of small-scale change requests was accumulated.</td>
<td>Outcome – little could be learned about the usability and usefulness of the proposed system design or how well it would fit with the organization, because pilot users never became sufficiently familiar with the pilot system to use it routinely as part of their daily work.</td>
</tr>
</tbody>
</table>
Figure 1: The five elements of a pilot implementation.
Author biographies:
**Morten Hertzum**, Ph.D., is associate professor of Computer Science at Roskilde University. His research includes user-centred design, achieving benefit from IT, and evaluation. Currently, his empirical work concerns IT in healthcare. He has published in, for example, *Information Processing & Management, International Journal of Human-Computer Interaction*, and *Information & Organization*.
**Jørgen P. Bansler** is a professor of Computer Science at University of Copenhagen. His research interests include information systems development, organizational implementation, CSCW and medical informatics. He has published in such journals as *ACM Transactions on Information Systems, Journal of the AIS, Information Technology & People*, and *Computer Supported Cooperative Work*.
**Erling C. Havn** is associate professor at Technical University of Denmark. His research interest includes organization theory, CSCW, medical informatics, organizational implementation of IS. He has published in such journals as *Journal of the AIS, Information Technology & People, Computer Supported Cooperative Work, International Journal in Human Factors in Manufacturing, AI&Society*.
**Jesper Simonsen** is Professor in Design Studies at Roskilde University. His research includes Participatory Design, in specific on offering theories and methods for IT design in an organizational context. Has published such journals as *Communications of the ACM, Scandinavian Journal of Information Systems, Human-Computer Interaction*, and *Computer Supported Cooperative Work*.
|
{"Source-Url": "https://static-curis.ku.dk/portal/files/144597336/PilotImpl_CAIS2012_preprint.pdf", "len_cl100k_base": 12516, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 48536, "total-output-tokens": 16399, "length": "2e13", "weborganizer": {"__label__adult": 0.0006442070007324219, "__label__art_design": 0.00152587890625, "__label__crime_law": 0.0006394386291503906, "__label__education_jobs": 0.037384033203125, "__label__entertainment": 0.0001518726348876953, "__label__fashion_beauty": 0.0004124641418457031, "__label__finance_business": 0.0018415451049804688, "__label__food_dining": 0.0007691383361816406, "__label__games": 0.0011606216430664062, "__label__hardware": 0.0026645660400390625, "__label__health": 0.0128936767578125, "__label__history": 0.0013380050659179688, "__label__home_hobbies": 0.0003228187561035156, "__label__industrial": 0.001094818115234375, "__label__literature": 0.0014162063598632812, "__label__politics": 0.00037741661071777344, "__label__religion": 0.0008692741394042969, "__label__science_tech": 0.44921875, "__label__social_life": 0.0002503395080566406, "__label__software": 0.0234375, "__label__software_dev": 0.459716796875, "__label__sports_fitness": 0.0004279613494873047, "__label__transportation": 0.0010633468627929688, "__label__travel": 0.0004000663757324219}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75207, 0.02979]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75207, 0.55785]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75207, 0.92823]], "google_gemma-3-12b-it_contains_pii": [[0, 475, false], [475, 4050, null], [4050, 9223, null], [9223, 14465, null], [14465, 19535, null], [19535, 24621, null], [24621, 30270, null], [30270, 35327, null], [35327, 40581, null], [40581, 45776, null], [45776, 51374, null], [51374, 56591, null], [56591, 60707, null], [60707, 64264, null], [64264, 67942, null], [67942, 68583, null], [68583, 70199, null], [70199, 73568, null], [73568, 73623, null], [73623, 75207, null]], "google_gemma-3-12b-it_is_public_document": [[0, 475, true], [475, 4050, null], [4050, 9223, null], [9223, 14465, null], [14465, 19535, null], [19535, 24621, null], [24621, 30270, null], [30270, 35327, null], [35327, 40581, null], [40581, 45776, null], [45776, 51374, null], [51374, 56591, null], [56591, 60707, null], [60707, 64264, null], [64264, 67942, null], [67942, 68583, null], [68583, 70199, null], [70199, 73568, null], [73568, 73623, null], [73623, 75207, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75207, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75207, null]], "pdf_page_numbers": [[0, 475, 1], [475, 4050, 2], [4050, 9223, 3], [9223, 14465, 4], [14465, 19535, 5], [19535, 24621, 6], [24621, 30270, 7], [30270, 35327, 8], [35327, 40581, 9], [40581, 45776, 10], [45776, 51374, 11], [51374, 56591, 12], [56591, 60707, 13], [60707, 64264, 14], [64264, 67942, 15], [67942, 68583, 16], [68583, 70199, 17], [70199, 73568, 18], [73568, 73623, 19], [73623, 75207, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75207, 0.08791]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
45a9587363b9115e991abc908b6b73b5a32c9804
|
What are your Programming Language’s Energy-Delay Implications?
Georgiou, Stefanos; Kechagia, Maria; Louridas, Panos; Spinellis, Diomidis
DOI
10.1145/3196398.3196414
Publication date
2018
Document Version
Accepted author manuscript
Published in
15th International Conference on Mining Software Repositories (MSR ‘18)
Citation (APA)
https://doi.org/10.1145/3196398.3196414
Important note
To cite this publication, please use the final published version (if applicable). Please check the document version above.
Copyright
Other than for strictly personal use, it is not permitted to download, forward or distribute the text or part of it, without the consent of the author(s) and/or copyright holder(s), unless the work is under an open content license such as Creative Commons.
Takedown policy
Please contact us and provide details if you believe this document breaches copyrights. We will remove access to the work immediately and investigate your claim.
ABSTRACT
Motivation: Even though many studies examine the energy efficiency of hardware and embedded systems, those that investigate the energy consumption of software applications are still limited, and mostly focused on mobile applications. As modern applications become even more complex and heterogeneous a need arises for methods that can accurately assess their energy consumption.
Goal: Measure the energy consumption and run-time performance of commonly used programming tasks implemented in different programming languages and executed on a variety of platforms to help developers to choose appropriate implementation platforms.
Method: Obtain measurements to calculate the Energy Delay Product, a weighted function that takes into account a task’s energy consumption and run-time performance. We perform our tests by calculating the Energy Delay Product of 25 programming tasks, found in the Rosetta Code Repository, which are implemented in 14 programming languages and run on three different computer platforms, a server, a laptop, and an embedded system.
Results: Compiled programming languages are outperforming the interpreted ones for most, but not for all tasks. C, C#, and JavaScript are on average the best performing compiled, semi-compiled, and interpreted programming languages for the Energy Delay Product, and Rust appears to be well-placed for I/O-intensive operations, such as file handling. We also find that a good behaviour, energy-wise, can be the result of clever optimizations and design choices in seemingly unexpected programming languages.
CCS CONCEPTS
• Hardware → Power estimation and optimization; • Software and its engineering → Software libraries and repositories; Software design tradeoffs;
Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org.
MSR '18, May 28–29, 2018, Gothenburg, Sweden © 2018 Association for Computing Machinery. ACM ISBN 978-1-4503-5716-6/18/05...$15.00 https://doi.org/10.1145/3196398.3196414
1 INTRODUCTION
Nowadays, energy consumption\(^1\) matters more than ever before—given that modern software applications should be able to run on devices with particular characteristics (e.g., regarding their main memory and processor). Although hardware design and utilization is undoubtedly a key factor affecting energy consumption, there is much evidence that software can also significantly influence the energy usage of computer platforms [7, 16, 18].
Today, software practitioners can select from a large pool of programming languages to develop software applications and systems. Each of these programming languages comes with a number of features and characteristics that can affect the energy consumption and run-time performance of programming tasks implemented in such languages. With the advent of cloud computing, data centers, and mobile platforms, the same programming tasks can run on distinct platforms consuming energy in different ways. In this context, there is limited work available that examines the energy and performance implications of particular programming tasks that are written in different languages and run on different platforms.
In this paper, we measure the Energy Delay Product (EDP), a weighted function of the energy consumption and run-time performance product, for a sample of commonly used programming tasks. We do this to identify which programming language implementations (i.e., programming tasks developed in particular programming languages) are more efficient. The usage of a metric like EDP can help us to make suggestions regarding the programming languages that should be used for the development of particular programming tasks, which are dependent on the energy or performance requirements of the software systems and applications the tasks
\(^1\) Although in the physical sense energy cannot be consumed, we will use the terms energy “demands”, “consumption”, and “usage” to refer to the conversion of electrical energy by computers to thermal energy dissipated to the environment. Correspondingly, we will use the term energy “savings”, “efficiency”, and “optimization” to refer to reduced consumption.
belong to. At the same time, the EDP metric can help us to investigate how the type of the execution environment, where particular implementations run on, affects their efficiency.
To achieve our goals, we make use of a large publicly available repository that is used for programming chrestomathy, the Rosetta Code Repository [29]. Conducting an empirical study on this data set, we elicit EDP results from small programming tasks implemented across popular programming languages. In our experiments, we include different programming paradigms, such as procedural, object-oriented, and functional. Our results highlight the EDP implications of a particular programming language’s implementations. We also analyze the collected results to derive conclusions on the behaviour of different computing platforms (i.e., embedded, laptop, and server system) vis-à-vis EDP.
The paper makes the following contributions:
- a customized and extended data set that can be used as a benchmark for similar studies to ours,
- a set of publicly available tools for measuring the EDP of various programming tasks implemented in different programming languages,
- an empirical study on programming language EDP implications, by using different types of programming tasks and software platforms, and
- a programming language-based ranking catalogue, in the form of heat maps, where developers can find which programming language to pick for particular tasks and platforms; when energy or run-time performance are important.
Our results show that C is the most EDP efficient language when it comes to computational-intensive tasks for almost all of our platforms. Go outperforms most implementations for sorting algorithms, Rust seems to make the most EDP efficient file I/O operations, JavaScript performs better for regular expression tasks, and C++ is the most efficient for function composition. On average, C, C#, and JavaScript are the most EDP efficient programming languages, while Swift, Java, and R show the weakest performance among the compiled, semi-compiled (i.e., compiled into intermediate code and executed on virtual machines), and interpreted groups, respectively. Our analysis also shows that the average EDP of the same programming language is significantly different, in statistical terms, between the embedded and the laptop platforms. However, we could not detect a statistically significant difference between the embedded and the server or the laptop and server platforms.
2 METHODS
In this section, we provide details regarding our objectives, research questions, and samples. We also present our automated approach for calculating programs’ EDP, its input parameters, as well as its threats and limitations.
2.1 Research Questions
Previous studies have claimed that compiled programming languages such as C and C++ are the most energy and performance efficient, while semi-compiled and interpreted languages are the least efficient [1, 10, 33]. We attempt to investigate whether the above statement is true by conducting a large scale empirical study on a sample of 25 programming tasks implemented in 14 programming languages. In addition to that, our focus is to introduce an automatic approach that software practitioners can use to calculate the EDP of a selected programming language for a certain task type, e.g., I/O- or CPU-intensive applications, running on specific computer systems. We define our research questions as follows:
RQ1. Which programming languages are the most EDP efficient and inefficient for particular tasks?—Our objective here is to rank the selected programming languages based on the EDP of the implemented programming tasks. By answering this research question, we will guide practitioners on which programming languages they should avoid or consider when developing software applications that require to be EDP efficient for particular tasks.
RQ2. Which types of programming languages are, on average, more EDP efficient and inefficient for each of the selected platforms?—Our goal here is to evaluate the efficiency of different programming languages’ families (i.e., compiled, interpreted, and semi-compiled) based on the average EDP of their implementations, when the latter are running on particular software platforms (i.e., server, laptop, and embedded system). By answering this research question, we will determine which types of programming languages can on average produce better EDP results when running on specific platforms.
RQ3. How much does the EDP of each programming language differ among the selected platforms?—For answering this research question, we plan to examine whether the average EDP of the selected tasks, which are implemented in a particular programming language, differs when these tasks run on different software platforms (i.e., server, laptop, and embedded system). By answering this research question, we will define whether programming tasks implemented in a specific programming language have similar EDP behavior when running on different software platforms.
2.2 Selection of Subject Systems
Data Set. We made use of the Rosetta Code Repository, a publicly available repository for programming chrestomathy. Rosetta Code offers 868 tasks, 204 draft tasks, and has implementations in 675 programming languages [29]. However, not all tasks are developed in all programming languages that we have selected for our experiments. To retrieve the online data set, we used a public Github Repository [3] that contains all the currently developed tasks listed in Rosetta Code’s web-page.
Since there is a large number of programming languages’ implementations available in Rosetta Code, we consulted the Tiobe [38] website to elicit the most popular languages. Tiobe offers a monthly rating index of programming languages’ popularity, by estimating the number of hits for a given search query on the internet. The search query is applied on 25 of the highest ranked search engines (according to Alexa) and it searches for programming language hits across the web that: 1) refer to at least 5,000 hits for the Google search engine, 2) are Turing complete, and 3) have their own Wikipedia page [39]. Taking Tiobe October’s 2017 index rating, we...
We selected the top 14 programming languages. We excluded from our initial list programming languages such as assembly, Scratch, Matlab, and Objective Pascal, that have particular limitations, i.e., they are architectural, visually oriented, proprietary, and os dependent, respectively. On the contrary, we included programming languages such as R, Swift, Go, and Rust, although they were not among the top 14. We have selected R and Swift because they had the next highest popularity in Tiobe. Also, we chose Go and Rust because they had one of the highest rise in ratings in a year and are considered to be promising according to Tiobe [38]. The selected programming language categories (compiled, interpreted, and semi-compiled), along with their names, compilers and interpreters’ versions, and compile-time performance optimization flags are shown in Table 1. We selected the highest possible performance optimization flags, since some languages (e.g., Go) by default apply the highest degree of optimizations. Regarding run-time configurations, we did not use or tune any environmental variables.
After retrieving our data set, we had to filter, crop, and modify it to adapt it to our study’s needs. For instance, consider that most of the categories found in Rosetta Code, such as arithmetic and string manipulation, offer more than one task. However, we had to use a balanced data set of different types of tasks. Therefore, we developed a script that extracts all the tasks that are implemented in at least half of the selected 14 programming languages. We ended up with the 25 tasks shown in Table 2. Table’s 2 first and second columns list the selected categories and the names of the tasks, as they were found in Rosetta Code. The third column explains the tasks and the fourth column provides the inputs that were used for each task; we tried to keep the original inputs as given from the Rosetta Code task Wiki-pages. The fifth column shows the task name abbreviations as they are used in Figure 1, 2a, 2b, and 2c.
**Handling the Data Set.** To properly use the above-mentioned data set, we had to do several amendments. Initially, we had to add each task to a for loop for making the run-time execution of each task to last more than a second—since our power analyzer, i.e., Watts Up Pro [41], has a sampling rate of a second (rate lowest). The for loop’s iterations among the tasks vary between a thousand to two billion of times. It is important to note that some implementations last significantly longer. For instance, the exponentiation-operator for C and R took 4.5 seconds and 109 minutes, respectively, to execute the task two billion of times. In addition, consider that some compilers and interpreters offer aggressive source code optimizations. Then, once they find out that the same function is being repeated multiple of times, they optimize their native code to avoid unnecessary calculations. To handle the above issue and execute the same tasks multiple times, we made the programming tasks’ loop variable dependent to enforce different outcomes each time. We also used volatile variables (whenever a programming language offered such an option), whose value may change between different accesses. Furthermore, some of the tasks developed in a specific language offered more than one implementation. Here, we chose the one that was most similar with the implementations in the other selected programming languages. For example, we added any required scaffolding, such as a main function or libraries that needed to be installed and configured. We also developed from scratch the tasks that were not implemented for all the programming languages of our selection whenever it was possible (e.g., multiple inheritance is not applicable in C#).
To execute all the tasks and collect the results, we developed a number of scripts that are available for public use in our Github Repository [19]. In total, we wrote 2,799 lines of source code in bash, Python, and Java to compile, execute, collect, filter, and plot our results. Moreover, we wrote 1,373 lines of source code to implement the missing tasks for programming languages including C, C#, JavaScript, Perl, PHP, R, Rust, Swift, and VB.NET.
**Experimental Platform.** To perform our experiments, we used a Dell Vostro 470 (with 16 GB RAM) server [12], an HP EliteBook 840 G3 Notebook laptop [25], and two Raspberry Pi 3b model [34], with an Intel i7-3770, an Intel i7-6500U, and a quad-core ARM Cortex-A53 micro-processors, respectively.
From hereafter, we refer to the server, laptop, and one of the rpis as Computer Node (cn) and to the Watts Up Pro as WUP. The cn’s responsibility is to execute the tasks and to retrieve their execution time using time [15]. In addition, we note that we used one of the two rpis (the one is not acting as a cn) to retrieve the energy measurements from wup’s internal memory. We will refer to it as an Energy Monitoring (em) system. Finally, to extract the collected measurements from wup’s internal memory, we used an open source Linux utility-based interface available in GitHub [5].
### 2.3 Research Method
Our calculations are based on EDP, an equation introduced by Horowitz et. al [24] and applied as a weighted function by Cameron et. al [6]. The EDP is defined as follows:
\[ E \times T^w \] (1)
Using the term \( E \), we denote the total energy consumed by a particular task from the start until its finish time. \( T \) is the total execution time of a task. The exponent \( w \) denotes weights, and it can take the following values: 1 for energy efficiency when energy is of major concern; 2 for balanced, when both energy consumption and performance are important; 3 for performance efficiency, when performance is most important. Here, we kept the exponent \( w \) equal to 1 (to compare energy/performance in equal terms) to
As it is suggested by Hindle [23], we tried to shut down background energy) and the processor’s clock speed might scale down (reducing system was using its fans to cool down (thus consuming additional high compared to its idle temperature, it could be possible that the document indexing, and so on, to minimize possible interference to our measurements. Additionally, to ensure our systems’ sta-
table condition (where the energy usage is stable) before starting to retrieve measurements—we defined a waiting period of five to minutes to avoid adding overhead to our results.) As it is suggested by Hindle [23], we tried to shut down background processes found in modern operating systems, such as disk defrag-
mentation, virus scanning, cron jobs, automatic updates, disk and document indexing, and so on, to minimize possible interference to our measurements. Additionally, to ensure our systems’ sta-
ble condition, we used the Linux-monitoring sensors tool, i.e., the 1m_sensors [35] for the server and laptop platforms and vcgencmd [17] for the RPI. We used 1m_sensors and vcgencmd to retrieve the systems’ temperature. If the systems’ temperature was found high compared to its idle temperature, it could be possible that the system was using its fans to cool down (thus consuming additional energy) and the processor’s clock speed might scale down (reducing run-time performance) to avoid overheating. On such occasions, our script stalled the execution of the next task’s implementation until they reach a stable condition.
Upon reaching a stable condition, our script initiated the execu-
tion of the tasks. Before the execution of a task the CN sent an ssh command to the EM device to start retrieving energy measurements from the wup’s internal memory. By the end of the whole use case, the EM has collected and sent the energy measurements to the CN through the scp utility. When the results were received by the CN, a plotting script depicted them in the form of heat maps.
### 2.4 Threats to Validity
**Internal validity.** Internal validity refers to possible issues of our techniques that can lead to false positives and imprecision. Here, we reveal the sources of such problems.
First, we used cabled instead of wireless connection, because the former is more energy efficient. However, the use of different protocols provided by the network connection might cause additional overhead. Also, the laptop we used has irreproducible battery and in case of discharge, the power supply immediately starts charging. This may also introduce additional overhead.
Second, wup offers aggregate sampling and reports a sample per second. This means that the energy consumption of the operations that last less than a second is not reported. Therefore, such cases
<table>
<thead>
<tr>
<th>Categories</th>
<th>Names</th>
<th>Explanation</th>
<th>Input Test</th>
<th>Abbreviations</th>
</tr>
</thead>
<tbody>
<tr>
<td>Arithmetic</td>
<td>numerical-integration</td>
<td>exponentiates integer and float calculate the definite integral by using methods rectangular(left,right,midpoint), trapezium, and Simpson’s for $10^x$ approximations</td>
<td>$f(x) = \int_0^{10^x} x^3 , dx$, $10^x/2$</td>
<td>numer-int.</td>
</tr>
<tr>
<td>Compression</td>
<td>huffman-coding</td>
<td>encodes and decodes a string</td>
<td>“huffman example”</td>
<td>huffman</td>
</tr>
<tr>
<td>Concurrent</td>
<td>concurrent-computing</td>
<td>threads creation and printing shares data between 2 threads</td>
<td>[Enjoy,Rosetta,Code]</td>
<td>conc-comp.</td>
</tr>
<tr>
<td>Data structures</td>
<td>json</td>
<td>concats two integer arrays serializes and loads json in data structure</td>
<td>[1,2,3,4,5],[6,7,8,9,0]</td>
<td>array</td>
</tr>
<tr>
<td>File handling</td>
<td>file-input-output</td>
<td>reads from A and writes to B</td>
<td>10,000 unique binary files</td>
<td>file-io</td>
</tr>
<tr>
<td>Recursion</td>
<td>factorial</td>
<td>factorial of $n$ examples of a total computable function that is not primitive recursive finds if word is palindrome</td>
<td>$(10^n)$, $A(n,n) = A(n-1,1)$, $A(n,m) = A(m-1,1)$</td>
<td>factorial</td>
</tr>
<tr>
<td>Regular</td>
<td>regular-expression</td>
<td>matches a word from a sentence and then replaces a word</td>
<td>“this is a matching string”</td>
<td>regex</td>
</tr>
<tr>
<td>Expression</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Sorting</td>
<td>[selection, insertion, merge, bubble, quick]</td>
<td>sorts an array of 100 random elements</td>
<td>[the same 100 random elements for all cases]</td>
<td>selection, insertion, merge, bubble, quick</td>
</tr>
<tr>
<td>String</td>
<td>url-encoding, url-decoding</td>
<td>encode a string</td>
<td>“<a href="http://foo">http://foo</a> bar/”</td>
<td>url-encode</td>
</tr>
<tr>
<td>Object Oriented</td>
<td>call-an-object-method</td>
<td>calls a method from an object</td>
<td>“http://%3A%2F%2Ffoo+bar%2Fabcd”</td>
<td>obj-method</td>
</tr>
<tr>
<td>Functional</td>
<td>function-composition</td>
<td>pipes a function’s result into another</td>
<td>$\sin(\text{asin}(0.5))$</td>
<td>func-comp.</td>
</tr>
</tbody>
</table>
address RQ1 and RQ3, and we used all three weights (to see how performance affects the average edp) to answer RQ2 in Section 3.
We chose edp among other energy metrics (e.g., Greenup, Speedup, and Powerup [2]) because normalized edp can offer fair comparisons among programming implementations, which run on different execution platforms. Contrary to Abdulsalam’s et al. study [2], we do not evaluate the efficiency of optimizations, where performance and energy is measured separately.
Before collecting our measurements, at the CN’s boot time, we had to ensure a stable condition (where the energy usage is stable) before starting to retrieve measurements—we defined a waiting period of five to minutes to avoid adding overhead to our results.) As it is suggested by Hindle [23], we tried to shut down background processes found in modern operating systems, such as disk defrag-
mentation, virus scanning, cron jobs, automatic updates, disk and document indexing, and so on, to minimize possible interference to our measurements. Additionally, to ensure our systems’ sta-
ble condition, we used the Linux-monitoring sensors tool, i.e., the 1m_sensors [35] for the server and laptop platforms and vcgencmd [17] for the RPI. We used 1m_sensors and vcgencmd to retrieve the systems’ temperature. If the systems’ temperature was found high compared to its idle temperature, it could be possible that the system was using its fans to cool down (thus consuming additional energy) and the processor’s clock speed might scale down (reducing run-time performance) to avoid overheating. On such occasions, our script stalled the execution of the next task’s implementation until they reach a stable condition.
Upon reaching a stable condition, our script initiated the execu-
tion of the tasks. Before the execution of a task the CN sent an ssh command to the EM device to start retrieving energy measurements from the wup’s internal memory. By the end of the whole use case, the EM has collected and sent the energy measurements to the CN through the scp utility. When the results were received by the CN, a plotting script depicted them in the form of heat maps.
### 2.4 Threats to Validity
**Internal validity.** Internal validity refers to possible issues of our techniques that can lead to false positives and imprecision. Here, we reveal the sources of such problems.
First, we used cabled instead of wireless connection, because the former is more energy efficient. However, the use of different protocols provided by the network connection might cause additional overhead. Also, the laptop we used has irreproducible battery and in case of discharge, the power supply immediately starts charging. This may also introduce additional overhead.
Second, wup offers aggregate sampling and reports a sample per second. This means that the energy consumption of the operations that last less than a second is not reported. Therefore, such cases
What Are Your Programming Language’s Energy-Delay Implications? MSR ’18, May 28–29, 2018, Gothenburg, Sweden
are excluded from our final results. Having full control over the os’ workload and background operations is hard, because, at any time, different daemons may operate. This could affect our calculations, too. Lastly, given that there exist several compiler and run-time versions of the programming languages we used, we cannot precisely calculate their impact on EDP.
Third, in Rosetta Code, not all tasks are implemented in all programming languages. For example, the classes and call-an-object-method tasks are not applicable to programming languages such as C, Rust, and Go. We have tried to keep the original snippets of Rosetta Code intact and apply only minor changes when needed, e.g., adding a main function, changing from iterative to recursion, and using structs. Consequently, some of the tasks might not reflect their most efficient and optimal implementations, resulting to higher EDP.
External validity. External validity refers to the extent to which the results of our study can be generalized to other programming implementations. Here, we present the limitations of our study.
According to Sahin et al. empirical studies that use real applications (e.g., mobile ones) show different energy consumption results from studies that use micro benchmarks (i.e., traditional desktop software) [36]. This mostly occurs because desktop or data center software are CPU bound, whereas mobile applications are more interactive. In addition, for mobile devices, screen, radios, and sensors—and not the CPU—consume most of the device’s battery. Admittedly, since our study’s results are based on a benchmark, our findings could be different for real software.
Finally, we have evaluated the EDP of 25 programming implementations written in 14 programming languages, and running on three platforms. Thus, it is currently difficult for us to generalize our arguments for other programming languages and platforms.
3 RESULTS
In this section, we discuss the EDP results for the selected platforms and tasks. We also compare their EDP when the implementations run on different software platforms.
Before plotting the heat maps, we ranked the tasks based on their EDP. For each particular task, we took the lowest EDP value and we used it to normalize the measurements of similar tasks. Some of the resulting values varied a lot among for all the selected platforms. Therefore, we used the base ten logarithm to reduce the influence of extreme values or outliers in the data without removing them from the data set.
Figure 1 illustrates the logarithmic base 10 EDP results for the server platform when performance is more important than energy. The y and x axes show the programming languages and the tasks, respectively. To this end, entries with 0 in Figure 1, correspond to the programming languages that achieved the lowest score of EDP for particular tasks, as 0 = log 1 after normalizing. The green color in the heat map shows higher efficiency, in terms of EDP, while red shows lower efficiency. The programming languages’ scores for each task are sorted from top to bottom and the tasks from left to right, starting from the lowest to the highest average EDP.
Due to space constraints, we only added one of the nine plotted heat maps. The remaining heat maps can be found in our GitHub repository [20].
3.1 RQ1. Which programming languages are the most EDP efficient and inefficient for particular tasks?
To answer this research question, initially, we discuss the results of each platform by grouping them into categories. We identify in which categories, in Table 2, specific programming languages show efficient or inefficient results. Then, we present programming languages’ EDP implications that cannot be grouped into categories. Note that for the tasks classes and call-an-object-method, if a non-object-oriented implementation achieved better results, we excluded it and we picked the next one that had a better EDP result.
Table 3 lists results by giving the task’s name, the most (min) and least (max) EDP efficient programming language implementations for the relevant task, and the corresponding difference. The difference is shown as the number of times a particular implementation is more EDP efficient than the other, in terms of the base ten logarithm EDP value. The difference between the most and least efficient raw values differed significantly, even close to billions of times in some cases. For instance, if the EDP’s raw value difference between the minimum and the maximum is equal to 10,000,000, that would result in a logarithm of 7. We therefore used the base ten logarithm of the following ratio:
\[
\log(p/p_{\text{min}}) \tag{2}
\]
Where \( p \) is the measurement and \( p_{\text{min}} \) is the minimum value of EDP for each task. If \( x = \log(p/p_{\text{min}}) \), the language giving \( p_{\text{min}} \) is \( x \) times more efficient than \( p \)’s implementation in logarithmic terms, that is, \( 10^x \) times more efficient. Finally, we use show in Figure 2 the score of EDP results all programming languages, for each task, using box plots.
3.1.1 Embedded System Results. Grouped into Categories.
The collected results, in Table 3 for the embedded system, show that C and Rust provide better EDP results than Perl, Swift, VB.NET, and R for tasks located under the category of arithmetic, compression, and data structures. C also performs more efficiently for the tasks falling under the concurrency category, by being 4.79 times more efficient than Perl. In terms of file-handling, Rust offers the best efficiency against Swift by 4.27 times. JavaScript is the programming language that achieves 3.88 times better EDP results for the regular expression category, compared to Java. For almost all sorting tasks, Go implementations are 3.98 to 6.52 times more EDP efficient compared to Swift, R, and Ruby. For performing functional tasks, C++ is proven to be 7.96 times more efficient than Swift.
Uncategorized Implications. The most EDP efficient implementations for the tasks falling under the recursion category are provided by the Go, VB.NET, and Swift implementations. More specifically, Go performs 4.77 times more efficiently for ackermann-function than R, VB.NET outperforms R by 3.66 times for palindrome-detection, and Swift outruns PHP by 4.03 times for the factorial task. For the url-encoding and decoding tasks, C and PHP achieve EDP efficiency of 6.36 and 7.38 times more than Java and R, respectively. For the oo tasks, the most efficient implementations vary: 1) C++ outperforms Python 5.62 times for the call-an-object-method task; 2) JavaScript outperforms R 5.1 times for the classes task; 3) Ruby outperforms JavaScript 7.94 times for the inheritance-multiple task; and 4) C++ outperforms JavaScript 3.6 times for the inheritance-single task.
3.1.2 Laptop System Results. Grouped into Categories.
Table 3 shows the results for the laptop platform where C performs 4.1 to 5.81 times more efficiently for the tasks grouped under arithmetic and compression. The file-handling category, which includes I/O operations, performs better in Rust’s implementation, which is 4.44 times more EDP efficient than VB.NET’s. Recursion category implementations (ackermann-function, palindrome-detection, and factorial) prove to be 4.42 to 5.06 times more EDP efficient when using the .NET framework (for C# and VB.NET) in contrast to R. For the regular expression category, JavaScript’s pattern matching and replacing operations performs 4.4 times better than R’s. Likewise, for the tasks classes and call-an-object-method, found under the oo category, JavaScript offers the most EDP efficient implementations by being 6.86 to 7.16 times more efficient than R and Perl, correspondingly. For the remaining tasks under the oo category (multiple and single inheritance), C++ has the best implementations. Also, C++ outperforms Perl for the functional category by being 5.62 times more efficient.
Uncategorized Implications. For the tasks concurrent-computing and synchronous-concurrency, C and C++ achieve the best efficiency against C++ and Java by being 6 and 1.88 times more efficient, respectively. C and PHP outperform Java by being 4.41 and 4.98 times more EDP efficient for the array-concatenation and json tasks, correspondingly. For sorting tasks like insertion and selection, JavaScript outruns R by 4.21 and 3.6 times. In addition, C# shows 4.6 and 5.48 times more EDP efficient results in contrast to R for bubble and quick sorting. Also, Go performs 4.74 times more efficiently for merge sorting compared to Swift. For the tasks of url-decoding and encoding, C++ and PHP perform 4.87 and 5.64 times better than R.
3.1.3 Server System Results. Grouped into Categories.
Table 3 for server system shows, that C is the programming language with the most efficient EDP implementations for the compression, concurrency, and file-handling categories. Regarding the regular expression category, JavaScript offers the best performance by being 4.38 times more efficient than Java. For most of tasks falling under the sorting category, Go performs 4.68 to 5.55 times more efficiently against R and Swift. C++ outperforms JavaScript and Java for oo tasks such as single and multiple inheritance by 1.68 and 3.32 times respectively. In addition, C++ performs 4.48 times better for the functional category compared to Java.
Uncategorized Implications. For the server platform, Go and C achieve the best efficiency for the exponentiation-operator and numerical-integration tasks, respectively. C and VB.NET outperform Java by being 4.35 and 4.46 times more efficient for the data structures category, correspondingly. C#, Perl, and C achieve, 4.46, 5.06, and 5.01 times better results for the recursion category than R. Moreover, C performs more efficiently for url-decoding and PHP for url-encoding against Java and R.
What Are Your Programming Language’s Energy-Delay Implications?
MSR ’18, May 28–29, 2018, Gothenburg, Sweden
### Table 3: All System Tasks EDP
<table>
<thead>
<tr>
<th>Task’s Name</th>
<th>Embedded</th>
<th></th>
<th></th>
<th>Laptop</th>
<th></th>
<th></th>
<th>Server</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>Logarithmic</td>
<td>Implementations</td>
<td>Logarithmic</td>
<td>Implementations</td>
<td>Logarithmic</td>
<td>Implementations</td>
<td>Logarithmic</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Ratio</td>
<td>Min</td>
<td>Max</td>
<td>Ratio</td>
<td>Min</td>
<td>Max</td>
<td>Ratio</td>
</tr>
<tr>
<td>exponentiation-operator</td>
<td>C</td>
<td>R</td>
<td>6.84</td>
<td></td>
<td>C</td>
<td>R</td>
<td>5.81</td>
<td>Go</td>
</tr>
<tr>
<td>numerical-integration</td>
<td>Rust</td>
<td>Perl</td>
<td>5.2</td>
<td></td>
<td>C</td>
<td>vb.net</td>
<td>4.2</td>
<td>C</td>
</tr>
<tr>
<td>huffman-coding</td>
<td>C</td>
<td>C++</td>
<td>4.94</td>
<td></td>
<td>C</td>
<td>vb.net</td>
<td>4.54</td>
<td>C</td>
</tr>
<tr>
<td>lzw-compression</td>
<td>Rust</td>
<td>Swift</td>
<td>9.56</td>
<td></td>
<td>C</td>
<td>Java</td>
<td>4.1</td>
<td>C</td>
</tr>
<tr>
<td>concurrent-computing</td>
<td>C</td>
<td>Perl</td>
<td>4.79</td>
<td></td>
<td>C</td>
<td>C++</td>
<td>6</td>
<td>C</td>
</tr>
<tr>
<td>synchronous-concurrency</td>
<td>C</td>
<td>Perl</td>
<td>0.57</td>
<td></td>
<td>C++</td>
<td>vb.net</td>
<td>1.88</td>
<td>C</td>
</tr>
<tr>
<td>array-concatenation</td>
<td>C</td>
<td>R</td>
<td>4.34</td>
<td></td>
<td>C</td>
<td>Java</td>
<td>4.41</td>
<td>C</td>
</tr>
<tr>
<td>json</td>
<td>Rust</td>
<td>Swift</td>
<td>4.93</td>
<td></td>
<td>PHP</td>
<td>Java</td>
<td>4.4</td>
<td>vb.net</td>
</tr>
<tr>
<td>file-input-output</td>
<td>Rust</td>
<td>Swift</td>
<td>4.27</td>
<td></td>
<td>Rust</td>
<td>vb.net</td>
<td>4.44</td>
<td>C</td>
</tr>
<tr>
<td>factorial</td>
<td>Swift</td>
<td>PHP</td>
<td>4.03</td>
<td></td>
<td>vb.net</td>
<td>R</td>
<td>4.42</td>
<td>C++</td>
</tr>
<tr>
<td>ackermann-function</td>
<td>Go</td>
<td>R</td>
<td>4.77</td>
<td></td>
<td>C++</td>
<td>R</td>
<td>4.88</td>
<td>Perl</td>
</tr>
<tr>
<td>palindrome-detection</td>
<td>vb.net</td>
<td>R</td>
<td>3.66</td>
<td></td>
<td>vb.net</td>
<td>R</td>
<td>5.06</td>
<td>C</td>
</tr>
<tr>
<td>regular-expression</td>
<td>JavaScript</td>
<td>Java</td>
<td>3.88</td>
<td></td>
<td>JavaScript</td>
<td>Java</td>
<td>4.4</td>
<td>JavaScript</td>
</tr>
<tr>
<td>merge-sort</td>
<td>Go</td>
<td>R</td>
<td>6.52</td>
<td></td>
<td>Go</td>
<td>Swift</td>
<td>4.74</td>
<td>Go</td>
</tr>
<tr>
<td>insertion-sort</td>
<td>JavaScript</td>
<td>R</td>
<td>5.13</td>
<td></td>
<td>JavaScript</td>
<td>R</td>
<td>4.21</td>
<td>Go</td>
</tr>
<tr>
<td>quick-sort</td>
<td>Go</td>
<td>Swift</td>
<td>5</td>
<td></td>
<td>C++</td>
<td>Swift</td>
<td>5.48</td>
<td>Go</td>
</tr>
<tr>
<td>selection-sort</td>
<td>Go</td>
<td>Ruby</td>
<td>3.98</td>
<td></td>
<td>JavaScript</td>
<td>R</td>
<td>3.6</td>
<td>C++</td>
</tr>
<tr>
<td>bubble-sort</td>
<td>Go</td>
<td>R</td>
<td>4.84</td>
<td></td>
<td>C++</td>
<td>Swift</td>
<td>4.6</td>
<td>Go</td>
</tr>
<tr>
<td>url-decoding</td>
<td>C</td>
<td>Java</td>
<td>6.36</td>
<td></td>
<td>C++</td>
<td>Java</td>
<td>4.87</td>
<td>C</td>
</tr>
<tr>
<td>url-encoding</td>
<td>PHP</td>
<td>R</td>
<td>7.38</td>
<td></td>
<td>PHP</td>
<td>R</td>
<td>5.64</td>
<td>PHP</td>
</tr>
<tr>
<td>call-an-object-method</td>
<td>C++</td>
<td>Python</td>
<td>5.62</td>
<td></td>
<td>JavaScript</td>
<td>Perl</td>
<td>7.16</td>
<td>C++</td>
</tr>
<tr>
<td>classes</td>
<td>JavaScript</td>
<td>R</td>
<td>5.1</td>
<td></td>
<td>JavaScript</td>
<td>R</td>
<td>6.86</td>
<td>JavaScript</td>
</tr>
<tr>
<td>inheritance-multiple</td>
<td>Ruby</td>
<td>JavaScript</td>
<td>7.94</td>
<td></td>
<td>C++</td>
<td>JavaScript</td>
<td>5.89</td>
<td>C++</td>
</tr>
<tr>
<td>inheritance-single</td>
<td>C++</td>
<td>JavaScript</td>
<td>3.6</td>
<td></td>
<td>C++</td>
<td>Java</td>
<td>1.79</td>
<td>C++</td>
</tr>
<tr>
<td>function-composition</td>
<td>C++</td>
<td>Swift</td>
<td>7.96</td>
<td></td>
<td>C++</td>
<td>Perl</td>
<td>5.62</td>
<td>C++</td>
</tr>
</tbody>
</table>
(a) Embedded System (b) Laptop (c) Server
Figure 2: EDP box plots. The points show outliers. The vertical scale is the logarithmic ratio \( \log_{10}(p/p_{min}) \) where \( p \) is the measurement and \( p_{min} \) is the minimum of the measurements for that task, corresponding to the most EDP-friendly language.
For the embedded system, tasks such as file-input-output, inheritance-single, and synchronous-concurrency exhibit smaller EDP scores. This does not happen for the laptop and server platforms.
Our figures also show that outliers do exist for all three platforms. For instance, the embedded system’s box plot has outliers for tasks such as function-composition, huffman-encoding, lzw-compression, palindrome-detection, and for url-encoding. Similarly, for the laptop platform huffman-coding and lzw-compression indicate that specific programming languages can offer much more gains in terms of EDP.
### 3.1.4 Range of results
Figure 2 depicts the ranges of the EDP scores for each task that we measure in the three platforms. Apart from a few tasks, our measurements have wide ranges—we note that we are using a logarithmic scale.
---
C is the best in arithmetic, compression and concurrency; while C++, Go, and Rust are the runners-up. R, Perl, Swift, and Java show weak, overall, performance in terms of EDP. Go is exhibiting best EDP results for sorting algorithms. Rust for file-I/O, JavaScript for pattern matching and replacing, and C++ for function-composition.
3.2 RQ2. Which types of programming languages are, on average, more EDP efficient and inefficient for each of the selected platforms?
We provide an EDP ranking for the programming languages—based on all tasks average EDP score—on our platforms. In addition, we discuss how EDP weights influence our results for each platform.
Overall Ranking. Table 4 illustrates for each platform the ranking of the programming languages’ average EDP and the influence of their weights; where this is applicable. For all the selected platforms, compiled programming languages such as C, C++, and Go are ranked on top by offering the best EDP implementations on average. Rust is also ranked among the most efficient EDP programming languages for the embedded system, but it drops for the laptop and server platforms. Swift is the only one, from the compiled programming languages, that shows weak performance.
From the semi-compiled programming languages, the .NET framework’s implementations (C# and VB.NET) score better against the interpreted languages, but remain less efficient than the compiled languages. Java is ranked as the most inefficient among the semi-compiled languages, while C# as the most efficient.
The interpreted programming languages are the ones offering on average lowest performance, for all platforms, and appear at the bottom ranks in the Table 4. Among them, JavaScript is the one being the most EDP efficient while R is the most inefficient.
Weights impact on EDP. By using different weights in the EDP, we force programming languages with low execution time but higher energy consumption to result in lower EDP score compared to the ones having low energy consumption but higher run-time performance. For instance, with \( w = 1 \) JavaScript achieves a logarithmic EDP score 3.19 for the numerical_integration case while C# achieves 1.68, which makes it more efficient compared to JavaScript. However, when \( w = 2 \) or \( w = 3 \), JavaScript’s EDP changes to 3.35 and 3.52 while for C# it changes to 3.03 and 4.38, respectively. This denotes that C# is consuming less energy but is slower than JavaScript.
By looking at the results presented in Table 4, we see that only the embedded system’s average EDP scores were affected by the changes in the weights. For instance, C#, VB.NET, and JavaScript were influenced after raising the run-time performance to the second and third power. Specifically, this denotes that JavaScript is much faster, on average, compared to C# and VB.NET but more energy demanding—since before raising the run-time performance C# and VB.NET had lower EDP.
Compiled languages are more EDP efficient compared to the interpreted ones. Among the compiled, semi-compiled, and interpreted languages, the best EDP is obtained by C, C#, and JavaScript, respectively. Raising the EDP performance exponent to 2 or 3 affects the ranking of the embedded platform’s tasks.
3.3 RQ3. How much does the EDP of each programming language differ among the selected platforms?
We investigate how much a programming language’s average EDP differs across the measurement platforms by using a non-parametric statistical test, the Wilcoxon’s signed-rank test. To do that, we developed a script to carry out pairwise statistical analysis for the average EDP that a programming language scored for all the tasks, between two of the platforms each time. Compared to RQ1 and RQ2, we used the raw values instead of logarithms, as the test takes into account the rank of the differences and not their magnitude. Our null hypothesis follows.
**Hypothesis H₀**: A programming language’s average EDP, does not have a statistically important difference between the measurement platforms.
Let \( \mathcal{L} \) be a programming language, and \( \mathcal{P}_1, \mathcal{P}_2, \) and \( \mathcal{P}_3 \) (where \( \mathcal{P}_1 \neq \mathcal{P}_2 \neq \mathcal{P}_3 \)) the selected platforms of our experiment. Also, we pick the average EDP for all the tasks and we compare them in pairs such as: \( (\mathcal{P}_1, \mathcal{P}_2); (\mathcal{P}_1, \mathcal{P}_3); (\mathcal{P}_2, \mathcal{P}_3) \). Since each platform’s results were used twice in a comparison (once for each other platform), we used the Bonferroni correction to counteract the multiple comparison problem. Therefore, if the test’s \( p \)-value for the pair \( \mathcal{P}_x \) and \( \mathcal{P}_y \) (where \( x, y \in \{1, 2, 3\} \) and \( x \neq y \)) satisfies the condition \( p < 0.01/3 \), as there are 3 platforms pairs for each language, the difference between the average of \( \mathcal{P}_x \) and \( \mathcal{P}_y \) is statistically significant for the \( \mathcal{L} \) programming language. Otherwise, if \( 0.01/3 \leq p < 0.05/3 \), the statistical significance of the difference between averages is weaker. If \( p \geq 0.05/3 \), the null hypothesis cannot be rejected. Table 5 illustrates results after the pairwise statistical test of two platforms at a time for all the programming languages. The collected results show that we can reject the null hypothesis only for two cases and a third with weaker statistical significance (highlighted in figure 5).
**Embedded and Laptop.** The results illustrate that there is significant difference between the average EDP of the embedded and laptop platforms for C and Swift. In addition, the results show a weaker evidence that the average EDP is different only for a single instance among the programming languages, that is C++, for which the null hypothesis cannot be rejected.
**Embedded and Server.** For the embedded and server platforms there is no strong statistical evidence for the difference in average EDP.
---
### Table 4: Programming Languages Average Weighted EDP Ranking
<table>
<thead>
<tr>
<th>Rank</th>
<th>Embedded</th>
<th>Laptop</th>
<th>Server</th>
</tr>
</thead>
<tbody>
<tr>
<td>( w = 1 )</td>
<td>( w = 2 )</td>
<td>( w = 3 )</td>
<td>( w = 1, 2, 3 )</td>
</tr>
<tr>
<td>( w = 1, 2, 3 )</td>
<td>( w = 1, 2, 3 )</td>
<td>( w = 1, 2, 3 )</td>
<td>( w = 1, 2, 3 )</td>
</tr>
<tr>
<td>1</td>
<td>C</td>
<td>C</td>
<td>C</td>
</tr>
<tr>
<td>2</td>
<td>C++</td>
<td>C++</td>
<td>C++</td>
</tr>
<tr>
<td>3</td>
<td>Go</td>
<td>Go</td>
<td>Go</td>
</tr>
<tr>
<td>4</td>
<td>Rust</td>
<td>Rust</td>
<td>Rust</td>
</tr>
<tr>
<td>5</td>
<td>C#</td>
<td>JavaScript</td>
<td>JavaScript</td>
</tr>
<tr>
<td>6</td>
<td>JavaScript</td>
<td>VB.NET</td>
<td>VB.NET</td>
</tr>
<tr>
<td>7</td>
<td>VB.NET</td>
<td>JavaScript</td>
<td>C#</td>
</tr>
<tr>
<td>8</td>
<td>PHP</td>
<td>PHP</td>
<td>PHP</td>
</tr>
<tr>
<td>9</td>
<td>Ruby</td>
<td>Ruby</td>
<td>Ruby</td>
</tr>
<tr>
<td>10</td>
<td>Python</td>
<td>Python</td>
<td>Python</td>
</tr>
<tr>
<td>11</td>
<td>Perl</td>
<td>Perl</td>
<td>Perl</td>
</tr>
<tr>
<td>12</td>
<td>Java</td>
<td>Java</td>
<td>Java</td>
</tr>
<tr>
<td>13</td>
<td>Swift</td>
<td>Swift</td>
<td>Swift</td>
</tr>
<tr>
<td>14</td>
<td>R</td>
<td>R</td>
<td>R</td>
</tr>
</tbody>
</table>
Laptop and Server. Between these two platforms we found no strong significant difference for any instance.
<table>
<thead>
<tr>
<th>Platforms</th>
<th>C#</th>
<th>C++</th>
<th>Go</th>
<th>JavaScript</th>
<th>Java</th>
<th>Perl</th>
<th>PHP</th>
<th>Python</th>
<th>R</th>
<th>Ruby</th>
<th>Rust</th>
<th>Swift</th>
<th>VB.NET</th>
</tr>
</thead>
<tbody>
<tr>
<td>Embedded–Laptop</td>
<td>0.09</td>
<td>0.00</td>
<td>0.01</td>
<td>0.08</td>
<td>0.02</td>
<td>0.56</td>
<td>0.62</td>
<td>0.12</td>
<td>0.15</td>
<td>0.54</td>
<td>0.10</td>
<td>0.05</td>
<td>0.00</td>
</tr>
<tr>
<td>Embedded–Server</td>
<td>0.39</td>
<td>0.07</td>
<td>0.22</td>
<td>0.29</td>
<td>0.20</td>
<td>0.47</td>
<td>0.91</td>
<td>0.39</td>
<td>0.40</td>
<td>0.97</td>
<td>0.35</td>
<td>0.37</td>
<td>0.04</td>
</tr>
<tr>
<td>Laptop–Server</td>
<td>0.19</td>
<td>0.27</td>
<td>0.14</td>
<td>0.43</td>
<td>0.11</td>
<td>0.31</td>
<td>0.47</td>
<td>0.33</td>
<td>0.52</td>
<td>0.36</td>
<td>0.24</td>
<td>0.28</td>
<td>0.07</td>
</tr>
</tbody>
</table>
There is a significant difference between the average EDP, in some case, of the embedded and laptop platforms.
4 DISCUSSION
We investigate the root causes of the results of Section 3 by digging into the source code of the tasks that showed better EDP results. We focus on the programming languages that achieved the most EDP efficient results. Additionally, we explain how the collected results from the heatmaps can be useful for practitioners in developing energy-aware applications.
4.1 Champions
Concurrency. Best efficiency in EDP is achieved in programming languages that rely on libraries implementations for concurrency. For instance, C, that achieved far better EDP, uses OpenMP [26] and libco [8] to execute the tasks found under the concurrency categories; in contrast to Perl’s and PHP’s thread libraries.
Regular Expressions. JavaScript produces the most EDP efficient results for regular-expression tasks, such as pattern matching and replacing. The reason behind this is that the V8 JavaScript engine (build in C++) achieves a speed-up for regular expressions, after the RegEx library is built on top of Irregexp, in combination with CodeStubAssembler [21]. Therefore, we conducted an experiment where we used nvm [9], a JavaScript version management for node.js, to install a JavaScript version that does not support the above-described libraries and related functionality (versions below 8.5.7). When using the version where the RegEx library does not use Irregexp and CodeStubAssembler, the EDP increased by 331%.
Object-Oriented Features. In addition, JavaScript, in most cases, achieves better results for the classes and call-an-object-method tasks. However, JavaScript is dynamically typed, i.e., types and type information is not explicit and attributes can be added to and deleted from objects on the fly. That means that object orientation under JavaScript is very different than object orientation in, say, C++, where the focus is on designing polymorphic types. Also, to access the types and properties effectively, V8 engine creates and uses the hidden classes, at run-time, to have an internal representation of the object to improve the property access time. In addition, once a hidden class is created for a particular object, the V8 engine shares the same hidden class among objects created in the same way [22].
File handling. Rust, compared to VB.NET, produces better EDP results for the file-i/o operations regarding the embedded and laptop platforms. We performed a small experiment—using the strace [14] Linux built-in command—and we found that VB.NET’s intermediate code makes 14 times more system calls in total compared to Rust. According to Aggarwal et al. [4], when the system calls between two applications diverge significantly, it is possible that the applications’ power usage will differ too. Moreover, the VB.NET implementation for this task takes 89% of its total execution time for mmap (creating a new mapping in the virtual address space for the current process files) and munmap (deleting the mapping for the process when it is no longer needed). VB.NET is slower since it executes the lseek operation when writing in a file which is not the case for Rust. This might occurs because VB.NET’s i/o-buffers are smaller than Rust’s and requires more than a single write operation to write all the data in the file. In this way, Rust spends much less time for i/o system calls compared to VB.NET, resulting in faster execution time and thus lower EDP.
Functional Programming Features. C++ is the language exhibiting the best EDP efficiency for the function-composition task. The reason behind this is that C++ uses meta-programming through the Standard Template Library to compose functions at compile-time via the help of preprossesor. As a result, C++ has faster execution time and less energy consumption resulting in more efficient EDP compared to the other implementations.
4.2 Applications
We believe that a developer can consult our heat maps and use them as a guideline to develop more EDP efficient applications. For the development of a more complex application—that may combine more that one of the generic tasks evaluated in this study—a developer can choose the language or languages that will provide the best efficiency, in terms of EDP.
In the context of embedded systems, even though we showed in Section 3.2 that Java and Swift, the major programming languages for developing Android and iOS applications, are on average EDP inefficient, developers can use several efficient practices. For instance, when developing Android applications, practitioners can use the Native Development Kit [13] to incorporate native C and C++ code for heavy arithmetic, concurrent, and functional tasks.
In general, each programming language offers a number of different features such as dynamic and static binding, lazy, and eager evaluation, garbage collection, automatic counter references, strong and weak typing, and so on. Moreover, the different platforms’ CPU architectures and resources could be also a factor of causing differences in EDP results. We do not know how these might affect the EDP. However, our results show certain programming languages implementations are more beneficial on selected tasks. Therefore, researchers could use these findings to identify which are the factors or features causing these outcomes and use them in developing EDP efficient programming languages.
5 RELATED WORK
To the best of our knowledge, this is the first study that assesses the EDP of commonly used programming tasks—when they are implemented in different programming languages and they run on three platforms (an embedded system, a laptop, and a server)—to provide developers with guidelines about the most efficient programming languages per case. In the following, we present and compare related work’s results with our findings.
5.1 Across Programming Languages
Pankratius et al. pursued a controlled comparative experiment on Java and Scala developers, in a multicore environment, to evaluate factors, such as the performance of both languages [31]. One of their important findings refers to the fact that the functional paradigm does not lead to bad performance, but programs that use both functional and imperative styles can have improved performance. Additionally, we took into account object-oriented and functional features from programming languages and we found that the latter result in more efficient EDP.
Pereira et al. conducted an empirical study on 27 programming languages from The Computer Language Benchmarks Game and they compared them on energy, time, and memory matters [32]. Even though our methods have similarities with Pereira’s et al. study, we, additionally, checked the EDP of our sample’s implementations on three different platforms, using implementations from the Rosetta Code Repository. Similarly to us, they found that compiled languages are the fastest, whereas interpreted languages, such as JavaScript and PHP, are the most energy efficient in operations with regular expressions.
Close to our paper is the empirical study that Nanz and Furia conducted on the Rosetta Code Repository to compare the performance of eight popular programming languages, including C, Go, C#, Java, F#, Haskell, Python, and Ruby [30]. Here, we did not measure only performance, but we also used a power analyzer to run programming tasks on 14 different platforms in order to compare their EDP. This study’s findings agree with ours regarding compiled languages that have the best performance.
Finally, Meyerovich and Rabkin performed an empirical study by analyzing 200,000 SourceForge projects and asking almost 13,000 programmers to identify characteristics that lead them to select appropriate programming languages for implementing their software projects [28]. We compared the EDP of programming tasks performed in several programming languages.
5.2 Across Execution Platforms
Abdulsalam et al. conducted experiments on workstations and evaluated the energy effect of four memory allocation choices (malloc, new, array, and vector). They showed that malloc is the most efficient in terms of energy consumption and performance [1]. Chen and Zong worked on smartphones and showed, by using the Android Run Time environment (instead of Dalvik), that the energy and performance implications of Java are similar to C and C++ [11]. Finally, Rashid et al. worked on an embedded system and compared the energy and performance impact of four sorting algorithms written in three different programming languages (ARM assembly, C/C++, and Java) [33]. They found that Java consumes most energy and performs slowly against C/C++ and assembly. Similarly, we found that Java was slower in comparison with C/C++. In addition, we observed that Go had the lowest EDP for sorting algorithms.
Many empirical studies have assessed the impact of coding practices (e.g., the use of for loops, getters and setters, static method invocation, views and widgets, and so on) regarding energy consumption. Characteristically, Tomini et al. conducted a study on Android applications and found that the use of for loops with specified length and the access of class variables without the use of getters and setters can reduce the amount of the energy that the applications consume [40]. Linares-Vsquez et al. performed an analysis of 55 Android applications from various domains and reported the most energy consuming API methods [27]. For instance, they found that from 60% of the most energy-greedy APIs, 37% were related to the graphical user interface and image manipulation, while the remaining 23% were associated with databases. Finally, Sampson et al. proposed an approach called EnerJ that uses annotations to indicate particular data types that are involved in computations that can consume lower energy [37]. They prove that for a small number of type annotations added to the types of a Java program they can achieve more energy savings.
Contrary to previous works, we compare EDP of small programming tasks implemented in 14 programming languages that can run on three distinct computer platforms. Overall, our results show that compiled programming languages perform far more EDP efficiently compared to interpreted and semi-compiled. Our findings also indicate significant difference between the results of the laptop and the embedded system execution environments.
6 CONCLUSIONS
We examined programming languages’ energy consumption and run-time performance implications for certain programming tasks, by using the EDP formula. We also investigated how our results vary among different computer platforms and showed that there is not a single winner for all cases. Based on our findings, we suggest that specific implementations are more EDP efficient than others with respect to the tasks they perform. So, developers can use:
- C for the development of computationally-intensive and concurrent tasks;
- Go for sorting tasks;
- Rust for I/O-intensive tasks, such as file handling;
- JavaScript for regular-expression tasks, such as string matching, substitution; and
- C++ for functional programming tasks, such as function composition, at a low level of abstraction.
Regarding our future research directions, we will attempt to: 1) identify which are the programming language features that offer major implications on EDP, 2) dig into generated machine and intermediate code to point out how different compiler implementations or run-time engines can affect EDP, 3) consider more programming task categories, including network access operations and image processing, and 4) increase the variety of our test inputs.
ACKNOWLEDGMENTS
This work is funded by the SENECA project, a Marie Skłodowska-Curie Innovative Training Networks (ITN-EID) 642954 agreement.
REFERENCES
|
{"Source-Url": "https://pure.tudelft.nl/portal/files/48109816/GKLS18.pdf", "len_cl100k_base": 14534, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 44925, "total-output-tokens": 17069, "length": "2e13", "weborganizer": {"__label__adult": 0.0004673004150390625, "__label__art_design": 0.0002818107604980469, "__label__crime_law": 0.00034308433532714844, "__label__education_jobs": 0.0008988380432128906, "__label__entertainment": 8.32676887512207e-05, "__label__fashion_beauty": 0.00017321109771728516, "__label__finance_business": 0.0003600120544433594, "__label__food_dining": 0.00033783912658691406, "__label__games": 0.0006794929504394531, "__label__hardware": 0.0023021697998046875, "__label__health": 0.0006208419799804688, "__label__history": 0.0003020763397216797, "__label__home_hobbies": 0.00013947486877441406, "__label__industrial": 0.000579833984375, "__label__literature": 0.00025177001953125, "__label__politics": 0.0002903938293457031, "__label__religion": 0.000484466552734375, "__label__science_tech": 0.055938720703125, "__label__social_life": 0.00010967254638671876, "__label__software": 0.006252288818359375, "__label__software_dev": 0.927734375, "__label__sports_fitness": 0.00029730796813964844, "__label__transportation": 0.0006737709045410156, "__label__travel": 0.00022423267364501953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69293, 0.04831]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69293, 0.45958]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69293, 0.88571]], "google_gemma-3-12b-it_contains_pii": [[0, 1243, false], [1243, 5893, null], [5893, 12125, null], [12125, 17993, null], [17993, 26969, null], [26969, 30396, null], [30396, 36968, null], [36968, 42838, null], [42838, 49288, null], [49288, 55407, null], [55407, 61799, null], [61799, 69293, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1243, true], [1243, 5893, null], [5893, 12125, null], [12125, 17993, null], [17993, 26969, null], [26969, 30396, null], [30396, 36968, null], [36968, 42838, null], [42838, 49288, null], [49288, 55407, null], [55407, 61799, null], [61799, 69293, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69293, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69293, null]], "pdf_page_numbers": [[0, 1243, 1], [1243, 5893, 2], [5893, 12125, 3], [12125, 17993, 4], [17993, 26969, 5], [26969, 30396, 6], [30396, 36968, 7], [36968, 42838, 8], [42838, 49288, 9], [49288, 55407, 10], [55407, 61799, 11], [61799, 69293, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69293, 0.24176]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
8cc09e5cfd543a0795f7948c411d87f8df19a047
|
[REMOVED]
|
{"Source-Url": "https://purehost.bath.ac.uk/ws/files/140944747/COIN_main.pdf", "len_cl100k_base": 13466, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 67679, "total-output-tokens": 17577, "length": "2e13", "weborganizer": {"__label__adult": 0.00038242340087890625, "__label__art_design": 0.0006823539733886719, "__label__crime_law": 0.0006513595581054688, "__label__education_jobs": 0.00305938720703125, "__label__entertainment": 0.00011616945266723631, "__label__fashion_beauty": 0.0002231597900390625, "__label__finance_business": 0.0007448196411132812, "__label__food_dining": 0.0004782676696777344, "__label__games": 0.001232147216796875, "__label__hardware": 0.00109100341796875, "__label__health": 0.0009398460388183594, "__label__history": 0.0004525184631347656, "__label__home_hobbies": 0.0002200603485107422, "__label__industrial": 0.0007562637329101562, "__label__literature": 0.0007200241088867188, "__label__politics": 0.0004341602325439453, "__label__religion": 0.0005612373352050781, "__label__science_tech": 0.1776123046875, "__label__social_life": 0.00014269351959228516, "__label__software": 0.01210784912109375, "__label__software_dev": 0.7958984375, "__label__sports_fitness": 0.0003020763397216797, "__label__transportation": 0.0008950233459472656, "__label__travel": 0.0002129077911376953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57346, 0.03242]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57346, 0.48274]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57346, 0.87347]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2874, false], [2874, 6603, null], [6603, 9743, null], [9743, 13519, null], [13519, 17250, null], [17250, 20410, null], [20410, 23312, null], [23312, 25803, null], [25803, 28273, null], [28273, 31383, null], [31383, 34070, null], [34070, 35882, null], [35882, 39346, null], [39346, 42676, null], [42676, 45730, null], [45730, 48757, null], [48757, 51842, null], [51842, 54836, null], [54836, 57346, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2874, true], [2874, 6603, null], [6603, 9743, null], [9743, 13519, null], [13519, 17250, null], [17250, 20410, null], [20410, 23312, null], [23312, 25803, null], [25803, 28273, null], [28273, 31383, null], [31383, 34070, null], [34070, 35882, null], [35882, 39346, null], [39346, 42676, null], [42676, 45730, null], [45730, 48757, null], [48757, 51842, null], [51842, 54836, null], [54836, 57346, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57346, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57346, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2874, 2], [2874, 6603, 3], [6603, 9743, 4], [9743, 13519, 5], [13519, 17250, 6], [17250, 20410, 7], [20410, 23312, 8], [23312, 25803, 9], [25803, 28273, 10], [28273, 31383, 11], [31383, 34070, 12], [34070, 35882, 13], [35882, 39346, 14], [39346, 42676, 15], [42676, 45730, 16], [45730, 48757, 17], [48757, 51842, 18], [51842, 54836, 19], [54836, 57346, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57346, 0.03972]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
7a16c2325b0b01bdb72b9bacc84cefea72599e00
|
1 FAST AND EFFICIENT SPATIAL SCALABLE IMAGE COMPRESSION USING WAVELET LOWER TREES
J. Oliver, Student Member, IEEE, M. P. Malumbres, Member, IEEE
Department of Computer Engineering (DISCA)
Technical University of Valencia
Camino de Vera 17, 46017 Valencia, Spain
Phone: +34 96 387 97 06, Fax: +34 96 387 75 79
E-mail: {joliver, mperez}@disca.upv.es
ABSTRACT
In this paper, a new image compression algorithm is proposed based on the efficient construction of wavelet coefficient lower trees. This lower-tree wavelet (LTW) encoder presents state-of-the-art compression performance, while its temporal complexity is lower than the one presented in other wavelet coders, like SPIHT and JPEG 2000. This fast execution is achieved by means of a simple two-pass coding and one-pass decoding algorithm. On the other hand, its computation does not need additional lists or complex data structures, so there is not memory overhead. A formal description of the algorithm is provided, so that an implementation can be performed straightforward. The results show that our codec works faster than SPIHT and JPEG2000 (up to eight times faster) with better performance in terms of rate-distortion metric.
1. INTRODUCTION
During the last decade, several image compression schemes emerged in order to overcome the known limitations of block-based algorithms that use the Discrete Cosine Transform (DCT), the most widely used compression technique at that moment.
Some of these alternative proposals were based on more complex techniques, like Vector Quantization and Fractal image coding, while others simply proposed the use of a different and more suitable mathematical transform, the Discrete Wavelet Transform (DWT). At that time, there was a generalized idea: more efficient images coders would only be achieved by means of sophisticated techniques with high temporal complexity, or by the combination of some of them. The Embedded Zero-Tree Wavelet coder (EZW) can be considered as the first Wavelet image coder that broke that trend. Since then, many wavelet coders were proposed and finally, the DWT was included in the JPEG 2000 standard due to its compression efficiency and other features (scalability, etc.).
All the wavelet-based image coders, and generally all the transform-based coders, consist in two fundamental stages. During the first one, the image is transformed from spatial domain to another one, in the case of wavelet transform a combined spatial-frequency domain called wavelet domain. In the second pass the coefficients resulting
\footnote{This work was supported by the Generalitat Valenciana research grant CTIDIB/2002/19}
from the domain transform are encoded in an efficient way, in order to achieve high rate/distortion performance and other features.
The wavelet transform can be implemented as a regular filter-bank convolution, however several strategies have been proposed in order to speed-up the computation time of this transform, along with the reduction of the total amount of memory needed to compute it. In this way, a line-based processing is proposed in [1], while an alternative wavelet transform method, called lifting scheme, is proposed in [2]. This lifting transform provides in-place calculation of the wavelet coefficients by overwriting the input sample values, and thus it minimizes the number of memory accesses.
However, the wavelet coefficient coding pass is not usually improved in terms of temporal complexity and memory requirements. When designing and developing a new wavelet image encoder, the most important factor to be optimized uses to be the rate/distortion (R/D) performance, while other features like embedded bit-stream, SNR scalability, spatial scalability and error resilience may be considered.
In this paper we propose an algorithm aiming to achieve equal or higher rate/distortion performance than state-of-the-art image coders, while the required execution time is minimized. Moreover, due to in-place processing of the wavelet coefficients, there is not memory overhead (it only needs memory to store the source image or piece of image to be coded). Additionally, our algorithm is naturally spatial scalable and it is possible to perform SNR scalability and certain level of error resilience.
This paper is organized as follows. In Section 2 we will focus on some important wavelet image coders that have been previously proposed, focusing on their computational complexity and R/D performance. Section 3 shows a fast and simple algorithm that will be used as a starting point for the proposed algorithm, which it is explained in detail in section 4. Finally, in section 5 we compare our proposal with other wavelet image coders using real implementations, and not simulation results.
2. PREVIOUS WAVELET IMAGE CODERS AND THEIR PERFORMANCE
One of the first efficient wavelet image coders reported in the literature is the EZW [3]. It is based on the construction of coefficient-trees and successive-approximations, that can be implemented as bit-plane processing. Due to its successive-approximation nature, it is SNR scalable, although at the expense of sacrificing spatial scalability. SPIHT [4] is an advanced version of this algorithm, where coefficient-trees are processed in a more efficient way. Both algorithms need the computation of coefficient-trees and perform different iterations focusing on a different bit plane in each iteration, what usually requires high computational complexity.
Other compression algorithms perform bit plane processing along with other techniques like run-length coding. In this way, the stack-run encoder [5] achieves spatial scalability, while the embedded run-length coder described in [6] is SNR scalable. Authors state that these proposals are faster due to the lack of computation needed to define coefficient-trees, but it also leads them to poorer R/D performance. Moreover, bit plane processing is still present, limiting the speed-up of the encoder. Notice that in software implementations, several iterations accessing to the same coefficients reduce the computer cache performance.
Recently, the JPEG 2000 standard was released [7]. The proposed algorithm does not use coefficient-trees, but it performs bit-plane processing with three passes per bit plane. In this way, it achieves finer rate control, along with a new R/D optimization algorithm. It also uses large number of contexts in order to overcome the inconvenience of not using coefficient-trees. JPEG 2000 attains both spatial and SNR scalability by means of postprocessing the encoded image, at the cost of higher computational complexity.
3. A SIMPLE FAST MULTIRESOLUTION IMAGE CODING ALGORITHM
For the most part, digital images are represented with a set of pixel values. The encoder proposed in this paper can be applied to a set of coefficients $C$ resulting from a dyadic decomposition $Ω(·)$, in order that $C=Ω(P)$. The most commonly used dyadic decomposition in image compression is the hierarchical wavelet subband transform [8], therefore an element $c_{i,j} \in C$ is called transform coefficient. In a wavelet transform, we call LH$_1$, HL$_1$ and HH$_1$ to the subbands resulting from the first level of the image decomposition, corresponding to horizontal, vertical and diagonal frequencies. The rest of image transform is performed by recursive wavelet decomposition on the remaining low frequency subband, until a desired decomposition level (N) is achieved (LL$_N$ is the remaining low frequency subband)
As we have seen in section 2, one of the main drawbacks in previous wavelet image encoders is their high temporal complexity. That is mainly due to the bit plane processing, that is performed along different iterations, using a threshold that focuses on a different bit plane in each iteration. In this way, it is easy to achieve an embedded bit-stream with progressive coding, since more bit planes add more SNR resolution to the recovered image.
Although embedded bit-stream is a nice feature in an image coder, it is not always needed and other alternatives, like spatial scalability, may be more valuable according to the final purpose. In this section, we are going to propose a very simple algorithm that is able to encode the wavelet coefficients without performing one loop scan per bit plane. Instead of it, only one scan of the transform coefficients will be needed.
In this algorithm, the quantization process is performed by two strategies: one coarser and another finer. The finer one consists on applying a scalar uniform quantization to the coefficients, and it is performed just after the DWT is applied. On the other hand, the coarser one is based on removing bit planes from the least significant part of the coefficients, and it is performed while our algorithm is applied. At this moment we define $rplanes$ as the number of less significant bits to be removed.
At encoder initialization, the maximum number of bits needed to represent the higher coefficient ($maxplane$) is calculated. This value and the $rplanes$ parameter are output to the decoder. Afterwards, we initialize an adaptive arithmetic encoder that will be used to encode the number of bits required by the coefficients. We will only output those coefficients ($c_{i,j} \in C$) that require more than $rplanes$ bits to be coded (those $c_{i,j}<2^{rplanes}$), thus only $maxplane-rplanes$ symbols are needed to represent this information. An extra symbol is required, so-called $LOWER$ symbol, to indicate those coefficients that are lower than the established threshold ($2^{rplanes}$). Notice that we say that $c_{i,j}$ is a significant
coefficient when it is different to zero after discarding the least significant \( r_{planes} \) bits, in other words, if \( c_{i,j} \geq 2^{r_{planes}} \).
In the next stage, the wavelet coefficients are encoded as follows. For each subband, from the \( N^{th} \) level to the first one, all the coefficients are scanned in Morton order (i.e., in medium-sized blocks). For each coefficient in that subband, if it is significant, a symbol indicating the number of bits required to represent that coefficient is arithmetically encoded. As coefficients in the same subband have similar magnitude, and due to the order we have established to scan the coefficients, the adaptive arithmetic encoder is able to represent very efficiently this information. However, we do not have enough information to reconstruct correctly the coefficient; we still need to encode its significant bits and sign.
On the other hand, if a coefficient is not significant, we should transmit a \texttt{LOWER} symbol so that the decoder can determine that it has been absolutely quantized, and thus it does not have associated information (neither coefficient bits nor sign).
Notice that when encoding the bits of a significant coefficient, the first \( r_{planes} \) bits and the most significant bit are not coded, the decoder can deduce the most significant bit through the arithmetic symbol that indicates the number of bits required to encode this coefficient. Moreover, in order to speed up the execution time of the algorithm, the bits and sign of significant coefficients are raw encoded, what results in very small lost in R/D performance.
The proposed encoding algorithm, \textit{algorithm I}, is defined as follows.
\begin{align*}
\text{(E1) INITIALIZATION} & \\
\text{output } & r_{planes} \\
\text{output } & \maxplane = \max_{\forall c_{i,j} \in C} \left\lfloor \log_2 \left( \left| c_{i,j} \right| \right) \right\rfloor \\
\text{(E2) OUTPUT THE COEFFICIENTS.} & \text{Scan the subbands in the established order.} \\
\text{For each } & c_{i,j} \text{ in a subband} \\
\text{nbits}_{i,j} & = \left\lfloor \log_2 \left( \left| c_{i,j} \right| \right) \right\rfloor \\
\text{if } & \text{nbits}_{i,j} > r_{planes} \\
\text{arithmetic\_output } & \text{nbits}_{i,j} \\
\text{output } & \text{bit}_{\text{nbits}_{i,j}-1}\left( c_{i,j} \right) \ldots \text{bit}_{r_{planes}+1}\left( c_{i,j} \right) \\
\text{output } & \text{sign}(c_{i,j}) \\
\text{else } & \\
\text{arithmetic\_output } & \text{LOWER} \\
\end{align*}
\textit{Note:} \( \text{bit}_n(c) \) is a function that returns the \( n^{th} \) bit of \( c \).
This algorithm is resolution scalable due to the selected scanning order and the nature of the wavelet transform. In this way, the first subband that the decoder attains is the LL\(_N\), which is a low-resolution scaled version of the original image. Then, the decoder progressively receives the remaining subbands, from lower frequency subbands to higher ones, which are used as a complement to the low-resolution image to recursively double its size, what is know as Mallat decomposition [9].
Notice that spatial and SNR scalability are closely related features. Spatial resolution allow us to have different resolution images from the same image. Through interpolation techniques, all these images could be resized to the original size, so that the larger an image is, the closer to the original it gets. Therefore, in some way this algorithm could also be used for SNR scalability purposes.
The robustness of the proposed algorithm lies in the low dependency among the encoded information. This dependency is only present in consecutive arithmetic encoded symbols, and thus the use of synchronism marks would increase the error resilience at the cost of slightly decreasing the R/D performance. However, the lack of dependency that yields to higher robustness also causes lower compression performance in the encoding process. The correlation among coefficients and subbands can be exploited in a more efficient way, as we can see in section 4, which takes this algorithm as a starting point to define a more efficient encoder, with similar characteristics to those presented in this section.
4. TWO-PASS EFFICIENT BLOCK CODING USING LOWER TREES
Tree based wavelet image encoders are proved to efficiently store the transform coefficients, achieving great performance results. In these algorithms, two stages can be established. The first one consists on encoding the significance map, i.e., the location and amount of bits required to represent those coefficients that will be encoded (significant coefficients). In the second stage, significant transform coefficients are encoded, i.e. their sign and magnitude bits, depending on the desired target bit rate.
Previous tree based wavelet image coders performs bit plane processing in both stages, resulting in high temporal complexity. The algorithm presented in this section is an extension of the one-pass algorithm that we have described in section 3. In this algorithm, a new tree based structure is introduced in order to reduce the data redundancy among subbands. This structure is called lower-tree.
Like in the rest of tree encoding techniques, coefficients from \( C = \Omega(P) \) can be logically arranged as a tree. In these trees, the offspring for every coefficient \( c_{a,b} \) can be computed as follows:
if \( c_{a,b} \in LL_N \land a \in \{2k_1\} \land b \in \{2k_2\} : k_1, k_2 \in Z \)
offspring\( (c_{a,b}) = \{\phi\} \)
if \( c_{a,b} \in LL_N \land a \in \{2k_1 + 1\} \land b \in \{2k_2\} : k_1, k_2 \in Z, w = \text{width}(LL_N), h = \text{height}(LL_N) \)
offspring\( (c_{a,b}) = \{c_{a+w,b}, c_{a+w+1,b}, c_{a+w,b+1}, c_{a+w+1,b+1}\} \)
if \( c_{a,b} \in LL_N \land a \in \{2k_1\} \land b \in \{2k_2 + 1\} : k_1, k_2 \in Z, w = \text{width}(LL_N), h = \text{height}(LL_N) \)
offspring\( (c_{a,b}) = \{c_{a+b,h}, c_{a+b+h,1}, c_{a+b,h+1}, c_{a+b+1,h+1}\} \)
if \( c_{a,b} \in LL_N \land a \in \{2k_1 + 1\} \land b \in \{2k_2 + 1\} : k_1, k_2 \in Z, w = \text{width}(LL_N), h = \text{height}(LL_N) \)
offspring\( (c_{a,b}) = \{c_{a+b+h,1}, c_{a+b+h+1,1}, c_{a+b+h,1+1}, c_{a+b+h+1,1+1}\} \)
if \( c_{a,b} \in HL_1 \lor c_{a,b} \in LH_1 \lor c_{a,b} \in HH_1 \)
offspring\( (c_{a,b}) = \{\phi\} \)
if \( c_{a,b} \in LL_N \land c_{a,b} \in HL_1 \land c_{a,b} \in LH_1 \land c_{a,b} \in HH_1 \)
offspring\( (c_{a,b}) = \{c_{2a,2b}, c_{2a+1,2b}, c_{2a,2b+1}, c_{2a+1,2b+1}\} \)
In this way, if a coefficient has offspring, the direct descendents always form a 2x2 block of coefficients, and the rest of descendant levels can be attained by successively calculating the offspring of these direct descendents.
The quantization used in this new proposed algorithm is the same as in the algorithm I, so that a coefficient is called lower-tree root if this coefficient and all its descendants are lower than $2^{r\text{planes}}$. The set formed by all these coefficients form a lower-tree.
In this new proposal, we use the label LOWER to point out that a coefficient is the root of a lower-tree. The rest of coefficients in the lower-tree are labeled as LOWER_COMPONENT. On the other hand, if a coefficient is lower than $2^{r\text{planes}}$ but it does not belong to a lower-tree, it is considered as ISOLATED_LOWER. Labels are applied by overwriting the coefficient value by an integer value associated to the corresponding label, which must be outside the possible range of the wavelet coefficients (typically by reusing the values in the quantized range [0.. $2^{r\text{planes}}$])
Once we have defined the basic concepts to understand the algorithm, we are ready to define the coding process. It is a two-pass algorithm. During the first pass, the wavelet coefficients are properly labeled according to their significance and all the lower-trees are formed. This coding pass is new with respect to the algorithm I. In the second image pass, the coefficient values are coded in a similar way than in the E2 stage of algorithm I, taking into account the new symbols introduced in the algorithm II. Notice that both significance map and significant values are encoded in this pass in only one iteration.
The encoder algorithm, algorithm II, is described as follows.
(E1) INITIALIZATION
\[
\text{output } r\text{planes} \\
\text{output } \maxplane = \max \left\{ \left\lfloor \log_2 \left( \left| c_{i,j} \right| \right) \right\rfloor \right\}
\]
(E2) CALCULATE SYMBOLS (first image pass)
Scan the first level subbands (HH1, LH1 and HL1) in 2x2 blocks.
For each block $B_n$
\[
\text{if } c_{i,j} < 2^{r\text{planes}} \forall c_{i,j} \in B_n \\
\text{set } c_{i,j} = \text{LOWER}_\text{COMPONENT} \forall c_{i,j} \in B_n \\
\text{else} \\
\text{for each } c_{i,j} \in B_n \\
\text{if } c_{i,j} < 2^{r\text{planes}} \\
\text{set } c_{i,j} = \text{LOWER}
\]
Scan the rest of level subbands (from level 2 to N) in 2x2 blocks.
For each block $B_n$
\[
\text{if } c_{i,j} < 2^{r\text{planes}} \land \text{descendant}(c_{i,j}) = \text{LOWER}_\text{COMPONENT} \forall c_{i,j} \in B_n \\
\text{set } c_{i,j} = \text{LOWER}_\text{COMPONENT} \forall c_{i,j} \in B_n \\
\text{else} \\
\text{for each } c_{i,j} \in B_n \\
\text{if } c_{i,j} < 2^{r\text{planes}} \land \text{descendant}(c_{i,j}) = \text{LOWER}_\text{COMPONENT}
\]
set $c_{i,j} = \text{LOWER}$
if $c_{i,j} < 2^{r_{\text{planes}}} \land \text{descendant}(c_{i,j}) \neq \text{LOWER\_COMPONENT}$
set $c_{i,j} = \text{ISOLATED\_LOWER}$
(E3) OUTPUT THE COEFFICIENTS (second image pass)
Scan the subbands in an established order.
For each $c_{i,j}$ in a subband
if $c_{i,j} \neq \text{LOWER\_COMPONENT}$
if $c_{i,j} = \text{LOWER}$
arithmetic_output \text{LOWER}
else if $c_{i,j} = \text{ISOLATED\_LOWER}$
arithmetic_output \text{ISOLATED\_LOWER}
else
\[ n\text{bits}_{i,j} = \lceil \log_2 |c_{i,j}| \rceil \]
if descendant$(c_{i,j}) \neq \text{LOWER\_COMPONENT}$
arithmetic_output $n\text{bits}_{i,j}$
else
arithmetic_output $n\text{bits}_{i,j}^{\text{LOWER}}$
output $\text{bit}_{n\text{bits}_{i,j}^{\text{LOWER}}} \left( \left[ c_{i,j} \right] \ldots \left[ c_{i,j} \right] \right)$
output $\text{sign}(c_{i,j})$
Note: $\text{bit}_n(c)$ is a function that returns the $n^{\text{th}}$ bit of $c$.
If we analyze the first image pass we can observe that labeling of lower-trees is performed in a recursive way, building the lower-trees from leaves to the root. In the first level subbands, coefficients are scanned in 2x2 blocks and, if all the four coefficients are insignificant (i.e., lower than $2^{r_{\text{planes}}}$), they are considered to be part of the same lower-tree, being labeled as $\text{LOWER\_COMPONENT}$. Later on, if a 2x2 block in an upper level has four insignificant coefficients, and all their offspring have been labeled as $\text{LOWER\_COMPONENT}$, the coefficients in the block are also labeled as $\text{LOWER\_COMPONENT}$, creating a new, larger lower-tree.
However, when any coefficient in the block is significant, the lower-tree cannot continue growing. In that case, for any insignificant coefficient, if its descendants are $\text{LOWER\_COMPONENT}$, it is the root of that lower-tree and thus it is labeled as $\text{LOWER}$ symbol, otherwise it is labeled as $\text{ISOLATED\_LOWER}$.
In the second pass, all the subbands are explored from the $N^{\text{th}}$ level to the first one, and all their coefficients are scanned in medium-sized blocks (to take profit from data locality). For each coefficient in a subband, if it is a lower-tree root or an isolated lower, the corresponding $\text{LOWER}$ or $\text{ISOLATED\_LOWER}$ symbol is output. On the other hand, if the coefficient has been labeled as $\text{LOWER\_COMPONENT}$ no output is needed because this coefficient is already represented by another symbol.
A significant coefficient is coded in a similar way as in Algorithm I. A symbol indicating the number of bits required to represent that coefficient is arithmetically
coded, and the coefficient bits and sign are raw coded. However, two types of numeric symbols are used according to the coefficient offspring. A regular numeric symbol \( nbits_{i,j} \) simply shows the number of bits needed to encode a coefficient, but a special lower numeric symbol \( nbits_{i,j}^{\text{LOWER}} \) not only indicates the number of bits of the coefficient, but also the fact that all its descendants are labeled as \textit{LOWER COMPONENT}, and thus they belong to a not yet codified lower-tree. In this way, this type of symbol is able to represent efficiently some special lower-trees, in which the root coefficient is significant and the rest of coefficients are insignificant. Notice that the number of symbols needed to represent both set of numeric symbols is \( 2 \times (\text{maxplane} - \text{rplanes}) \), therefore the arithmetic encoder must be initialized to handle at least this amount of symbols along with two additional symbols: the \textit{LOWER} and \textit{ISOLATED LOWER} symbols (a \textit{LOWER COMPONENT} coefficient is never encoded).
On the other hand, notice that the decoder algorithm may perform the reverse process in only one pass, without the need of calculating the symbols for the coefficients, which are directly input from the encoder side.
Further adjustments may improve the compression performance of the algorithm, as for example, simple context coding based on the left and the upper coefficients, and fitting the \textit{maxplane} parameter in every subband level, and hence fitting the number of symbols needed in the arithmetic encoder.
5. COMPARISON WITH OTHER WAVELET CODERS USING REAL IMPLEMENTATIONS
We have implemented this Lower-Tree Wavelet (LTW) encoder and decoder algorithms in order to test its performance. It has been implemented using standard C++ language, and all the simulation tests have been performed on a regular Personal Computer. The reader can easily perform new tests using the win32 version of LTW available at http://www.disca.upv.es/joliver/LTW/LTW.zip.
In order to compare our algorithm with other wavelet encoders, the standard Lena (monochrome, 8bpp, 512x512) and café (monochrome, 8bpp, 2560x2048) images have been selected. On the one hand, the widely used Lena image (from the USC) allow us to compare it with practically all the published algorithms, because results are commonly expressed using this image. On the other hand, the café image, less blurred and more complex than Lena, has been obtained from the JPEG2000 test set and represents a typical picture that has been taken using a high quality 5-Megapixel digital camera.
Table 1 provides PSNR performance when using the Lena image. We can see as LTW outperforms the other coders, including the recently released JPEG 2000 standard, which results have been attained using JASPER [10], an official implementation included in the ISO/IEC 15444-5 standard.
Results for the café image are shown in table 2. Notice that only SPIHT and JASPER have been compared to LTW because the compiled versions of the rest of coders have not been released. In this case, the PSNR rate is still higher for our algorithm, although JASPER practically performs equally to LTW.
According to tables 1 and 2, we can deduce that LTW works better with low frequency images, due to its capability of grouping low amplitude coefficients in lower-tree structures.
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>EZW</th>
<th>SPIHT</th>
<th>Stack Run</th>
<th>Embedded Run-length</th>
<th>JASPER/ JPEG2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>n/a</td>
<td>45.07</td>
<td>n/a</td>
<td>n/a</td>
<td>44.62</td>
<td>45.46</td>
</tr>
<tr>
<td>1</td>
<td>39.55</td>
<td>40.41</td>
<td>n/a</td>
<td>40.28</td>
<td>40.31</td>
<td>40.50</td>
</tr>
<tr>
<td>0.5</td>
<td>36.28</td>
<td>37.21</td>
<td>36.79</td>
<td>37.09</td>
<td>37.22</td>
<td>37.35</td>
</tr>
<tr>
<td>0.25</td>
<td>33.17</td>
<td>34.11</td>
<td>33.63</td>
<td>34.01</td>
<td>34.04</td>
<td>34.31</td>
</tr>
<tr>
<td>0.125</td>
<td>30.23</td>
<td>31.10</td>
<td>n/a</td>
<td>n/a</td>
<td>30.84</td>
<td>31.27</td>
</tr>
</tbody>
</table>
Table 1: PSNR (dB) with different bit rates and coders using Lena (512x512)
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>SPIHT</th>
<th>JASPER/ JPEG2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>38.91</td>
<td>39.09</td>
<td>39.11</td>
</tr>
<tr>
<td>1</td>
<td>31.74</td>
<td>32.04</td>
<td>32.03</td>
</tr>
<tr>
<td>0.5</td>
<td>26.49</td>
<td>26.80</td>
<td>26.85</td>
</tr>
<tr>
<td>0.25</td>
<td>23.03</td>
<td>23.12</td>
<td>23.24</td>
</tr>
<tr>
<td>0.125</td>
<td>20.67</td>
<td>20.74</td>
<td>20.76</td>
</tr>
</tbody>
</table>
Table 2: PSNR (dB) with different bit rates and coders using Café (2560x2048)
One of the main advantages of the LTW algorithm is its lower temporal complexity. Table 3 shows as our algorithm greatly outperforms SPIHT and JASPER in terms of execution time. Our encoder is from 2.5 to 8.5 times faster than JASPER, while LTW decoder executes from 1.5 to 2.5 faster than JASPER decoder, depending on the bit-rate and the image size. In the case of SPIHT, our encoder is from 1.25 to 2.5 times faster, and the decoding process is from 2.5 to 7.5 times faster. Notice that in these tables we only have evaluated the coding or decoding process, since the used wavelet transform is the same in all the cases (the popular Daubechies 9/7 bi-orthogonal wavelet filter).
The computation of the symbols pass is only performed on the encoder side, and its temporal complexity is the same at any rate. That is what makes the LTW asymmetric at low bit rates.
### Lena coding
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>SPIHT</th>
<th>JASPER / JPEG 2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>210.4</td>
<td>278.5</td>
<td>92.4</td>
</tr>
<tr>
<td>1</td>
<td>119.4</td>
<td>256.1</td>
<td>62.4</td>
</tr>
<tr>
<td>0.5</td>
<td>72.3</td>
<td>238.2</td>
<td>46.7</td>
</tr>
<tr>
<td>0.25</td>
<td>48.7</td>
<td>223.4</td>
<td>38.9</td>
</tr>
<tr>
<td>0.125</td>
<td>36.8</td>
<td>211.3</td>
<td>34.7</td>
</tr>
</tbody>
</table>
### Lena decoding
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>SPIHT</th>
<th>JASPER / JPEG 2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>217.0</td>
<td>108.8</td>
<td>85.0</td>
</tr>
<tr>
<td>1</td>
<td>132.7</td>
<td>72.3</td>
<td>47.1</td>
</tr>
<tr>
<td>0.5</td>
<td>90.7</td>
<td>51.4</td>
<td>27.1</td>
</tr>
<tr>
<td>0.25</td>
<td>69.9</td>
<td>38.1</td>
<td>17.4</td>
</tr>
<tr>
<td>0.125</td>
<td>59.7</td>
<td>31.1</td>
<td>12.3</td>
</tr>
</tbody>
</table>
### Café coding
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>SPIHT</th>
<th>JASPER / JPEG 2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>210.4</td>
<td>278.5</td>
<td>92.4</td>
</tr>
<tr>
<td>1</td>
<td>119.4</td>
<td>256.1</td>
<td>62.4</td>
</tr>
<tr>
<td>0.5</td>
<td>72.3</td>
<td>238.2</td>
<td>46.7</td>
</tr>
<tr>
<td>0.25</td>
<td>48.7</td>
<td>223.4</td>
<td>38.9</td>
</tr>
<tr>
<td>0.125</td>
<td>36.8</td>
<td>211.3</td>
<td>34.7</td>
</tr>
</tbody>
</table>
### Café decoding
<table>
<thead>
<tr>
<th>codec\rate</th>
<th>SPIHT</th>
<th>JASPER / JPEG 2000</th>
<th>LTW</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>217.0</td>
<td>108.8</td>
<td>85.0</td>
</tr>
<tr>
<td>1</td>
<td>132.7</td>
<td>72.3</td>
<td>47.1</td>
</tr>
<tr>
<td>0.5</td>
<td>90.7</td>
<td>51.4</td>
<td>27.1</td>
</tr>
<tr>
<td>0.25</td>
<td>69.9</td>
<td>38.1</td>
<td>17.4</td>
</tr>
<tr>
<td>0.125</td>
<td>59.7</td>
<td>31.1</td>
<td>12.3</td>
</tr>
<tr>
<td>codec\rate</td>
<td>SPIHT</td>
<td>JASPER / JPEG 2000</td>
<td>LTW</td>
</tr>
<tr>
<td>-----------</td>
<td>-------</td>
<td>---------------------</td>
<td>-----</td>
</tr>
<tr>
<td>2</td>
<td>4368.7</td>
<td>7393.1</td>
<td>1663.5</td>
</tr>
<tr>
<td>1</td>
<td>2400.1</td>
<td>6907.6</td>
<td>1203.7</td>
</tr>
<tr>
<td>0.5</td>
<td>1399.3</td>
<td>6543.9</td>
<td>938.6</td>
</tr>
<tr>
<td>0.25</td>
<td>889.8</td>
<td>6246.2</td>
<td>782.8</td>
</tr>
<tr>
<td>0.125</td>
<td>626.5</td>
<td>6058.2</td>
<td>696.5</td>
</tr>
</tbody>
</table>
Table 3: Execution time comparison for Lena and café (time in Million of CPU cycles)
### 6. CONCLUSIONS
In this paper, we have presented a new wavelet image encoder based on the construction and efficient coding of wavelet lower-trees (LTW). Its compression performance is within the state-of-the-art, outperforming the typically used algorithms (SPIHT is improved in 0.2-0.4 dB, and JPEG 2000 with Lena in 0.35 dB as mean value).
However, we have shown that the main contribution of this algorithm is its lower temporal complexity. According to the image size and the bit-rate, it is able to encode an image up to 8.5 times faster than JASPER and 2.5 times faster than SPIHT.
Due to its lower temporal complexity and the lack of memory overhead, we think that the LTW is a good candidate for real-time interactive multimedia communications, allowing implementation both in hardware and in software.
### 7. REFERENCES
|
{"Source-Url": "http://www.grc.upv.es/papers/docs/dcc2k3.pdf", "len_cl100k_base": 8454, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 25190, "total-output-tokens": 9338, "length": "2e13", "weborganizer": {"__label__adult": 0.0005750656127929688, "__label__art_design": 0.0016536712646484375, "__label__crime_law": 0.00069427490234375, "__label__education_jobs": 0.000431060791015625, "__label__entertainment": 0.0002307891845703125, "__label__fashion_beauty": 0.0002639293670654297, "__label__finance_business": 0.0002923011779785156, "__label__food_dining": 0.0005164146423339844, "__label__games": 0.0008549690246582031, "__label__hardware": 0.01105499267578125, "__label__health": 0.00090789794921875, "__label__history": 0.0004911422729492188, "__label__home_hobbies": 0.00014269351959228516, "__label__industrial": 0.001140594482421875, "__label__literature": 0.00026702880859375, "__label__politics": 0.00041556358337402344, "__label__religion": 0.000964641571044922, "__label__science_tech": 0.464599609375, "__label__social_life": 9.08970832824707e-05, "__label__software": 0.020416259765625, "__label__software_dev": 0.49267578125, "__label__sports_fitness": 0.0003757476806640625, "__label__transportation": 0.0007071495056152344, "__label__travel": 0.00027108192443847656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 31549, 0.06583]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31549, 0.67022]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31549, 0.86395]], "google_gemma-3-12b-it_contains_pii": [[0, 2644, false], [2644, 6110, null], [6110, 9642, null], [9642, 12740, null], [12740, 16115, null], [16115, 18955, null], [18955, 21611, null], [21611, 24831, null], [24831, 28482, null], [28482, 31549, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2644, true], [2644, 6110, null], [6110, 9642, null], [9642, 12740, null], [12740, 16115, null], [16115, 18955, null], [18955, 21611, null], [21611, 24831, null], [24831, 28482, null], [28482, 31549, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31549, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31549, null]], "pdf_page_numbers": [[0, 2644, 1], [2644, 6110, 2], [6110, 9642, 3], [9642, 12740, 4], [12740, 16115, 5], [16115, 18955, 6], [18955, 21611, 7], [21611, 24831, 8], [24831, 28482, 9], [28482, 31549, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31549, 0.2402]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
125b948163bda4da548ae5f0b565575975f0ee3b
|
Finally, a Polymorphic Linear Algebra Language
Amir Shaikhha
Department of Computer Science, University of Oxford, UK
amir.shaikhha@cs.ox.ac.uk
Lionel Parreaux
DATA Lab, EPFL, Switzerland
lionel.parreaux@epfl.ch
Abstract
Many different data analytics tasks boil down to linear algebra primitives. In practice, for each different type of workload, data scientists use a particular specialised library. In this paper, we present Pilatus, a polymorphic iterative linear algebra language, applicable to various types of data analytics workloads. The design of this domain-specific language (DSL) is inspired by both mathematics and programming languages: its basic constructs are borrowed from abstract algebra, whereas the key technology behind its polymorphic design uses the tagless final approach (a.k.a. polymorphic embedding/object algebras). This design enables us to change the behaviour of arithmetic operations to express matrix algebra, graph algorithms, logical probabilistic programs, and differentiable programs. Crucially, the polymorphic design of Pilatus allows us to use multi-stage programming and rewrite-based optimisation to recover the performance of specialised code, supporting fixed sized matrices, algebraic optimisations, and fusion.
2012 ACM Subject Classification Software and its engineering → Domain specific languages; Computing methodologies → Linear algebra algorithms; Mathematics of computing → Automatic differentiation; Mathematics of computing → Graph algorithms; Theory of computation → Probabilistic computation
Keywords and phrases Linear Algebra, Domain-Specific Languages, Tagless Final, Polymorphic Embedding, Object Algebra, Multi-Stage Programming, Graph Processing, Probabilistic Programming, Automatic Differentiation.
Digital Object Identifier 10.4230/LIPIcs.ECOOP.2019.8
Category Pearl
Acknowledgements The authors would like to thank Jeremy Gibbons and Oleg Kiselyov for their helpful comments on draft versions of this paper. The first author was partially supported by EPFL during the preparation of this paper.
1 Introduction
It is well-known that many problems can be formulated using linear algebra primitives. These problems come from various data analytics domains including machine learning, statistical data analytics, signal processing, graph processing, computer vision, and robotics.
Despite the fact that all these workloads could use a standard unified linear algebra library, in practice many different specialised libraries are developed and used for each of these workload types [9]. This is mainly due to the performance-critical nature of such data analytics workloads: in order to satisfy their performance requirement, such workloads use hand-tuned specialised libraries implemented using either general-purpose or specialised domain-specific programming languages.
In this paper, we demonstrate the Pilatus language (Polymorphic Iterative Linear Algebra, Typed, Universal, and Staged). Pilatus is a polymorphic domain-specific language (DSL), in the sense that it can support various workloads, such as standard iterative linear algebra tasks, graph processing algorithms, logical probabilistic programs, and linear algebra
Finally, a Polymorphic Linear Algebra Language
programs relying on automatic differentiation. By default, this polymorphic nature causes a significant performance overhead. We demonstrate how to remove this overhead by using safe high-level meta-programming and compilation techniques, and more specifically multi-stage programming (MSP, or staging) [66, 65].
This paper uses the tagless final approach [36, 10] (also known as polymorphic embedding [30] and object algebras [48]) in order to embed [32] the Pilatus DSL in the Scala programming language. This technique allows embedding an object language in a host language in a type-safe manner. In addition, this approach allows multiple semantics for the embedded DSL (EDSL). Based on this feature and by carefully choosing the abstractions involved in defining Pilatus (such as semi-ring/ring, module, and linear map structures), we provide several evaluation semantics. More specifically, we allow several variants of a linear algebra language, such as: a standard matrix algebra language, a graph language for expressing all-pairs reachability and shortest path problems, a logical probabilistic programming language, and a differentiable programming language. The polymorphic aspect of Pilatus is also essential for the seamless application of staging, and to express different optimised staged variants: fixed size matrices, deforestation [67, 25, 63, 13], and algebraic optimisations.\footnote{We used Scala as the implementation language for Pilatus, but other programming languages with support for lambda expressions and multi-stage programming could be used as well; most of the techniques presented in this paper can also be implemented in Haskell, OCaml, and Java for example. For expressing rewrite-based optimisations, either the multi-stage programming framework should support code inspection (as is the case with Squid [51], which we use), or the developer is responsible for implementing/extend the intermediate representations (as with frameworks like LMS [57]).}
Next, we motivate the need for Pilatus (Section 2), and we make the following contributions:
- We present Pilatus, a polymorphic EDSL in Section 3. This DSL uses the notion of semi-rings and rings (Section 3.2) in order to define operations on each individual element of a vector and a matrix. Furthermore, Pilatus uses the notion of pull arrays (Section 3.5) for defining a collection (or array) of elements.
- We present four different languages that are implemented by providing a concrete interpreter for Pilatus in Section 5: (1) a standard matrix algebra language (Section 5.1); (2) a graph DSL (Section 5.2); (3) a logical probabilistic linear algebra language (Section 5.3); and (4) a differentiable linear algebra language (Section 5.4).
- We present our use of multi-stage programming to improve the performance of Pilatus programs by creating a staged language (Section 6.2) for fixed size matrices (Section 6.5), performing algebraic optimisations (Section 6.4), and performing fusion (Section 6.6).
- We show the impact of using multi-stage programming on the performance of applications written using Pilatus in Section 7. Overall, the implementation of Pilatus consists of around 400 LoC supporting all the features presented in this paper. Pilatus uses the Squid [51] type-safe meta-programming framework for its multi-stage programming facilities, which is the only external library dependency.
Finally, we present the related work in Section 8 and conclude the paper in Section 9.
2 Motivation
Apart from standard matrix algebra tasks, many numerical workloads in various domains can be expressed using linear algebra primitives [17]. Among such examples are various graph
\footnote{We used Scala as the implementation language for Pilatus, but other programming languages with support for lambda expressions and multi-stage programming could be used as well; most of the techniques presented in this paper can also be implemented in Haskell, OCaml, and Java for example. For expressing rewrite-based optimisations, either the multi-stage programming framework should support code inspection (as is the case with Squid [51], which we use), or the developer is responsible for implementing/extend the intermediate representations (as with frameworks like LMS [57]).}
problems such as reachability and shortest path. Figure 1 shows as example the reachability
problem on both deterministic and probabilistic graphs.
Despite the expressiveness of linear algebra, there are many different libraries specialized
for each particular data analytics task. This is because of two main reasons. First, most
existing linear algebra libraries do not define the interfaces for extending their usage for the
problems in other domains. Second, despite some efforts on providing abstract and extensible
linear algebra libraries [17], such analytical tasks are performance critical. As a result, there
should be hand-tuned and specialized libraries for each particular task. As an example, for
graph problems, rather than having the linear-algebra-based solutions presented in Figure 1,
the library developers prefer to provide specialized graph libraries for performance reasons.
This paper aims to solve both these issues by combining ideas from mathematics and
programming languages. The first issue is tackled by defining a polymorphic linear algebra
language by using abstractions from abstract algebra, including the ring, module, and linear
map structures for expressing scalar values, a vector of values, and a matrix of values,
respectively. Furthermore, for implementing these abstract interfaces, we use the tagless-final
approach [10, 36], a well-known technique from the programming language community.
The examples of Figure 1 show matrices of elements of various types, for which the
addition and multiplication operations can be assigned various meanings. Figure 1a shows
the usage of linear algebra primitives for expressing graph reachability problems. To do so, the
addition and multiplication operators are instantiated to boolean disjunction and conjunction,
respectively. For expressing the reachability problems on probabilistic graphs, these two
operators are instantiated with the disjunction and conjunction on boolean distributions,
as shown in Figure 1b. Finally, Figure 1c shows the process of computing the derivative
of an example matrix expression with respect to a given variable. To do so, each element
of the matrix should be represented as a pair of numbers, known as dual numbers, where
the first component is the actual value of that expression and the second component is the
value of its derivative with respect to the given variable. As an example, the dual number
representation for the element of the second row and third column is represented as \(3 \Delta 2\), meaning
that the actual value of this element at \(x = 2\) is \(2x - 1 = 3\), whereas its derivative value is
\((2x - 1)' = 2\). Similarly, the addition and multiplication operators are instantiated with the
corresponding ones operating on dual numbers, which implement the derivative rules.
All of these use cases can be easily represented as Pilatus programs, parameterized over
the meaning one wants to use for a particular domain.
The second issue is the performance overhead caused by the polymorphic nature of
the language, due to the abstractions introduced in order to solve the first issue. We use
multi-stage programming (also known as staging) to compile away the overhead corresponding
to these abstractions. Moreover, by using a staging framework with support for rewriting,
we can also implement algebraic optimization rules for further improving performances.
Next, we give more details on the design of Pilatus.
## 3 Pilatus Design
In this section, we first give an overview of the tagless final approach. Then, we define the
polymorphic interface for the semi-ring and ring structures. Afterwards, we show an abstract
interface for vectors and matrices using the mathematical notions of modules and linear
maps. Finally, we define the interface for a functional encoding of an array of elements and
control-flow constructs.
The reachability problem in a graph can also be expressed using matrix-matrix multiplication of the adjacency matrix of a graph. Instead of using the standard addition operator, here we use the boolean disjunction, and instead of the multiplication operator, we use the boolean conjunction.
(a) The reachability problem in a graph can be expressed using matrix-matrix multiplication of its adjacency matrix. Each element of the adjacency matrix represents the presence of a node with probability \( p \). The addition and multiplication operators correspond to disjunction and conjunction of two boolean distributions, respectively.
(b) The reachability problem in a probabilistic graph can also be expressed using matrix-matrix multiplication of its adjacency matrix. Each element of the adjacency matrix represents the presence of a node with probability \( p \). The addition and multiplication operators correspond to disjunction and conjunction of two boolean distributions, respectively.
\[
f(x) = \begin{bmatrix} 0 & 0 & x+3 \\ 8 & 0 & 2x-1 \\ 0 & 0 & x \end{bmatrix}^2 = \begin{bmatrix} 0 & 3x+3 & x^2+3x \\ 0 & 6x^2+3x-3 & 6x+8 \\ 24x+24 & 6x^2+3x-3 & 18x+18 \end{bmatrix}
\]
\[
f'(x) = \begin{bmatrix} 0 & 3 & 2x+3 \\ 0 & 12x+3 & 6 \\ 0 & 12x+3 & 18 \end{bmatrix}
\]
\[
f(x) = \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} \cdot \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix} = \begin{bmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{bmatrix}
\]
(c) The derivative of a matrix with respect to the variable \( x \) can also be expressed using linear algebra operations. The dual number technique represents each element of a matrix as the pair \( v \oplus d \) of the actual value \( v \) and the value of its derivative \( d \). Accordingly, the addition and multiplication operators are the corresponding ones on dual numbers.
**Figure 1** Example of problems expressed using different interpretations of linear algebra primitives.
3.1 Tagless Final
Tagless final [10, 36] (also known as polymorphic embedding [30] and object algebras [48] in the context of object-oriented programming languages) is a type-safe approach for embedding domain-specific languages. This approach solves the expression problem [68] by encoding each DSL construct as a separate function, and leaving their interpretation abstract.
There are different ways of implementing this approach: (1) in languages like Haskell, one can use type classes [10, 36]; (2) in OCaml, one can use the module system [10, 37]; (3) in languages like Java, one can use the object-oriented features [48]; and (4) in Scala one can use either type classes or mixin composition (also known as the cake pattern) [30, 57].
In this paper, we follow the approach based on type classes. Consider a DSL with two constructs, one for creating an integer literal, and the other for adding two terms. The tagless final interface for this DSL is as follows:
```scala
trait SimpleDSL[Repr] {
def lit(i: Int): Repr
def add(a: Repr, b: Repr): Repr
}
```
The code above defines a trait (similar to an interface in Java or a module signature in ML). The `SimpleDSL` trait is parameterised with a `Repr` type, which is the type of the objects manipulated by the DSL. This trait contains one abstract method for each construct of the DSL, here `lit` and `add`.
For convenience, we also typically define free-standing functions for writing programs in the DSL while omitting the particular DSL implementation used:
```scala
def lit[Repr](i: Int) (implicit dsl: SimpleDSL[Repr]): Repr = dsl.lit(i)
def add[Repr](a: Repr, b: Repr)(implicit dsl: SimpleDSL[Repr]): Repr = dsl.add(a, b)
```
These functions require an implicit instance of the `SimpleDSL` trait, and redirect to the implementations of the corresponding methods in that instance. In Scala, implicit parameters need not be specified by users at each call site; indeed, they can be filled in automatically by the compiler, based on their expected type. Implicits are the mechanism used to implement type classes in Scala [49].
One can then define generic programs in the DSL, as follows:
```scala
def myProgram[Repr](implicit dsl: SimpleDSL) = add(lit(2), lit(3))
```
Which can also be written using the following shorthand syntax:
```scala
def myProgram[Repr: SimpleDSL] = add(lit(2), lit(3))
```
Then, one can specify a particular evaluation semantic for this program. As an example, the following type class instance defines an evaluator/interpreter for `SimpleDSL`:
```scala
implicit object SimpleDSLInter extends SimpleDSL[Int] {
def lit(i: Int): Int = i
def add(a: Int, b: Int): Int = a + b
}
```
Evaluating the example program above in the REPL with this evaluation semantics, which is automatically picked up by the compiler based on the requested type `Int`, results in:
```
scala> myProgram[Int]
result: Int = 5
```
Finally, a Polymorphic Linear Algebra Language
```scala
trait SemiRing[R] {
def add(a: R, b: R): R
def mult(a: R, b: R): R
def one: R
def zero: R
}
trait Ring[R] extends SemiRing[R] {
def neg(a: R): R
def sub(a: R, b: R): R = add(a, neg(b))
}
object Pilatus {
def add[R](a: R, b: R)(implicit sr: SemiRing[R]): R = sr.add(a, b)
// ... other boilerplate methods elided for brevity
}
```
Figure 2 The tagless final interface for semi-rings and rings.
Rather than directly evaluating DSL programs, one can also represent the programs as strings. Below is a type class instance that stringifies programs in our DSL:
```scala
implicit object SimpleDSLStringify extends SimpleDSL[String] {
def lit(i: Int): String = i.toString
def add(a: String, b: String): String = s"$a + $b"
}
```
Evaluating the same program with the stringification evaluation semantic results in:
```
scala> myProgram[String]
result: String = "2 + 3"
```
**Pilatus** defines a separate type class for each category of the language constructs (e.g., semi-rings, rings, modules, linear maps, etc.), as we show next. We will introduce different evaluation semantics for this DSL by providing type class instances. These evaluation semantics are both interpretation-based (cf. Section 5) and compilation-based (cf. Section 6).
### 3.2 Semi-Ring and Ring
A semi-ring is defined as a set of numerical values $R$, with two binary operators $+$ and $\times$, and two elements $0$ (additive identity) and $1$ (multiplicative identity), such that for all elements $a, b,$ and $c$ in $R$ the following properties hold:
- $a + 0 = a$
- $a + b = b + a$
- $(a + b) + c = a + (b + c)$
- $a \times 1 = 1 \times a = a$
- $a \times 0 = 0 \times a = 0$
- $(a \times b) \times c = a \times (b \times c)$
- $a \times (b + c) = (a \times b) + (a \times c)$
- $(a + b) \times c = (a \times c) + (b \times c)$
---
2 String interpolation syntax `s"...$x$..."` is equivalent to `"...+ x + "..."`.
---
A ring is a semi-ring with an additional additive inverse operator (\(-\)) such that for all elements \(a\) in \(R\), \(a + (-a) = 0\). The binary operator for subtraction can be easily defined as \(a - b = a + (-b)\).
The tagless final encoding of semi-rings and rings is shown in Figure 2. There are six DSL constructs corresponding to addition, multiplication, negation, subtraction, one, and zero. These methods are redirected to the implementation of the corresponding operations of the SemiRing and Ring type classes. The implementation of the methods of these type classes are left abstract. These definitions will be given by each concrete semantics, which should make sure that the aforementioned properties hold for the elements of type \(R\).
### 3.3 Module
A mathematical module is a generalization of the notion of a vector space. A module over a particular semi-ring is realised using an addition operator for two modules (similar to vector addition), and a multiplication between a semi-ring element and the module (similar to scalar-vector multiplication). For all elements \(a\) and \(b\) in a semi-ring \(R\) with the multiplicative identity \(1_R\), and the elements \(u\) and \(v\) in a (left-)module \(M\), the following properties hold:
\[
\begin{align*}
a \cdot (u + v) &= a \cdot u + a \cdot v \\
(a + b) \cdot u &= a \cdot u + b \cdot u \\
(a \times b) \cdot u &= a \cdot (b \cdot u) \\
1_R \cdot u &= u
\end{align*}
\]
Additionally, the dimension of a finite module generalises the notion of the number of basis vectors\(^3\) representing a vector.
Figure 3 shows the tagless final interface for modules. The Module type class has three type parameters: (1) \(V\) specifies the type of the underlying vector representation; (2) \(R\) specifies the type of each element of the vector; and (3) \(D\) specifies the type of the dimension of the underlying vector. Note that all the elements of type \(R\) and \(D\) support semi-ring operations, thanks to the two type class instances \(sr\) and \(dr\). Furthermore, the Module type class supports the following operations: (1) the \texttt{dim} method returns the dimension of the given module; (2) the \texttt{add} method computes the result of the addition of two module elements; and (3) the \texttt{smult} method computes the multiplication of a semi-ring element and a given module.
### 3.4 Linear Map
A linear map is a transformation between two modules, which preserves the addition and the scalar multiplication operations of the given module. Assume the linear map \(M\) transforming module \(V\) to module \(W\), and both modules are over the semi-ring \(R\). Then for all elements \(f\) in the linear map \(M\), \(u\) and \(v\) from module \(V\), and \(a\) from the semi-ring \(R\), the following properties hold:
\[
\begin{align*}
f(u + v) &= f(u) + f(v) \\
f(a \cdot u) &= a \cdot f(u)
\end{align*}
\]
\(^3\) The basis vectors are linearly independent vectors (none of them can be expressed as a linear combination of the other ones) that can be used to express every vector as a unique linear combination of them.
Finally, a Polymorphic Linear Algebra Language
```scala
trait Module[V, R, D] {
implicit val sr: SemiRing[R]
implicit val dr: SemiRing[D]
def dim(a: V): D
def add(a: V, b: V): V
def smult(s: R, a: V): V
}
object Pilatus {
// ...
def dim[V, D](a: V)(implicit m: Module[V, _, D]): D = m.dim(a)
// ... other boilerplate methods elided for brevity
}
```
Figure 3 The tagless final interface for modules.
```scala
trait LinearMap[M, V, R, D] {
implicit val rowModule: Module[V, R, D]
implicit val sr: SemiRing[R]
implicit val dr: SemiRing[D]
def apply(m: M, v: V): V
def compose(m1: M, m2: M): M
def add(m1: M, m2: M): M
def dims(mat: M): (D, D)
}
object Pilatus {
// ...
def apply[M, V](m: M, v: V)(implicit lm: LinearMap[M, V, _, _]): V = lm.apply(m, v)
// ... other boilerplate methods elided for brevity
}
```
Figure 4 The tagless final interface for linear maps.
Similar to functions, linear maps have two operations. First, a linear map can be applied to a module returning a transformed module, behaving similar to the function application. Second, a linear map can be composed with another linear map resulting in another linear map, behaving similarly to function composition.
Figure 4 shows the tagless final encoding of linear maps. Here, we only consider finite linear maps transforming two finite modules, and we assume that both modules are over the same semi-ring (represented with type R, and the sr type class instance) with the same module type representation (represented with the type V). From a vector/matrix point of view, the compose and apply methods correspond to the matrix-matrix and matrix-vector multiplication, respectively. The add method corresponds to the matrix addition operator, and the dims construct returns the dimension of the input and output modules, which is represented as a tuple.
### 3.5 Pull Array and Control-Flow Constructs
Using a pull array is a well-known approach in the high-performance functional programming community for a functional encoding of arrays [64, 2, 12]. In this representation, an array is defined using two components: (1) the length of the array; and (2) a function mapping an index to the value of the corresponding element in that array.
trait PullArrayOps[A, E, L] {
def build(len: L)(f: L => E): A
def get(arr: A)(i: L): E
def length(arr: A): L
}
trait Looping[L] {
def forloop[S](z: S)(n: L)(f: (S, L) => S): S
}
object Pilatus {
// ...
// ... other boilerplate methods elided for brevity
}
Figure 5 The tagless final interface for pull arrays and control-flow constructs.
Figure 5 demonstrates the tagless final encoding of pull arrays and looping constructs. The build method is responsible for constructing a pull array of size len, in which the $i^{th}$ element is $f(i)$, indexed from 0 to len - 1. The get method returns the $i^{th}$ element of the array arr, whereas the length method returns the size of the given array. Finally, the forloop method is meant for implementing recursion and iteration. More specifically, this function starts from the state $z$, iterates $n$ times (from 0 to n - 1), and at the $i^{th}$ step, updates the state $s$ with $f(s, i)$.
4 Matrix Algebra
In this section, we build the constructs of matrix algebra based on the mathematical notions explained in the previous section. First, we show the construction of vector constructs using modules and pull arrays. Then, we demonstrate the matrix constructs by using linear maps and vectors.
4.1 Vector: Module + Pull Array
A vector (more specifically, a dense vector where most elements are non-zero) can be seen as a module the elements of which are stored as a pull array. Given that each element of a vector form a semi-ring, we can define the addition, element-wise multiplication, and dot product of two vectors.
The implementation for the tagless final encoding of a vector, as well as the mentioned methods are given in Figure 6. The $V$ type parameter specifies the underlying vector type representation, the $R$ type parameter specifies the type of each element of the vector, and the $D$ type parameter is the type of the dimension of the underlying vector.
The zipMap method, receives two vectors $v1$ and $v2$ as input and creates a vector of the same size,\(^4\) for which each element is constructed by applying the binary operator $\bigoplus$ on the corresponding elements from $v1$ and $v2$. The add and elemMult are constructed by passing the addition and multiplication functions of the underlying semi-ring of elements to the zipMap method. The map method applies a given function to each element of the input
\(^4\) We assume that the input vectors have the same size for the sake of simplicity. In practice, this property can be enforced statically using Scala’s powerful implicit programming capabilities, and singleton types.
Finally, a Polymorphic Linear Algebra Language
```scala
implicit val pa: PullArrayOps[V, R, D]
implicit val looping: Looping[D]
def dim(a: V): D = pa.length(a)
def add(v1: V, v2: V): V = zipMap(v1, v2, sr.add)
def smult(s: R, a: V): V = map(a, e => sr.mult(s, e))
def map(v: V, op: R => R): V = pa.build(pa.length(v))(i => op(pa.get(v)(i)))
def zipMap(v1: V, v2: V, op: (R, R) => R): V = pa.build(pa.length(v1))(i => op(pa.get(v1)(i), pa.get(v2)(i)))
def elemMult(v1: V, v2: V): V = zipMap(v1, v2, sr.mult)
def dot(v1: V, v2: V): R =
looping.forloop(sr.zero)(pa.length(v1))((acc, i) =>
sr.add(acc, sr.mult(pa.get(v1)(i), pa.get(v2)(i))))
/* sum and norm are omitted for brevity */
}
```
Figure 6 The tagless final implementation for (dense) vectors.
vector and produces a vector of the same size with the transformed elements as output. The `smult` method is implemented using this method. Finally, the `dot` method computes the dot product of two vectors `v1` and `v2` by first computing the element-wise multiplication of these vectors, and then adding the elements of the intermediate vector.
Next, we use the mentioned vector data structure together with linear maps in order to define a matrix data-structure.
4.2 Matrix: Linear Map + Vector
Figure 7 shows the implementation of matrices (more specifically, dense matrices) using linear maps and vectors. The `M` type parameter specifies the type of the underlying matrix representation, `V` represents the type of each row-vector and column-vector of the matrix, `R` denotes the type of each element of the matrix, and `D` specifies the type of the dimension of each row and each column of the matrix.
In order to facilitate usages of the generic library, we have implemented several helper methods. The `get` method returns the corresponding element in the `r`th row and `c`th column of the matrix. The `numRows` and `numCols` methods return the number of rows and columns of a matrix, respectively. The `getRow` method returns the vector representing the `r`th row of the given matrix, whereas `getCol` returns a vector containing the elements in the `c`th column of the given matrix. Finally, the `zipMap` and `map` methods have similar behaviour to the methods with the same name from the vector data type.
The `add` method returns the result of the addition of two matrices, which is implemented using the `zipMap` method. The `mult` method returns the matrix-matrix multiplication of two matrices. This method is implemented by performing a vector dot-product of each row of the first matrix with each column of the second matrix. Finally, the `transpose` method returns the transpose of the given matrix.
---
5 As we will see in Section 6, `r` and `c` can have types other than `Int`.
implicit val paMat: PullArrayOps[M, V, D]
implicit val vector: Vector[V, R, D]
/* Other implicit values: paRow, rowModule, looping, dr, sr */
/* apply and compose methods use the mult method, elided for brevity. */
def get(mat: M, r: D, c: D): R = paRow.get(paMat.get(mat)(r))(c)
def numRows(mat: M) = dims(mat)._1
def numCols(mat: M) = dims(mat)._2
def getRow(mat: M, i: D): V = paMat.get(mat)(i)
def getCol(mat: M, j: D): V = getRow(transpose(mat), j)
def zipMap(m1: M, m2: M, bop: (R, R) => R): M =
paMat.build(numRows(m1))(i =>
paRow.build(numCols(m1))(j =>
bop(get(m1, i, j), get(m2, i, j))))
def add(m1: M, m2: M): M = zipMap(m1, m2, sr.add)
def mult(m1: M, m2: M): M =
paMat.build(numRows(m1))(i =>
paRow.build(numCols(m2))(j =>
vector.dot(getRow(m1, i), getCol(m2, j))))
def transpose(mat: M): M =
paMat.build(numCols(mat))(i =>
paRow.build(numRows(mat))(j => get(mat, j, i)))
/* map, eye, fill, and zeros are omitted for brevity */
}
Figure 7 The tagless final implementation for (dense) matrices.
trait Printable[T] {
def string(e: T): String
}
object Pilatus {
// ...
def getString[T](e: T)(implicit p: Printable[T]) = p.string(e)
}
Figure 8 The tagless interface for the stringification of the values of different evaluation semantics.
4.3 Putting It All Together
Before showing different evaluation semantics in the upcoming sections, we need a way to print the result values. To do so, we define the Printable type class which converts the value of a particular type into a string. Figure 8 shows the corresponding tagless final definition.
Example. Throughout this paper, we use the following example matrix program, where we change the values for matrix m based on the evaluation semantic that we are interested in:
```scala
def example[M, D](m: M)(implicit mev: Matrix[M, _, _, D], pev: Printable[M]): Unit = {
import mev._
val I = eye(numRows(m))
val m2 = mult(m, m)
val res = add(I, add(m, m2))
println(getString(res))
}
```
This program accepts the matrix m, the value of which differs based on the evaluation semantic
Finally, a Polymorphic Linear Algebra Language
```scala
implicit object RingInt extends Ring[Int] {
def add(a: Int, b: Int) = a + b
def mult(a: Int, b: Int) = a * b
def one: Int = 1
def zero: Int = 0
def neg(a: Int): Int = -a
}
implicit object RingDouble extends Ring[Double] {
/* Similar to RingInt */
}
```
Figure 9 The tagless final interpreter (a.k.a. type class instances) for a ring of integer and double values.
that we would like to use. The result of this program is the addition of the identity matrix (represented using the `eye` method), the given input matrix, and the second power of it. In the next sections, we give several concrete interpretations for Pilatus, and we show the output of the example program above for each of the interpretations.
5 Interpreted Languages
In this section, we first show an evaluation strategy which results in a standard matrix algebra library. Then, we show how we can define an alternative interpretation which leads to treating Pilatus as a graph library. Afterwards, we show a linear algebra library for logical probabilistic programming. Finally, we demonstrate how Pilatus can behave as a library for differentiable programming.
5.1 Standard Matrix Algebra
In order to define a standard matrix algebra library for Pilatus, we start by defining a normal interpreter for rings. Figure 9 shows the interpretation for a ring of integer and double values. In both cases, the addition and multiplication operations are defined using the primitive operations provided by the Scala language.
Figure 10 shows an interpreter for pull arrays, where every constructed pull array is materialised into an array of elements. Hence, retrieving an element and returning the size of the pull array is achieved by returning the corresponding element in the materialised array and the length of the array, respectively. Finally, the implementation of `forloop` is achieved by performing a `foldLeft` on the range of elements from 0 to n-1, and passing the initial state and the accumulator function.
An alternative way of interpretation for pull arrays, which avoids the materialisation of the intermediate arrays into a sequence, keeps a data structure which holds the length and the constructor function of each element. This representation is given in Figure 11.
**Example.** The standard matrix algebra interpreter evaluates the example program as follows:
```scala
import Semantics.{ pullArrayInterOps, loopingInt, ringInt }
val adj = Array(Array(0, 0, 1, 5),
Array(8, 0, 3, 6),
Array(0, 9, 0, 0),
Array(0, 0, 2, 0))
val m = build(4)(i => build(4)(j => adj(i)(j)))
```
class PullArrayArrayOps[E: ClassTag] extends PullArrayOps[Array[E], E, Int] {
def build(len: Int)(f: Int => E): Array[E] =
Array.tabulate(len)(f)
def get(arr: Array[E])(i: Int): E =
arr(i)
def length(arr: Array[E]): Int =
arr.length
}
class LoopingInt extends Looping[Int] {
def forloop[S](f: (S, Int) => S)(z: S)(n: Int): S =
(0 until n).foldLeft(z)(f)
}
object Semantics {
implicit def pullArrayArrayOps[E: ClassTag] =
new PullArrayArrayOps[E]
implicit val loopingInt = new Looping[Int]
}
Figure 10 The tagless final interpreter for a pull array, represented as a list of elements, and the control-flow constructs.
case class PullArrayInter[E](len: Int, f: Int => E)
class PullArrayInterOps[E] extends PullArrayOps[PullArrayInter[E], E, Int] {
def build(len: Int)(f: Int => E): PullArrayInter[E] =
PullArrayInter(len, f)
def get(arr: PullArrayInter[E])(i: Int): E =
arr.f(i)
def length(arr: PullArrayInter[E]): Int =
arr.len
}
object Semantics {
// ...
implicit def pullArrayInterOps[E] =
new PullArrayInterOps[E]
}
Figure 11 The tagless final interpreter for a pull array, represented as a pair of length and the element constructor function.
element(m)
// output:
[[ 1, 9, 11, 5 ],
, [ 8, 28, 23, 46 ],
, [ 72, 9, 28, 54 ],
, [ 0, 18, 2, 1 ] ]
Note that the build method is redirected to the build method of the PullArrayOps type class (cf. Figure 5).
5.2 Graph DSL for Reachability and Shortest Path
A directed graph can be represented using its adjacency matrix. More specifically, a graph with \( n \) vertices can be represented using a matrix of size \( n \times n \), in which all elements are Boolean. If the element in the \( i^{th} \) row and \( j^{th} \) column is true, this means that there is an edge between the \( i^{th} \) and \( j^{th} \) vertices in the graph.
Finally, a Polymorphic Linear Algebra Language
```scala
class SemiRingBoolean extends SemiRing[Boolean] {
def add(a: Boolean, b: Boolean) = a || b
def mult(a: Boolean, b: Boolean) = a && b
def one: Boolean = true
def zero: Boolean = false
}
```
```scala
object Semantics {
implicit val semiRingBoolean = new SemiRingBoolean{
// ...
}
}
```
**Figure 12** The tagless final interpreter for a semi-ring of Boolean values, used for expressing graph reachability problems.
In order to support such adjacency matrices, we need to use the Boolean semi-ring for the matrix elements. Figure 12 shows the implementation of the Boolean semi-ring, in which addition performs disjunction, and multiplication performs conjunction.
Using the Boolean semi-ring for the elements of a matrix leads to a graph library. This instantiation of Pilatus is appropriate for expressing reachability computations among all vertices of a graph: given an adjacency matrix $M$, each element of $M \times M$ shows the existence of a path of length 2 between the two vertices in the corresponding graph.
The graph algorithms that can be implemented on top of Pilatus are not limited to reachability ones. By adding other types of semi-rings, one can express other graph computation problems. As an example, Tropical semi-rings can express shortest-path graph problems [45, 17]. Figure 13 shows the tagless final encoding of Tropical semi-rings. The `ShortestPath` data type represents the path between two nodes of a graph, where `Unreachable` specifies a path of length $+\infty$, and `Distance(v)` specifies a path of length $v$. The Tropical semi-ring computes the minimum length of two paths as the addition operator of the semi-ring, and adds the length of two paths as the multiplication operator. We omit the definition for other semi-rings for graph and other similar problems (e.g., linear equations, data-flow analysis, petri nets, etc., which are already explored in the literature [17]).
**Example.** When one uses the Boolean semi-ring, the example program is actually computing the existence of paths with maximum length two among all the nodes. When we provide the adjacency matrix of the graph of Figure 1a, the example program evaluates to:
```scala
import Semantics.{ pullArrayInterOps, loopingInt, ringInt, semiRingBoolean }
val adj = Array(Array(false, false, true, true),
Array(true, false, true, true),
Array(false, true, false, false),
Array(false, false, true, false))
val m = build(4)(i => build(4)(j => adj(i)(j)))
example(m)
// output:
[ [ T, T, T, T ]
, [ T, T, T, T ]
, [ T, T, T, T ]
, [ F, T, T, T ] ]
```
sealed trait ShortestPath {
def add(o: ShortestPath): ShortestPath = (this, o) match {
case (Unreachable, x) => Unreachable
case (x, Unreachable) => Unreachable
case (Distance(v1), Distance(v2)) => Distance(v1 + v2)
}
def min(o: ShortestPath): ShortestPath = (this, o) match {
case (Unreachable, x) => x
case (x, Unreachable) => x
case (Distance(v1), Distance(v2)) => Distance(math.min(v1, v2))
}
}
case class Distance(v: Int) extends ShortestPath
case object Unreachable extends ShortestPath
class SemiRingTropical extends SemiRing[ShortestPath] {
def add(a: ShortestPath, b: ShortestPath) = a.min(b)
def mult(a: ShortestPath, b: ShortestPath) = a.add(b)
def one: ShortestPath = Distance(0)
def zero: ShortestPath = Unreachable
}
object Semantics {
// ...
implicit val semiRingTropical = new SemiRingTropical
}
Figure 13 The tagless final interpreter for a semi-ring of Boolean values, used for expressing graph shortest-path problems.
5.3 Probabilistic Linear Algebra Language
Probabilistic models are used in many applications including artificial intelligence, machine learning, cryptography, and economics. Probabilistic programming languages have proven to be successful for expressing such stochastic models in a declarative style without worrying about computational aspects [11, 28, 27, 39]. As an example, an important computer vision application was recently expressed in only 50 lines of code in the Picture probabilistic programming language [40].
In this paper, our aim is not to make PILATUS a full-fledged probabilistic programming language. Instead, we show how we can encode Boolean probability distributions in PILATUS in the form of a semi-ring. This means that we support the conjunction and disjunction between two Boolean distributions. Also, the zero and one elements of the semi-ring correspond to the distribution with the probability of one for false and true, respectively. As a side effect of the compositional design of PILATUS, we can support vectors and matrices of such distributions as well, virtually for free. Thus, PILATUS supports probabilistic graphs and the associated path queries, similar to systems such as ProbLog [15].
Figure 14 shows the tagless final implementation for Boolean distributions. The BoolProb data type has a list of probabilities assigned to each Boolean value. This data type is actually a probability monad [26, 19]. As is customary with monad implementation in Scala, the flatten method represents the bind operator of the monad, and the apply method of the companion object represents the unit operator. The normalise method makes sure that the list of probabilities associated to each Boolean value has distinct Boolean values, and that
Finally, a Polymorphic Linear Algebra Language
case class BoolProb(l: List[(Boolean, Double)]) {
def flatMap(f: Boolean => BoolProb): BoolProb = {
val ll = for (x <- l; y <- f(x._1).l) yield (y._1 -> (y._2 * x._2))
BoolProb(ll).normalise()
}
def normalise(): BoolProb = {
val sum = l.map(_._2).sum
val nl = l.groupBy(_._1).mapValues(_.map(_._2).sum / sum)
BoolProb(nl.toList)
}
}
object BoolProb {
def apply(v: Boolean): BoolProb = BoolProb(List(v -> 1.0))
}
class SemiRingBoolProb extends SemiRing[BoolProb] {
def add(a: BoolProb, b: BoolProb) = a.flatMap(x =>
if (x) one else b)
def mult(a: BoolProb, b: BoolProb) = a.flatMap(x =>
if (x) b else zero)
def one: BoolProb = BoolProb(true)
def zero: BoolProb = BoolProb(false)
}
object Semantics {
// ...
implicit val semiRingBoolProb = new SemiRingBoolProb
}
Figure 14 The tagless final implementation using the Boolean probability monad for semi-ring operations.
There are many alternative implementations for the probability monad such as lazy trees [39] with the possibility to support distributions for values other than Booleans. Furthermore, in this context one can use various optimisations such as variable elimination [16]. Finally, it is possible to explore other inference mechanisms [42]. All these aspects are orthogonal to the purposes of this work, and PILATUS can be extended to support all these features, which we leave as exercises to the reader.
Example. When we give the adjacency matrix of the probabilistic graph of Figure 1b as the input to the example program, the evaluation is as follows:
```scala
import Semantics.{ pullArrayInterOps, loopingInt, ringInt, semiRingBoolProb }
val adj = Array(Array(flip(0), flip(0), flip(0.1), flip(0.5)),
Array(flip(0.8), flip(0), flip(0.3), flip(0.6)),
Array(flip(0), flip(0.9), flip(0), flip(0)),
Array(flip(0), flip(0), flip(0.2), flip(0)))
val m = build(4)(i => build(4)(j => adj(i)(j)))
example(m)
// output:
[[ 1, 0.1, 0.2, 0.5 ]
, [ 0.8, 1, 0.4, 0.8 ]
, [ 0.7, 0.9, 1, 0.5 ]
, [ 0, 0.2, 0.2, 1 ]]```
As in the previous section, the example program computes the all-pairs path with maximum length of two. Hence, the result matrix is the probability of the existence of a path by traversing at most one intermediate node.
5.4 Differentiable Linear Algebra DSL
Many applications in machine learning such as training artificial neural networks require computing the derivate of an objective function. In many cases, the manual derivation of analytical derivatives is not a practical solution, as it is error prone and time consuming. Hence, several techniques were developed for automating the derivation process.
Automatic differentiation (or algorithmic differentiation) is one of the most well-known techniques to systematically compute the derivative of a program. This technique systematically applies the chain rule, and evaluates the derivatives for the primitive arithmetic operations (such as addition, multiplication, etc.) [4].
Among different implementations of automatic differentiation, here we show the forward mode technique using dual numbers. In this implementation, every number is augmented with an additional component, which maintains the computed derivative value. Correspondingly, all primitive operations should be augmented with the appropriate derivation computation.
Figure 15 demonstrates the generic tagless final interface for the dual number representation of a ring. This interface uses the pair representation for dual numbers, in which the first component is the normal value, whereas the second component is the derivative value. The second component in the implementation of the addition operator reflects the addition rule of derivation \( \frac{d}{dx}(a + b) = \frac{da}{dx} + \frac{db}{dx} \), whereas the one in multiplication reflects the multiplication rule \( \frac{d}{dx}(a \times b) = \frac{da}{dx} \times b + a \times \frac{db}{dx} \).
Example. Let us consider again the example matrix given in Figure 1c. By representing this input matrix using dual numbers, our running example is evaluated as follows:
```.scala
import Semantics.{ pullArrayInterOps, loopingInt, ringInt, dualRing }
val adj = Array(Array(0 -> 0, 0 -> 0, 1 -> 0, 5 -> 1),
Array(8 -> 0, 0 -> 0, 3 -> 2, 6 -> 0),
Array(0 -> 0, 9 -> 3, 0 -> 0, 0 -> 0),
Array(0 -> 0, 0 -> 0, 0 -> 0, 0 -> 0))
```
Finally, a Polymorphic Linear Algebra Language
```scala
val m = build(4)(i => build(4)(j => adj(i)(j)))
example(m)
// output:
[ [ 1 -> 0, 9 -> 3, 11 -> 7, 5 -> 1 ]
, [ 8 -> 0, 28 -> 27, 23 -> 8, 46 -> 8 ]
, [ 72 -> 24, 9 -> 3, 28 -> 27, 54 -> 18 ]
, [ 0 -> 0, 18 -> 15, 2 -> 1, 1 -> 0 ] ]
```
More specifically, computing the square of this matrix results in:
```scala
val m2 = compose(m, m)
println(getString(m2))
// output:
[ [ 0 -> 0, 9 -> 3, 10 -> 7, 0 -> 0 ]
, [ 0 -> 0, 27 -> 27, 20 -> 6, 40 -> 8 ]
, [ 72 -> 24, 0 -> 0, 27 -> 27, 54 -> 18 ]
, [ 0 -> 0, 18 -> 15, 0 -> 0, 0 -> 0 ] ]
```
This output is the same as what we have observed in Figure 1c.
6 Staging and Optimisation
In this section, we show how to use multi-stage programming (MSP, or just staging) to improve the performance of Pilatus programs, by removing the abstraction overhead incurred by the high-level programming features we use to make our DSL polymorphic. We use Squid [51, 52], a type-safe meta-programming framework that supports MSP. Squid is implemented in Scala as a macro library, making its usage straightforward and user-friendly.
6.1 Preliminaries on Squid and Multi-Stage Programming
Squid makes use of quasi-quotes to manipulate program fragments; this way, one can both compose programs together (multi-stage programming) and pattern-match on them to perform rewritings, thereby achieving quoted staged rewriting [50].
**Quasi-quotes.** Given a Scala expression \(e\) of type \(T\), the quasi-quote expression `code"\(e\)"` has type `Code[T]` and represents a program fragment whose representation can be manipulated programmatically. Crucially, quasi-quotes may contain holes, delineated by the `{...}` escape syntax.\(^6\) When constructing a program fragment, code inside of a hole is evaluated and inserted in place of the hole. For example, `val part = code"List(1,2,3)"; code"2 * $part.length"`, which has type `Code[Int]`, evaluates to `code"2 * List(1,2,3).length"`.
**Runtime Compilation.** After composing a program at run time using quasi-quotes, one can then either dump a stringified version of the code inside a file to be compiled and run later, or runtime-compile it on the fly, using the `.compile` method, which will produce bytecode that can then be run efficiently. After the one-off cost of runtime compilation, a definition such as `val f = code"(x: Int) => x + 1".compile` will be as efficient as `val f = (x: Int) => x + 1`.
**Multi-Stage Programming (MSP).** The goal of MSP is to turn a program which contains abstractions and indirections into a code generator: instead of producing the program’s result directly, this staged program will produce code that is straightforward and free of
\(^6\) When the escaped expression is a simple identifier, one can leave out the curly braces.
abstractions, to compute the program’s result more efficiently. To achieve this, one annotates
the non-static parts of the program (those that should be executed later) using quasi-quotes
and code types. Thanks to runtime compilation, the staged program effectively partially
evaluates the fixed parts of a program even if they depend on values obtained at runtime.
**Code Pattern Matching and Rewriting.** Squid extends the classical MSP ability with
code pattern matching and rewriting (quasi-quotes are allowed in patterns), which lets
programmers inspect already-composed code fragments in a type-safe way. As we will see
in Section 6.4, in practice this saves programmers the trouble of having to define their own
inspectable program representations before turning them into code.
### 6.2 Staging Pilatus
Thanks to the polymorphic nature of Pilatus, it is quite straightforward to turn a given
semantics into a multi-stage program. All we need to do is to provide an evaluation semantics
which manipulates program fragments instead of normal values, and which composes these
fragments together instead of directly evaluating the results of each operation.
Figure 16 shows the staged versions of some of the Pilatus interfaces. A `RingCode[T]`
is a ring implementation\(^7\) that manipulates `Code[T]` ring elements (the `RingCode[T]` class
extends `Ring[Code[T]]`). The `CodeType[T]` type class is used to automatically infer runtime
type representations, which is necessary for Squid program manipulation. Notice that the
implicit `ringCode` definition takes an implicit argument of type `Code[Ring[T]]`. This works out
of the box, because Squid can turn an implicit `Ring[T]` into a `Code[Ring[T]]` automatically,
lifting the code used for generating the implicit.
As an example, consider the following polymorphic Pilatus program:
```scala
def polymorphicProgram[R: Ring](a: R, b: R): R = mult(add(a, one), b)
```
And the following two usages, one with a direct `R = Int` interpretation, and one with a staged
`R = Code[Int]` one:
```scala
import Semantics.{ ringInt }, StagedSemantics.{ ringCode }
Console.print("Enter an integer number: ")
val k = Console.readInt
val f_slow = (x: Int) => polymorphicProgram(x, k)
val f_code = (x: Code[Int]) => polymorphicProgram(x, Const(k))
val f_fast = code/quotesingle.Var /quotesingle.Var(x: Int) => ${f_code}(x)
```
The `Const` constructor turns a primitive value (here an `Int`) into a code value (here a `Code[Int]`).
Notice that we insert `f_code` into a quasi-quote even though it is not a code value, but a
function from code to code; in fact, it is implicitly lifted by Squid [51].
Assuming the user enters the number 27 on the console, the code generated at runtime for
`f_fast` will be equivalent to `(x: Int) => Semantics.ringInt.mult(Semantics.ringInt.add(x, 1), 27)` which,
after inlining of the statically-dispatched `ringInt` methods, corresponds to
`(x: Int) => (x + 1) * 27`. To understand why this is much more efficient than the `f_slow`
version, consider that the evaluation of `f_slow` has to go through virtual dispatch of all
the ring operations; moreover, it also has to use boxed representations of the manipulated
integer values due to the generic context in which ring operations are defined, which requires
\(^7\) Strictly speaking, this implementation does not form a ring, because for example `code"2+1"` is not the
same as `code"1+2"` — though they are “morally” equivalent as they represent equivalent programs.
Finally, a Polymorphic Linear Algebra Language
repeated allocations and unwrapping of boxed integers. As a result, in a realistic workload, even the just-in-time compiler will typically not manage to make that code as fast as the straightforward primitive operations performed by $f_{fast}$.
This kind of overhead easily compounds as we introduce more abstractions, to the point where non-staged abstract programs end up being orders of magnitude slower than the staged versions [72], as we will see in Section 7.
6.3 Staged Representation Optimisations
An interesting aspect of MSP is that it lets us define data structures made of partially-staged data. For example, if we want to partially evaluate the allocation of pairs and the selection of their components, we can use representations of type $(\text{Code}[A], \text{Code}[B])$ instead of $\text{Code}[(A, B)]$.
This comes in useful when representing dual numbers in our staged interpreter. We can implement an alternative to $\text{DualRing}$ that is specialised for handling code values, and define its operations accordingly, for example:
```python
def mult(a: (\text{Code}[R], \text{Code}[R]), b: (\text{Code}[R], \text{Code}[R])) =
(code"sr.mult($\text{a._1}, \text{b._1}$)",
code"sr.add($sr.mult($\text{a._1}, \text{b._2}$), $sr.mult($\text{a._2}, \text{b._1}$))")
```
Note that in the code above, we use program fragments $\text{a._1}$ and $\text{b._1}$ several times. This is fine, because the default intermediate representation that Squid uses to encode program fragment is based on the A-normal form [20], which let-binds every subexpression to a local variable, and thus avoids code duplication [51, 50]; in other words, by inserting a given code value in several places, we only duplicate variable references.
6.4 Algebraic Optimisations
Thanks to the staged interpretations of Pilatus, which allows us to manipulate program fragments as first-class values, we can leverage the algebraic properties of ring structures to perform optimisations. To do so, we can extend the staged ring implementation, so that we use the normal staged method implementations by default, and override those methods where there is a potential for algebraic optimisations. The goal of the overridden methods is to return simplified program fragments based on the shape of their inputs.
This technique is similar to the original tagless final [10] and polymorphic embedding [30] approaches to algebraic optimisation. The main difference is that thanks to Squid’s analytic capabilities, we do not need to create our own intermediate symbolic representation of programs, and instead we can pattern-match on code values directly.
An implementation of this optimised staged semantics for rings is given in Figure 17. When used in pattern position, traditional quasi-quote escapes $\{\ldots\}$, which insert code values into bigger expressions, are written $\$$\{\ldots\}$ instead.
Many more algebraic rewritings can be added to perform partial evaluation and normalization of program fragments. We have omitted them for the sake of brevity. Furthermore,
one can encode the algebraic properties of modules (cf. Section 3.3) and linear maps (cf. Section 3.4) as rewrite rules, which we leave for the future.
6.5 Fixed-Size Matrix DSL
In some applications, such as computer vision, the matrices or vectors have a small size and sometimes their size are statically known (e.g. a vector of size 3 to show a point in the 3D space). In these cases the necessary memory for the corresponding arrays can be allocated at compile time (or even stack allocated), leading to better performance and memory consumption at run time.
PILATUS can be instantiated with an evaluator that makes sure that the length of arrays is known during the compilation time. In this case, the representation of a pull array is a sequence of the symbolic representation for each element. Furthermore, the representation for its length is an integer, instead of a symbolic representation. Interestingly, this representation is the same as the one shown in Figure 10, but with the E type instantiated to multi-stage code types.
6.6 Fused DSL
Deforestation [67, 25, 63, 13] is a well-known technique used in functional languages in order to remove the unnecessary intermediate data structures. This removal has a positive effect on both memory consumption and run-time performance, thanks to the removal of unnecessary
8:22 Finally, a Polymorphic Linear Algebra Language
```scala
class SemiRingOptCode[T: CodeType](sr: Code[SemiRing[T]]) extends SemiRingCode[T](sr) {
override def add(a: Code[T], b: Code[T]) = (a, b)
match {
case (_, code$$sr.zero) => a
case (code$$sr.zero, _) => b
case _ => super.add(a, b)
}
override def mult(a: Code[T], b: Code[T]) = (a, b)
match {
case (_, code$$sr.zero) => code$$sr.zero
case (code$$sr.zero, _) => code$$sr.zero
case (_, code$$sr.one) => a
case (code$$sr.one, _) => b
case _ => super.mult(a, b)
}
}
class RingOptCode[T: CodeType](ring: Code[Ring[T]]) extends RingCode[T](ring) {
override def neg(a: Code[T]) = a
match {
case code$$ring.zero => code$$ring.zero
case _ => super.neg(a)
}
}
```
Figure 17 The tagless final encoding of the compiled library of Pilatus, which applies algebraic optimisations for the elements of matrices.
memory allocations and avoidance of unnecessary computations.
One of the key advantages of using pull arrays is providing deforestation. However, to benefit from this feature, one should provide an appropriate representation for pull arrays which avoids materialisation. This can be achieved by symbolically maintaining the length and the constructor function. Whenever the array is indexed or the length of array is needed, instead of creating a symbolic representation for them, we can use the maintained length and constructor function.
Figure 18 represents the implementation of fused pull array, and a compiler allowing deforestation for Pilatus.
7 Evaluation
In this section, we show how multi-stage programming and rewriting can make Pilatus faster than the high-level implementation, while being competitive with a handwritten low-level implementation. We use several micro benchmarks consisting of a pipeline of vector operations such as addition, dot product, and norm. Each benchmark is tested with five different approaches:
- Pilatus by using a native array without optimisation
- Pilatus by using a pull array without optimisation
- Pilatus by using a pull array with staging
- Pilatus by using a pull array with staging and fusion
- A handwritten low-level optimised implementation
The experiments are performed on a six-core Intel Xeon E5-2620 v2 processor with 256GB of DDR3 RAM (1600Mhz), with Scala version 2.12.8 running on the OpenJDK 64-Bit Server VM (build 24.95-b01) with Java 1.7.0_101.
```scala
case class PullArrayCode[E](len: Code[Int], f: Code[Int] => Code[E])
class PullArrayCodeFusedOps[E]
extends PullArrayOps[PullArrayCode[E], Code[E], Code[Int]] {
PullArrayCode(len, f)
def get(arr: PullArrayCode[E])(i: Code[Int]): Code[E] =
arr.f(i)
def length(arr: PullArrayCode[E]): Code[Int] =
arr.len
}
```
**Figure 18** The tagless final encoding of the compiled library of Pilatus, which removes all unnecessary intermediate arrays.
**Figure 19** Performance comparison between Pilatus with different configurations and a baseline low-level implementation.
Figure 19 shows the performance results. For these experiments, the input vectors are all stored in a native JVM array, consisting of one million integer elements. Based on these experiments we make the following observations. First, changing the usage of native array representation to a pull array causes a minor performance overhead. This is because the JIT of JVM is unable to remove the overhead caused by the lambdas used in a pull array. Second, the overhead of lambdas as well as several other overheads are removed by using staging. This performance improvement is between 2.5x to 5x. Finally, the intermediate arrays are successfully removed by benefiting from the fusion of pull arrays (cf. Section 6.6). The improvement varies between 4x to 26x depending on the number of removed intermediate arrays. This makes the staged and fused Pilatus competitive with the baseline low-level implementation.
# 8 Related Work
## 8.1 Linear Algebra Languages and Libraries
The R programming language [56] is widely used by statisticians and data miners. It provides a standard language for statistical computing that includes arithmetic, array manipulation, object oriented programming and system calls. It is a Turing-complete language. By contrast, with our language we chose to focus solely on linear algebra operations. This minimalist approach results in a language that is not Turing Complete, but is nevertheless polymorphic...
8:24 Finally, a Polymorphic Linear Algebra Language
in various dimensions.
The Spiral [55] project introduces the languages SPL [71], OL [22], and more recently LL [62] which mainly captures the non-iterative matrix operations of Pilatus. Furthermore, the intermediate languages Σ-SPL [23] and Σ-LL [62] expose opportunities to perform loop fusion. One interesting direction is to use the search-based techniques to perform global optimisations offered by Spiral. Furthermore, Spiral in Scala [47] supports loop unrolling and fixed size matrices by using the staging facilities offered by LMS [57] and abstracting over data layout. Kiselyov [37] has used the tagless final approach and staging facilities of MetaOCaml in order to implement a linear algebra DSL based on rings and pull arrays (but not modules and linear maps) and has implemented many of the optimisations that we have presented in this paper. However, to the best of our knowledge, none of these projects consider graph algorithms, probabilistic programming, and automatic differentiation of linear algebra.
In the Haskell programming language, Dolan [17] implements a linear algebra library which uses different semi-ring configurations for expressing graph algorithms, as well as several other algorithms. We can easily extend Pilatus in order to support the additional semi-ring configurations used in that work. However, even though Elliot [18] implements a library for forward automatic differentiation in Haskell, Dolan [17] does not consider automatic differentiation. In addition, as both these two libraries are implemented without using any multi-stage programming facilities, none of them can support the staged libraries provided by Pilatus.
8.2 Deforestation and Array Fusion
Deforestation [67] and the corresponding short cut techniques [25, 63, 13] were introduced for functional languages for removing the unnecessary intermediate collections. Recently, these techniques have been implemented as a library using multi-stage programming [33, 38, 59].
On the other hand, in the high-performance functional array programming there are the two well-known array representations, which also achieve deforestation: pull arrays and push arrays [2, 12]. Each one of these two array representations comes with its own benefits, for which [64] combines the benefits of these two complementary representations. Pull arrays have been used for various DSLs [3, 37, 60] to produce efficient low-level code from the high-level specification of linear algebra programs. However, none of these systems consider other domains presented in this paper.
8.3 Automatic Differentiation and Differentiable Programming
Many techniques for finding optima of a given objective function (such as gradient-descent-based techniques) require the derivative of that function. Automatic differentiation (AD) [35] is one of the key techniques for automatically computing the derivative of a given program. Thus, these tools are an essential component of many machine learning frameworks. There is a large body of work on AD frameworks for imperative programming languages such as Tapenade [29] for C and Fortran, ADIFOR [7] for Fortran, and Adept [31] and ADIC [46] for C++, ADiMat [8], ADiGator [70], and Mad [21] performs AD for MATLAB programs, whereas AutoGrad [41], Theano [6], Tensorflow [1] performs AD for a subset of Python programs. There are also AD tools developed for functional languages such as DiffSharp [5] for F#, dF [61] for a subset of F#, Stalingrad [53] for a dialect of Scheme, as well as the work by Karczmarczuk [34] and Elliott [18] for Haskell. The most similar work to ours is Lantern [69], which uses the multi-stage programming features provided by LMS [57] in order
to perform AD for numerical programs written in a subset of Scala. A key feature provided by Lantern is supporting reverse-mode AD by using delimited continuations [14], which can also be supported by Pilatus, which we leave it for the future. All the presented frameworks are only for differentiable programming, whereas Pilatus supports graph computations and probabilistic programming, while providing algebraic-based and compiler optimisations for improving performance.
8.4 Probabilistic Programming
Probabilistic programming languages (PPL) can express stochastic models in a productive manner without worrying about the low-level details [28]. Infer.NET [44], Picture [40], and probabilistic C are examples of imperative PPLs, whereas, BUGS [24], STAN [11], and Church [27] are functional PPLs. Figaro [54] is an object-oriented probabilistic programming language which is defined as an EDSL on top of Scala. PRISM [58], BLOG [43], and ProbLog [15] are examples of Logical PPLs. Pilatus is inspired by both logical PPLs and the embedding of functional PPLs [39]. Although Pilatus has a more limited expressivity power in comparison with other logical probabilistic programs, it supports various other domains such as differentiable programming for linear algebra workloads.
9 Conclusions
In this paper, we have presented Pilatus, a polymorphic linear algebra language. This language is embedded in Scala and can have several interpretations supporting various domains such as standard matrix algebra, all-pairs reachability and shortest-path computations for graphs, logical probabilistic programming, and differentiable programming. In order to compensate the performance penalty caused by the abstraction overheads, Pilatus uses multi-stage programming. Furthermore, thanks to the mathematical nature of Pilatus, we use algebraic rewrite rules to further improve the performance.
References
Finally, a Polymorphic Linear Algebra Language
Finally, a Polymorphic Linear Algebra Language
|
{"Source-Url": "https://os.unil.cloud.switch.ch/tind-customer-epfl/5db29915-1c8a-4e15-986c-ba038a096b40?response-content-disposition=attachment%3B%20filename%2A%3DUTF-8%27%27%255Bv1.0.2%255D%2520PILATUS%2520ECOOP%25202019.pdf&response-content-type=application%2Fpdf&AWSAccessKeyId=ded3589a13b4450889b2f728d54861a6&Expires=1569856658&Signature=DEw9o1nUSv5eYR3iNMM2aGjYhZ4%3D", "len_cl100k_base": 15982, "olmocr-version": "0.1.50", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 82940, "total-output-tokens": 22583, "length": "2e13", "weborganizer": {"__label__adult": 0.0003757476806640625, "__label__art_design": 0.00034999847412109375, "__label__crime_law": 0.00028252601623535156, "__label__education_jobs": 0.0007100105285644531, "__label__entertainment": 7.426738739013672e-05, "__label__fashion_beauty": 0.00015795230865478516, "__label__finance_business": 0.00019812583923339844, "__label__food_dining": 0.0004029273986816406, "__label__games": 0.0005979537963867188, "__label__hardware": 0.0009379386901855468, "__label__health": 0.0005388259887695312, "__label__history": 0.0002887248992919922, "__label__home_hobbies": 0.0001061558723449707, "__label__industrial": 0.0004992485046386719, "__label__literature": 0.0002562999725341797, "__label__politics": 0.00031876564025878906, "__label__religion": 0.0006198883056640625, "__label__science_tech": 0.027923583984375, "__label__social_life": 9.524822235107422e-05, "__label__software": 0.004673004150390625, "__label__software_dev": 0.95947265625, "__label__sports_fitness": 0.00031876564025878906, "__label__transportation": 0.0006499290466308594, "__label__travel": 0.00020003318786621096}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 81536, 0.0241]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 81536, 0.67474]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 81536, 0.80551]], "google_gemma-3-12b-it_contains_pii": [[0, 3208, false], [3208, 7536, null], [7536, 11408, null], [11408, 13398, null], [13398, 16307, null], [16307, 18284, null], [18284, 21417, null], [21417, 23669, null], [23669, 26401, null], [26401, 29236, null], [29236, 31430, null], [31430, 34094, null], [34094, 35954, null], [35954, 38653, null], [38653, 41452, null], [41452, 43533, null], [43533, 45850, null], [45850, 48663, null], [48663, 52166, null], [52166, 55284, null], [55284, 56618, null], [56618, 59085, null], [59085, 61201, null], [61201, 64955, null], [64955, 68239, null], [68239, 72122, null], [72122, 75715, null], [75715, 79541, null], [79541, 81536, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3208, true], [3208, 7536, null], [7536, 11408, null], [11408, 13398, null], [13398, 16307, null], [16307, 18284, null], [18284, 21417, null], [21417, 23669, null], [23669, 26401, null], [26401, 29236, null], [29236, 31430, null], [31430, 34094, null], [34094, 35954, null], [35954, 38653, null], [38653, 41452, null], [41452, 43533, null], [43533, 45850, null], [45850, 48663, null], [48663, 52166, null], [52166, 55284, null], [55284, 56618, null], [56618, 59085, null], [59085, 61201, null], [61201, 64955, null], [64955, 68239, null], [68239, 72122, null], [72122, 75715, null], [75715, 79541, null], [79541, 81536, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 81536, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 81536, null]], "pdf_page_numbers": [[0, 3208, 1], [3208, 7536, 2], [7536, 11408, 3], [11408, 13398, 4], [13398, 16307, 5], [16307, 18284, 6], [18284, 21417, 7], [21417, 23669, 8], [23669, 26401, 9], [26401, 29236, 10], [29236, 31430, 11], [31430, 34094, 12], [34094, 35954, 13], [35954, 38653, 14], [38653, 41452, 15], [41452, 43533, 16], [43533, 45850, 17], [45850, 48663, 18], [48663, 52166, 19], [52166, 55284, 20], [55284, 56618, 21], [56618, 59085, 22], [59085, 61201, 23], [61201, 64955, 24], [64955, 68239, 25], [68239, 72122, 26], [72122, 75715, 27], [75715, 79541, 28], [79541, 81536, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 81536, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
81a71fc872a3d6d8f6c26be1e2f8aa6a574b6d03
|
5-2019
Code Reuse Between Java and Android Applications
Yoonsik Cheon
University of Texas at El Paso, ycheon@utep.edu
Carlos V. Chavez
University of Texas at El Paso, cvchavez2@miners.utep.edu
Ubaldo Castro
University of Texas at El Paso, ucastro@miners.utep.edu
Follow this and additional works at: https://digitalcommons.utep.edu/cs_techrep
Part of the Computer Sciences Commons
Comments:
An extended version of the paper to be presented at the 14th International Conference on Software Technologies (ICSOFT 2019), Prague, Czech Republic, July 26–28, 2019.
Recommended Citation
Cheon, Yoonsik; Chavez, Carlos V.; and Castro, Ubaldo, "Code Reuse Between Java and Android Applications" (2019). Departmental Technical Reports (CS). 1320.
https://digitalcommons.utep.edu/cs_techrep/1320
This Article is brought to you for free and open access by the Computer Science at DigitalCommons@UTEP. It has been accepted for inclusion in Departmental Technical Reports (CS) by an authorized administrator of DigitalCommons@UTEP. For more information, please contact lweber@utep.edu.
Code Reuse Between Java and Android Applications
Yoonsik Cheon, Carlos V. Chavez and Ubald Castro
TR #19-50
May 2019
Keywords: code reuse, multiplatform application, platform difference, software development, Android, Java
An extended version of the paper to be presented at the 14th International Conference on Software Technologies (ICSOFT 2019), Prague, Czech Republic, July 26–28, 2019.
Department of Computer Science
The University of Texas at El Paso
500 West University Avenue
El Paso, Texas 79968-0518, U.S.A.
Code Reuse Between Java and Android Applications
Yoonsik Cheon, Carlos V. Chavez and Ubaldo Castro
Department of Computer Science, The University of Texas at El Paso, El Paso, Texas, U.S.A.
ycheon@utep.edu, {cvchavez2, ucastro}@miners.utep.edu
Keywords: Code reuse, multiplatform application, platform difference, Android, Java
Abstract: Java and Android applications can be written in the same programming language. Thus, it is natural to ask how much code can be shared between them. In this paper, we perform a case study to measure quantitatively the amount of code that can be shared and reused for a multiplatform application running on the Java platform and the Android platform. We first configure a development environment consisting of platform-specific tools and supporting continuous integration. We then propose a general architecture for a multiplatform application under a guiding design principle of having clearly defined interfaces and employing loose coupling to accommodate platform differences and variations. Specifically, we separate our application into two parts, a platform-independent part (PIP) and a platform-dependent part (PDP), and share the PIP between platform-specific versions. Our key finding is that 37%–40% of code can be shared and reused between the Java and the Android versions of our application. Interestingly, the Android version requires 8% more code than Java due to platform-specific constraints and concerns. We also learned that the quality of an application can be improved dramatically through multiplatform development.
1 INTRODUCTION
Java is one of the most popular programming languages in use today for developing a wide spectrum of applications running on a range of platforms from mobile and desktop to server (TIOBE, 2019). The Android operating system is the dominating mobile platform of today (IDC, 2019), and Android applications can be written in Java albeit some differences between the Java application programming interface (API) and the Android API. Source code reuse is considered as a fundamental part of software development (Abdalkareem et al., 2017). Thus, it is natural to ask how much code can be shared and reused between Java and Android applications. In this paper, we study and answer this question.
Our research question is: how much code can be shared and reused in developing multiplatform applications written in the same programming language? A multiplatform application is an application that is developed for and runs on multiple platforms. In this paper, we use the term platform loosely to mean operating systems, runtimes including virtual machines, and software development kits (SDKs). We include SDK in the platform, as our research is focused on code reuse and we are also interested in studying the impact and complications caused by API differences of SDKs. The two specific platforms that we consider in this paper are Java SDK for desktop applications and Android Java SDK. At the time of writing, Java is the primary language for developing Android applications; Android tools also support other programming languages such as Kotlin and C/C++.
We answer the above research question by performing an experiment to measure quantitatively the degree of code reuse possible between Java and Android versions of an application. Our experiment is a case study developing a Java application and its Android version running on mobile devices like smartphones and tablets. The application is small in Java but is a typical Android application of an average size (Minelli and Lanza, 2013), requiring a graphical user interface (GUI), data persistence, networking, and a bit of multithreading. The application helps a user to figure out the best time to purchase products by watching over fluctuating online prices (see Section 2). We develop the application incrementally and iteratively with continuous integration and testing by switching instantly between platform-specific integrated development environments (IDEs). For this, we configure a custom multiplatform application development environment by sort of gluing individual platform-specific tools and IDEs. It propagates immediately changes made on the shared code
using one IDE to other IDEs and platforms. We attempt to maximize code reuse between two versions of the application. Our design approach is to decompose an application into two different parts: a **platform-independent part (PIP)** and a **platform-dependent part (PDP)**. The PIP is the part of an application that does not depend on platform specifics and thus can be reused on different platforms. The guiding design principle is to have clearly defined interfaces and employ loose coupling between the two parts to accommodate platform differences and variations. To determine code reuse, we measure the size of our code with a simple metric counting the number of lines of code (LOC). We also share other findings and lessons that we learned from our case study.
One difference of Android from Java is that its devices are resource-constrained in storage capacity and battery lifetime, and thus memory efficiency is an important quality factor for Android applications (Cheon et al., 2017) (Sillars, 2015). The performance constraints may affect the design and coding of an application and thus its code reuse. In this paper, however, we do not consider the performance in the implementation of the Android version of our application.
The rest of this paper is structured as follows. In Section 2, we describe our case study application, including the third party libraries and frameworks we use for its implementation. In Section 3, we explain our development of the application, starting with the configuration of tools and some design challenges along with our solutions. In Section 4, we assess our development in terms of code reuse by measuring our code quantitatively and interpreting the measurements. In Section 5, we mention related work, and we conclude this paper in Section 6.
2 CASE STUDY
As mentioned in the previous section, we perform a small but realistic case study to find an answer to our research question on multiplatform code reuse. The primary objective of our case study thus is to measure quantitatively the amount of code reuse possible between a Java application and its Android version. The secondary objective is to learn any complications or issues associated with multiplatform application development. They may be related with not only the design and coding of an application but also configuration of tools for incremental application development with continuous integration.
In our case study, we develop a Java desktop application and its Android mobile version, named Price Watcher. The application tracks the prices of products, or items, extracted from their webpages (see Figure 1 for sample screenshots). The application helps a user to figure out the best time to buy items by watching over fluctuating prices. As the prices are scraped from webpages, the watch list may consist of items from different online stores or websites.
Most applications today are built with libraries or frameworks that are either provided by the platforms themselves or acquired from third parties. These libraries and frameworks may introduce additional complications to the development of multiplatform applications. To study their implications in the code reuse, we use several different libraries and frameworks in our development. The APIs of Java and Android Java are very similar for common libraries such as collections, file I/O, and networking. However, graphical user interface (GUI) frameworks of Java and Android are completely different, as Android offers its own framework for GUI programming. Interestingly, there are also differences in the ways third-party libraries and framework are provided or supported by platforms.
- **Plain old Java objects (POJOs).** A library or framework is written in the ordinary Java, not bound by any special restriction other than those of the Java language specification. It is often bundled in the SDK. For instance, Android SDK includes one particular open source JSON library while Java SDK does not. An open-source library or framework can also be tightly integrated into the platform and be part of the platform’s APIs. That is, it is provided as a built-in feature of the platform, often modified significantly through the integration. A good example is Android’s support for SQLite, a lightweight, serverless relational database system (SQLite Consortium, 2019). There are noticeable differences be-
between the Android-specific SQLite API and the
JDBC-based Java SQLite API.
- Platform-specific SDK. A third party framework is often provided as a platform specific SDK. An example relevant to our case study is Google’s Firebase Database, a cloud-hosted database (Google LLC, 2019). Google provides different Firebase SDKs for different platforms, and the APIs of Android and Java (Firebase Admin Java SDK) are similar but with some subtle syntactic and semantic differences.
We will use three different approaches in our case study to persist the items being watched: a local file (JSON), a SQLite database, and a Firebase cloud storage. As said above, the main reason for doing this is to study their implications in the code reuse.
3 DEVELOPMENT
We develop our application incrementally—one feature at a time—and iteratively by continuously integrating and testing code written on different platforms (Cheon, 2019). In this section, we first show how to configure a multiplatform development environment supporting our development approach. The key requirement is to immediately propagate changes made on the shared code to other IDEs and platforms so that we can switch between IDEs and platforms for simultaneous work on multiple projects. We then point out some of the design challenges associated with multiplatform applications and describe our solutions. Our primary design goal is to maximize code reuse between two versions of our application, and toward that goal we propose a general architecture for multiplatform applications that recognizes and separates platform specifics. Our guiding design principle is to have clearly defined interfaces and employ loose coupling to accommodate platform differences and variations.
3.1 Tools
It is crucial to have adequate tool support for multiplatform application development. Since we develop two versions of an application, one for each platform, our development environment logically consists of three IDEs: two platform-specific IDEs and one for developing the common, sharable code. For Android, we of course use Android Studio, the official IDE from Google for Android application development built on JetBrains’s Java IDE called IntelliJ IDEA. For the development of both the Java application and the common code, any reasonable Java IDE including IntelliJ IDEA will work. However, since we are also interested in learning complexities and issues caused by diversity of tools, we opt for Eclipse. It is very likely that a combination of several tools be used for multiplatform application development. We configure our own multiplatform application development environment by composing a few platform-specific tools or IDE as suggested in (Speicher and Cheon, 2018).
Figure 2 shows our development environment consisting of Eclipse and Android Studio. We develop our application incrementally and iteratively with continuous integration and testing. One key requirement for incremental development of a multiplatform application is to propagate changes immediately from one IDE to the other. We use Apache Maven (Apache Software Foundation, 2019), a software project management and build tool, to share code and propagate changes in the form of a library, a Java archive (jar) file. Both the Java project and the Library project in Eclipse are Maven projects, and the Library project produces a library jar file, called an artifact in Maven, of the common code. The library jar file is installed in the Maven local repository and becomes available instantaneously to the Android project. Android Studio uses the Gradle build tool that understands Maven repositories. For the Java project we can also make it reference, or depend on, the Library project by changing its build path, as both are Eclipse projects. This allows us to also use Eclipse to build the Java project.
3.2 Design
Our primary design goal is to maximize code reuse between Java and Android versions of the application. For this, we decompose our application into two parts: a platform-independent part and a platform-dependent part. The platform-independent part (PIP) is the part of an application that does not depend on specifics of implementation platforms like platform-specific APIs (Cheon, 2019). In the model-view-controller (MVC) architecture, the model is a good
candidate for the PIP. The platform-dependent part (PDP) is the part of an application that does depend on a specific platform, e.g., the view and view-specific controller of MVC (Cheon, 2019). We make this distinction to share the PIP code across platforms while developing a specific PDP on each target platform. Thus, the key criterion on identifying and determining the PIP of an application is whether the code can be shared on all the target platforms of the application. Our notions of PIP and PDP are similar to those of platform-independent models (PIM) and platform-specific models (PSM) in model-driven software development (Brown, 2004) (Meservy and Fenstermacher, 2005). As said earlier, Maven plays a central role in our development by immediately propagating changes made on the PIP to other tools and IDEs.
One challenge in the design and coding of our application is to cleanly separate the PIP from the PDP while minimizing code duplication. It is easy to say and difficult to do. We need to identify commonalities and differences between the two target platforms in terms of the APIs and libraries needed for the implementations of the application. The PIP—the common, shared code—has to accommodate the platform differences and variations. Figure 3 shows the high level design of our application. The box labeled “Shared model” is the PIP and the other two are the PDP. Since Android provides its own GUI framework along with Android-specific concepts such as activities and fragments, the biggest platform difference is the UI. The other is to encapsulate platform differences and variations for the PIP (more on this below and later sections). As expected, the PIP does not depend on the PDP.
How does the PIP accommodate platform differences and variations? In a single platform application, the PIP and the PDP code are often interwoven and tangled. For a multiplatform application, we need to separate them and make the dependencies between them clean and explicit. In particular, we need to eliminate any dependency of the PIP on the PDP. There are several different techniques and approaches possible, such as required interface, inheritance and hook, parameterization, interface cloning, and interface unification (Cheon, 2019).
3.2.1 Plug-ins via Required Interfaces
The implementation of the PIP often depends on that of the PDP. As an example, consider the case when a new item is added to the watch list through the UI or externally through the shared cloud storage. The notions of items and the watch list can be coded once in the PIP and thus the PIP will be responsible for adding the item to the watch list. The PIP however cannot display the newly added item. Instead, it has to tell the UI (PDP) to display the newly added item, and each platform provides a different way of telling the UI to update its display. We eliminate this kind of dependencies by applying the dependency inversion principle, a specific form of decoupling program modules (Martin, 2003). We let the PIP depend on an abstraction of the PDP, not its concrete implementation. The assumption that the PIP makes on the PDP or its environment is coded explicitly in the form of a required interface (F. Bronsard, et al., 1991), an interface that is defined by a service provider of an interaction that specifies what a service consumer or client needs to do so that it can be used in that interaction. In a sense, this approach allows one to plug in platform-specific code to the PIP by providing a class that implements the required interface.
Figure 4 shows an application of this approach. A model class named ItemListModel manages the items that are currently displayed by the UI, and it defines a required interface to interact with a platform-specific UI. Both the Java and the Android applications provide an implementation of the required interface coded using platform-specific APIs. In the figure these are shown using the socket/lollipop notation. In a sense, the platform-specific UI is a plug-in that can be inserted into the PIP. The class diagram also shows how we maximize code reuse and minimize code duplication. The UI needs to display the items being watched, and each platform of course provides a different view, or widget, for displaying a collection of data, e.g., JList in Java and RecyclerView in Android. This so-called container view stores the data.
differently in a view-specific model classes, e.g., ListModel and RecyclerAdapter, providing a different set of operations. However, there is enough commonality in the set of operations, including grouping, filtering, sorting, and searching, that need be implemented for our application. Therefore, our design decision is to introduce a platform-neutral model class, ItemListModel, in the PIP and let platform-specific model classes in the PDP to delegate their operations to it.
3.2.2 Templates via Inheritance
Another way to accommodate platform differences and variations is to provide a skeleton algorithm, or code, in the PIP and let the PDP fill out the details in a platform-specific way. For this we use well-known software design patterns such as template method, strategy, factory method, and abstract factory (Gamma et al., 1994). This approach gives less freedom to the PDP than the previous approach, as the PDP has to follow the skeleton algorithm defined in the PIP, but more code is shared and reused. Figure 5 shows an application of this approach, our design for storing the items in a cloud storage from Google called Firebase (Google LLC, 2019). We define a special item manager class to store all items in a cloud storage. The idea is to override all mutation methods inherited from its superclass to make the items persistent by storing them in a cloud storage. As mentioned in the previous section, Firebase is supported in several different platforms including Android and Java. However, Google provides different Firebase SDKs for different platforms, and the APIs of Android and Java (Firebase Admin Java SDK) have subtle differences (Google LLC, 2019). In a Java application, for example, one has to write code to authenticate and initialize the application to use Firebase, which on Android is taken care of by the system. We encapsulate this platform difference in a separate, abstract class named FirebaseHelper and let the PDP complete it through subclassing. The abstract class defines a skeleton algorithm, or a sequence of steps, for using a Firebase database in terms of hook methods that can be overridden by a platform-specific subclass like the JavaFirebaseHelper shown in the figure. A similar approach is used to persist items using a local file and a SQLite database.
3.2.3 Building Blocks via Classes
Instead of providing a set of well-defined extension points in the form of pluggable interfaces or abstract classes with hook methods as described above, we can provide platform-neutral complete classes to be used as building blocks, or components, by the PDP. The PIP provides minimal support for PDP, but the PDP has full control over the use of the provided components. This approach can be a good alternative if there are big API differences among the target platforms or it is hard to come up with a well-designed, unified API for all platforms. In our application, for example, the list of supported online stores, or websites, can be different on each platform, and the website list can be used in several platform-specific ways, e.g., creating UI elements such as menu and action items. Some website attributes like icons are also stored and manipulated in platform-specific ways. We thus decide to define an enum type in the PIP that gives all websites that are supported by both platforms. Each website of the enum type defines only common, platform neutral attributes and operations, including its name, URL, and a command object to find the price of an item from its webpage. The PDP defines a platform-specific enum type by adding platform-specific attributes like website icons to the enum values provided by the PIP and, if any, adding platform-specific websites.
There are also several other techniques that can be used to address platform differences, and some of which will be mentioned and described in Section 4.3.
3.3 Implementation
We performed iterative and incremental development in our case study for two different reasons. First, we were not familiar with multiplatform application development and thus wanted to take advantage of what we learned during the development of earlier increments or versions of our application. Second, we wanted to refine our experiment as the development progresses by adding new application features partly based on the preliminary findings from the early increments. This was the exact reason that we ended up supporting three different persistent storages (file, database, and cloud storage) even if only one is needed for our application. Our initial plan was to store item data in a local database.
For each increment we need to work on three different projects: two Java projects in Eclipse and one Android project in Android Studio. The way our
Table 1: PIP classes and their sizes
<table>
<thead>
<tr>
<th>Class</th>
<th>No. of Lines</th>
</tr>
</thead>
<tbody>
<tr>
<td>Item</td>
<td>150</td>
</tr>
<tr>
<td>ItemListModel</td>
<td>295</td>
</tr>
<tr>
<td>ItemManager</td>
<td>246</td>
</tr>
<tr>
<td>FileHelper</td>
<td>12</td>
</tr>
<tr>
<td>FileItem</td>
<td>45</td>
</tr>
<tr>
<td>FileItemManager</td>
<td>106</td>
</tr>
<tr>
<td>SqliteDatabaseHelperable</td>
<td>19</td>
</tr>
<tr>
<td>SqliteItem</td>
<td>28</td>
</tr>
<tr>
<td>SqliteItemManager</td>
<td>114</td>
</tr>
<tr>
<td>FirebaseHelper</td>
<td>137</td>
</tr>
<tr>
<td>FirebaseItem</td>
<td>93</td>
</tr>
<tr>
<td>FirebaseItemManager</td>
<td>129</td>
</tr>
<tr>
<td>PriceFinder</td>
<td>35</td>
</tr>
<tr>
<td>WebPriceFinder</td>
<td>64</td>
</tr>
<tr>
<td>WebStoreBase</td>
<td>317</td>
</tr>
<tr>
<td>Log</td>
<td>35</td>
</tr>
<tr>
<td>Total</td>
<td>1825</td>
</tr>
</tbody>
</table>
development environment is configured allows us to work on all three projects at the same time by moving the mouse back and forth between Eclipse and Android Studio. However, it is more productive to first develop an application for one platform, create or derive a PIP from the application by refactoring its code, and then refine the PIP by writing the application for the other platform. The reason is that the PDP captures what is specific or unique on each platform, and the PIP is a generalization of all platforms. The PIP is coded by identifying and specifying algorithms and data that are common on all platforms. The complete Java application consists of 36 classes and 4604 lines of source code, and the Android version consists of 41 classes and 4987 lines of source code. In the next section we will measure our code to analyze code reuse between the two versions.
4 ASSESSMENT
In this section we first measure the size of our code with a simple metric counting the number of lines of code (LOC) including comments and blank lines that our classes take up in the source code files. We then analyze and interpret the measured LOCs. We also describe other findings and lessons that we learned from our development.
4.1 PIP
The PIP consists of 16 Java classes and 1825 lines of source code (see Table 1). Nested classes and interfaces are not included in the number of classes, but their code were of course counted in the number of source code lines. We can group the PIP classes into four different categories for use later in our analysis.
- **Items**: Classes in this group implement the core business logic of our application and include Item, ItemManager and ItemListModel. They store information about the items being watched and manage the watch list by providing operations such as adding, removing, updating, filtering, and sorting.
- **Storage**: As mentioned in the previous sections, we support three different approaches to persist item data: file, database, and cloud storage. For each data persistence approach, we provide three classes: a manager as a subclass of ItemManager, a helper to encapsulate platform differences of the storage APIs, and a special item class as a subclass of Item to store storage-specific item information such as a database id or cloud key.
- **Network**: These are network-related classes including classes for online stores, or websites, and for finding an item’s price from its webpage. We define a price finder class for each online store.
- **Others**: Utility and miscellaneous classes.
It would be very interesting to see how the code is distributed among these groups of classes (see Figure 6). The item-related classes account for 38% of our code, the storage 38%, and the network 23%. If we look further into the items group, 43% (295 lines) of source code belong to the ItemListModel class. Remember this is a UI-specific model class that we introduced to maximize code reuse (see Section 3.2). The class helps the UI to display watched items in many different ways; it is not really a core business logic class. Therefore, we can infer that our application is UI-intensive. Another thing we can quickly learn from the graph is that the three data persistence approaches have varying code sizes: file (9%), database (9%), and cloud (20%). This may indicate either the complexities of the approach themselves or the degrees of their code reuse possible. We will discuss
more on this later in this section.
4.2 PDP
Table 2 shows the sizes of both the Java and the Android versions of our application including their PDPs. The source code lines of the Android PDP include only manually-written Java code; they do not include so-called resource files such as GUI layouts written in XML or automatically generated Java source code files. The last column of the table shows the percentage that each part accounts for the whole application code, calculated using a formula, $x / (PDP + PDP) * 100$, where $x$ is either PIP or PDP. The PIP takes 40% and 37% of the Java and the Android application code, respectively. That is, 37%–40% of code are reused in our application despite being UI-intensive. One side finding is that the Android PDP requires 14% ((3162 - 2779) / 2779 * 100) more code than Java. This may be partly because the Android version provides a few additional features. However, Android applications generally require more coding to address Android-specific concerns such as application lifecycles and screen orientation changes. The overall size of the Android version is 8% larger than the Java version.
How many lines of code are needed to interface with the PIP? Table 3 lists platform-specific classes along with the numbers of source code lines written to interface with the PIP. Note that some of the classes are named the same as those of the PIP; but they are platform-specific subclasses defined in the PDPs. The last row shows the percentages of the interfacing code in the PDPs, 14% for Java and 22% for Android. As mentioned before, Android requires more coding, and this is clearly shown in the table. Two bulky classes are RecyclerAdapter and WebStore. The first class addresses Android-specific UI concern, e.g., re-cycling widgets to display multiple items. The additional code of the second class is mainly due to one more online store supported in the Android version; Android-specific features were used for this. Another thing to notice is the relative amount of code for three data persistence approaches. The database approach requires 3–6 times more code (see below for more discussion on this).
It would be very interesting and instructive to see how the platform differences of the same API affect reuse of the PIP code. If we combine the data from Table 1 and Table 3, we can estimate the amount of code that has to be written to reuse the major features of the PIP. Figure 7 shows this by plotting the sizes of the PIP classes and the corresponding PDP code for three features: UI, storage and network. The PDP code of course includes only the interfacing code—code written to interface with the PIP feature in question. Figure 8 shows the same information but in percentages. As shown, the percentages vary widely from 6% (of Android cloud) to 58% (of Java database) among the PIP features; the average is 18% for Java and 25% for Android. Th LOC numbers in Figure 7 generally indicate the degrees of code reusability as well as the easiness of reuse. For example, the first bar says one needs to write only 78 lines of Java code instead 619 (= 78 + 541) lines to manage watched items and help the UI to display them. For each PIP feature the size of its interfacing code is marginal compared to coding the whole logic in the PDP.
However, there is one exception. Among the
three data persistence approaches of file, database and cloud storage, the database approach requires more code in the PDP side—58% for Java and 46% for Android (see Figure 8). Before we look into this unusual case, let us first measure the complexity of each of the persistence approach in terms of source code lines. As shown in Table 4, the file-based approach is smaller than the database that requires somewhat less code than the cloud storage.
One thing that the table does not show is the similarity of the platform APIs between Java and Android. The Android File (I/O) APIs are exactly the same as those of Java except for additional notations for denoting different kinds of storages (internal and external) and directories (download, documents, etc.). The Google’s Firebase APIs for Java and Android are also very similar albeit some subtle differences in some of the operations provided. However, the story is completely different for the SQLite database. Android supports it as sort of a built-in feature with an API tightly integrated with its own framework. For Java, there is an open-source, JDBC-based library for SQLite databases. Due to this difference of platform APIs, we had to push more code to the PDPs, and that is why more code was written in the PDPs. In short, the platform APIs and their commonalities and differences greatly affect the development of the PIP and its reusability.
How does the separation of PIP and PDP affect the size of an application? Is there an increase in the code size caused by the separation, and if so, how much? The way we develop our application allows us to answer this question with minimal effort. We wrote our application incrementally by writing complete code on one platform for the feature under development and then refactored the code to derive a reusable PIP. As a result, we have two versions of our application, written with and without using the PIP. Table 5 shows the sizes of different versions of our application. As guessed, the monolithic versions—the ones written without using the PIP—have less classes and lines of code, and the size overheads of PIP/PDP are 14% and 13% for Java and Android, respectively.
### 4.3 Other Findings and Lessons
We learned both positive and negative sides of multplatform application development through our case study. Besides the obvious benefit of code reuse, perhaps, the most important side benefit from a developer’s point of view is that it provides opportunities for improving the quality of an application. We have to address diversity of platforms by considering platform-specific restrictions or concerns. In addition we have to work on, or review, the same or derived code several times, each with a different perspective—either as a service provider or a consumer. We first prototyped a new application feature in one of the platforms, refactored the monolithic code into a reusable library (PIP) and the PDP of that platform, and apply the library in the other platform. The implementation of a feature required several iterations with continuous integration and testing on two platforms. This development process allowed us to notice issues and problems from simple mistakes like naming inconsistency to more serious ones.
To be more specific we found that Android-specific features allowed us to explore and test our application in a way that would be impossible or unnecessary for a typical Java application, often exposing a potential issue or problem in the application. An example is device orientation change. The screen on an Android device can switch between portrait and landscape mode in response to the way one holds the device or when the device is rotated. Our application allows the user to filter items to be displayed in several different ways, e.g., based on online stores, item groups and keyword search. An item can belong to a user-named group, but not all items have to belong
to a group. The filtering feature was first introduced to the Java version, and it worked correctly. When the feature was added to the Android version, however, the device orientation change causes the application to show only those items that do not belong to any item group. We soon learned that this strange behavior was caused by an incorrect re-initialization of the application. A re-initialization occurs when the screen orientation changes because Android creates a new instance of a framework class upon screen orientation change; no such re-initialization is needed for the Java version. We fixed the problem by modifying the PIP. We also added a new UI element in both PDPs to provide an option for displaying all those items that do not belong to any item group. This option was overlooked in the initial design of the filtering feature.
Multiplatform application development encourages one to generalize APIs, especially those of the PIP, to address and accommodate platform differences and variations. In fact, even platform-specific restrictions or constraints contribute positively on the creation of a more reusable and extensible application. The initial design of our network module done on the Java platform provided synchronous operations, and a special return value was used to notify when the invoked operations fail. On Android, however, the provided network operations were always called in background threads created by the UI because Android does not allow any network operation on the UI thread (while Java does). This made us to create a new version of the network module that also provides asynchronous operations implemented using the Observer design pattern (Gamma et al., 1994). Due to the use of this design pattern, the error handling was also improved by creating a separate callback method in the observer, or listener, interface. The error reporting is separated from the main logic, and thus more detailed information about the error is provided to the caller. Android’s emphasis on application responsiveness also made us to improve the user experience of our application by providing additional features such as setting network timeouts and canceling network operations.
We noticed different kinds of platform differences and variations, including APIs (both syntactic and semantic), literal constant definitions and externalization, and use of external resources such as images. We used a range of techniques to accommodate these platform differences, including required interfaces, callbacks, delegation, parameterization, operation cloning, and design patterns like template methods, factory methods and strategy patterns (see Section 3.2).
One obvious downside of the PIP-PDP separation is that the PIP has to be written using the common denominators, or shared traits, of the both platforms. That is, the platform for the PIP is the intersection of the two target platforms. A common platform feature has to provide the same syntactic interface— operation name and signature, class, and package—as well as the semantics. Otherwise, it cannot be directly used in the PIP implementation and has to be pushed to the PDPs. Let us consider a very simple example. All GUI frameworks provide a way to perform a task on the UI thread, as they are single threaded. However, its syntactic interface may be different, e.g., SwingUtilities.invokeLater(Runnable) in Java and Activity.runOnUiThread(Runnable) in Android.1 A UI-specific PIP module such as ItemListModel (see Section 3.2) sometimes needs to perform a task on the UI thread, but it cannot use the above methods directly. Our solution was to include it in the required interface of the module and let the PDP provide a platform-specific operation.
It is common practice to use the print statement as a simple and quick tool to trace the flow of execution and print interesting values. This use of the print statement is often referred to as print debugging. On Android, however, the recommended style is to use a utility class named Log that offers several static methods.2 The log messages are fed from an Android device to Android Studio and can be viewed with a tool called LogCat. We addressed this issue of an API mismatch by cloning the Log class on the Java platform, which involves (a) defining a stub class in the PIP with the same syntactic interface as the Android and (b) providing an implementation in the Java PDP written in terms of the Java print statements. Note that the stub class is just for compiling the PIP and is not included in the distribution, the library jar file. We had to use a similar approach when a third party library is provided in the SDK of one platform but not in the other. An example is JSON, which was used to store items in a local file. An open-source JSON library is included in the Android SDK but not in the Java SDK.
Regarding debugging, we found it is a really good idea to include source code files in the snapshot library jar file during the development. Android Studio uses them, instead of the skeleton code decompiled from the bytecode, to show stack trace of an exception, thus providing better support for debugging the
---
1There is also a subtle semantic difference when the method is called on the UI thread.
2In fact, the Java coding style of the Android Open Source Project states that the print statements should never be used (https://source.android.com/setup/contribute/codestyle).
Android PDP code.
5 RELATED WORK
We found no published work measuring code reuse between Java and Android applications. However, source code reuse in Android applications recently received much attention from researchers. One interesting report is that the practice of software reuse is high among mobile application developers (Mojica et al., 2014). One study even reported that 61% of Android application classes appeared in two or more other applications (Ruiz et al., 2012). Unfortunately, the significant code reuse also indicates illegal cloning of classes, code piracy, or even repackaging of applications (Linares-Vásquez et al., 2014) (Gonzalez et al., 2015). Code reuse also impacts the quality of an application, particularly when code is reused in the copy-and-paste manner from online question-and-answer websites such as Stack Overflow (Abdalkareem et al., 2017). Unlike these existing work, our study investigated code reuse between a mobile application and a desktop application written in the same programming language, where the development processes and practices can be quite different (Minelli and Lanza, 2013) (Syer et al., 2013).
The diversity of mobile devices and platforms made native development of mobile applications challenging and costly, thus approaches like cross-platform development have emerged to reuse code across different mobile platforms by using various techniques including cross-compilation, virtual machines, and web technologies and platforms (Palmieri et al., 2012) (Heitkötter et al., 2013). Our case study, unlike the cross-platform development approach, was concerned with native development and sharing code with a desktop version of the application.
There are various types of software reuse possible (Ambler, 1998). Our study focused only on the reuse of source code in the form of a library or framework. However, the notions and concepts that we introduced in our case study for a multiplatform application development, such as PIP, PDP, and platform differences and variations (Cheon, 2019), are related with those of the established software engineering. For example, PIP and PDP are similar to a platform-independent model (PIM) and a platform-specific model (PSM), respectively, in model-driven software development (Brown, 2004). A PIM is a software model that is independent of the specific technological platform used to implement it, and is translated to a PSM, a model that is linked to a specific technological platform (Meservy and Fenstermaker, 2005). Software product line development has been widely adopted in professional software development to create a collection of similar software systems, known as a product family, from a shared set of software assets using a common means of production (Northrop, 2002). Several architectural styles are proposed for developing software product lines of Android applications (Durschmid et al., 2017). One core idea of the software product line development is identifying the commonalities and variabilities within a family of products (Coplien et al., 1998). In our case study, we used the commonality and variability analysis to identify platform differences and variations as well as the platform for the PIP.
6 CONCLUSION
We performed a small but realistic case study to measure quantitatively the degree of code reuse possible between Java and Android versions of an application. The case study application watches over the fluctuating prices of online products and thus helps a user to figure out the best time to purchase the products. To share code between the two platforms, we decomposed our application into two parts: the platform-independent part (PIP) and the platform-dependent part (PDP). The PIP is shared between the two platforms, and each platform has its own PDP to address platform-specific concerns. To determine code reuse achieved in our application, which is the main contribution of our work, we measured the size of our code with a simple metric counting the number of lines of code. Our finding is very promising in that we were able to achieve 40% and 37% code reuse for Java and Android versions, respectively, for a UI-intensive application. We also learned that the Android version requires 8% more code than the Java version. The degree of code reuse, of course, depends heavily on the types and degrees of platform differences and variations. We noticed several types of platform differences, each requiring a different technique to cope with it. It would be interesting future work to study the platform differences systematically to categorize them, to measure quantitatively their impacts on the code reuse, and suggest effective techniques to address them. As a side benefit, we also learned that multiplatform application development can improve the quality of an application dramatically. A platform-specific restriction or constraint may provide an opportunity to explore and test an application in a way that would be impossible or unnecessary on another platform, often exposing a potential issue or problem in the application. Platform differences and vari-
ations also encourage one to generalize APIs, especially those of the PIP, to accommodate them, thus making the code more reusable and extensible.
It is only fair that we should mention the overheads associated with multiplatform application development that we learned in our case study, such as configuration of tools, writing stub code, constant attention to subtle platform differences, and code size. In term of code size, our PIP/PDP multiplatform application requires 13% (Java) and 14% (Android) more lines of code than the single platform, monolithic versions.
REFERENCES
|
{"Source-Url": "https://digitalcommons.utep.edu/cgi/viewcontent.cgi?article=2329&context=cs_techrep", "len_cl100k_base": 9477, "olmocr-version": "0.1.49", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 41087, "total-output-tokens": 11742, "length": "2e13", "weborganizer": {"__label__adult": 0.0003843307495117187, "__label__art_design": 0.00023281574249267575, "__label__crime_law": 0.0002834796905517578, "__label__education_jobs": 0.0008831024169921875, "__label__entertainment": 4.655122756958008e-05, "__label__fashion_beauty": 0.0001595020294189453, "__label__finance_business": 0.0001806020736694336, "__label__food_dining": 0.0002930164337158203, "__label__games": 0.0004074573516845703, "__label__hardware": 0.00063323974609375, "__label__health": 0.0003361701965332031, "__label__history": 0.00017964839935302734, "__label__home_hobbies": 6.759166717529297e-05, "__label__industrial": 0.00023734569549560547, "__label__literature": 0.0002033710479736328, "__label__politics": 0.00020503997802734375, "__label__religion": 0.0003614425659179687, "__label__science_tech": 0.0026645660400390625, "__label__social_life": 8.147954940795898e-05, "__label__software": 0.003139495849609375, "__label__software_dev": 0.98828125, "__label__sports_fitness": 0.0002682209014892578, "__label__transportation": 0.0004093647003173828, "__label__travel": 0.00017344951629638672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51809, 0.04872]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51809, 0.35276]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51809, 0.91175]], "google_gemma-3-12b-it_contains_pii": [[0, 1113, false], [1113, 1922, null], [1922, 6143, null], [6143, 10536, null], [10536, 14851, null], [14851, 19241, null], [19241, 24002, null], [24002, 28339, null], [28339, 31688, null], [31688, 35614, null], [35614, 41063, null], [41063, 46183, null], [46183, 51362, null], [51362, 51809, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1113, true], [1113, 1922, null], [1922, 6143, null], [6143, 10536, null], [10536, 14851, null], [14851, 19241, null], [19241, 24002, null], [24002, 28339, null], [28339, 31688, null], [31688, 35614, null], [35614, 41063, null], [41063, 46183, null], [46183, 51362, null], [51362, 51809, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51809, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51809, null]], "pdf_page_numbers": [[0, 1113, 1], [1113, 1922, 2], [1922, 6143, 3], [6143, 10536, 4], [10536, 14851, 5], [14851, 19241, 6], [19241, 24002, 7], [24002, 28339, 8], [28339, 31688, 9], [31688, 35614, 10], [35614, 41063, 11], [41063, 46183, 12], [46183, 51362, 13], [51362, 51809, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51809, 0.11875]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
86dad7466a13169ee9e64704bc1f4a9d7227ce36
|
(User-friendly) formal requirements verification in the context of ISO26262
Original
(User-friendly) formal requirements verification in the context of ISO26262 / Makartetskiy, Denis; Marchetto, Guido; Sisto, Riccardo; Valenza, Fulvio; Virgilio, Matteo; Leri, Denise; Denti, Paolo; Finizio, Roberto. - In: ENGINEERING SCIENCE AND TECHNOLOGY, AN INTERNATIONAL JOURNAL. - ISSN 2215-0986. - ELETTRONICO. - (2019).
Availability:
This version is available at: 11583/2785894 since: 2020-02-28T12:29:35Z
Publisher:
Elsevier
Published
DOI:10.1016/j.jestch.2019.09.005
Terms of use:
openAccess
This article is made available under terms and conditions as specified in the corresponding bibliographic description in the repository
Publisher copyright
(Article begins on next page)
Full Length Article
(1) formal requirements verification in the context of ISO26262
Denis Makartetskiy, Guido Marchetto, Riccardo Sisto, Fulvio Valenza, Matteo Virgilio, Denise Leri, Paolo Denti, Roberto Finizio
Dipartimento di Automatica e Informatica, Politecnico di Torino, c.so Duca degli Abruzzi 24, Torino I-10129, Italy
Centro Ricerche Fiat (CRF), Str. Torino 50, Torino I-1004, Italy
ARTICLE INFO
Article history:
Received 19 March 2019
Revised 13 September 2019
Accepted 18 September 2019
Available online xxxx
Keywords:
ISO26262
Formal methods
SysML
ABSTRACT
In order to achieve the highest safety integrity levels, ISO26262 recommends the use of formal methods for various verification activities, throughout the lifecycle of safety-related embedded systems for road vehicles. Since formal methods are known to be difficult to use, one of the main challenges raised by these ISO26262 requirements is to find cost-effective approaches for being compliant with them. This paper proposes an approach for requirements formal verification where formal methods, languages, and tools are only minimally exposed to the user, and are integrated into one of the commonly used system modeling environments based on SysML. This approach does not require particular expertise in formal methods still allowing to apply them. Hence, personnel training costs and development costs should be kept limited. The proposed approach has been implemented as a plugin of the Topcased environment. Although it is limited to discrete system models, it has been successfully experimented on an industrial use case.
© 2019 Karabuk University. Publishing services by Elsevier B.V. This is an open access article under the CC BY-NC-ND license (http://creativecommons.org/licenses/by-nc-nd/4.0/).
1. Introduction
The ever-increasing complexity of automotive systems is raising new challenges in the area of system safety engineering. This statement is confirmed by our everyday life, where we continuously interact with electrical and/or electronic (E/E) systems, whose possible failures could have enormous safety consequences and implications (car airbag and cruise control are just two representative examples). Starting from these considerations, ISO 26262 [1] is a standard that was developed to meet the specific needs of safety critical systems within road vehicles and it applies to a complete automotive safety lifecycle: management, development, production, operation, service, decommissioning. It provides an automotive-specific risk-based approach to determine the Automotive Safety Integrity Levels (ASIL), a risk classification scheme defined in the standard to analyze and classify the impact of a particular potential hazard. The V model described in part 6 of the ISO 26262 standard (Fig. 1) is very similar to a standard V model for system designs at different abstraction levels, while formal verification is recommended for the specification of safety requirements and system designs at different abstraction levels, while formal verification is recommended for upwards design phase verifications. For example, the compliance and consistency of the software safety requirements with the technical safety requirements (expressing the output requirements of the system level development process) has to be verified, and formal verification is among the recommended techniques to be used for this purpose.
During the various product development phases, ISO26262 recommends the use of various specification and verification techniques. When dealing with items classified at the highest ASIL levels, formal and semi-formal methods are recommended. The most relevant recommendations about formal methods refer to the left-hand side of the V models, where formal specification is recommended for the specification of safety requirements and system designs at different abstraction levels, while formal verification is recommended for upwards design phase verifications. For example, the compliance and consistency of the software safety requirements with the technical safety requirements (expressing the output requirements of the system level development process) has to be verified, and formal verification is among the recommended techniques to be used for this purpose.
While the key role of formal verification techniques in the context of ISO 26262 is generally well understood, its application continues to appear a bit obscure and people with industrial background are often still reluctant in leveraging formal methods as they are known to be hard-to-use and very time consuming...
(therefore onerous, from an economic standpoint) [2]. All these observations lead us to the intuition that more user-friendly tools are needed to help people not familiar with formal methods, to approach and profitably use modern tools to formally model and verify the systems they are actually designing and implementing. Another feasible approach could be that of training personnel by spreading the necessary knowledge and skills to autonomously implement and complete verification tasks. While more appealing in the long-term, this solution would not be easily practicable from a cost perspective since it would require training time and associated costs, not to mention the initial learning curve which many companies may not be able to afford.
This paper addresses these issues by proposing techniques and tools that can contribute to remove the main obstacles to the use of formal methods in ISO26262-compliant development processes. Especially, our aim is to aid in the design phase verifications expected in the left-hand side of the V models, where the ability to compare models at varying levels of abstraction (going back up the abstraction levels) is required, and in the requirements-based testing activities that are required in the right-hand side of the V models.
More specifically, our work tries to cope with the above mentioned challenges, by proposing a modeling approach which does not require sophisticated skills in formal methods and is tailored on concepts that industry people are already aware of and familiar with: state machines, activity diagrams and sequence diagrams are palpable examples of “languages” already known to both academic and industry people that can be leveraged to model system behaviors. In particular, these languages are already part of UML-based semi-formal notations, such as for example SysML [3], which is widely known and accepted in the automotive industry [4,5]. A valuable feature of SysML is that it includes the possibility to specify hierarchical requirements with associated behavioral models expressed in the user-friendly language mentioned above. This enables the management of safety requirements according to the recommendations of ISO26262 and at the same time the formal specification of requirements through such behavioral models. Although SysML is known to be a semi-formal notation, its behavioral notations are quite close to fully formal models, and they can be converted into fully formal models by resolving the few variation points left in the definition of these languages.
Having created formal models of the requirements and the system at various levels of abstraction raises the question of how these models relate to each other. Does a model at a lower level of abstraction actually comply with a higher level one, by adding more detail while preserving the coarser behavior of the higher level one? In order to answer this question in a formal way, it is possible to use refinement checking, i.e. a formal check of whether a more abstract formal artifact is correctly refined into a less abstract one. The main advantage of refinement checking, compared to other formal verification techniques such as model checking, is that it does not require the user to specify formal properties in temporal logics, which is known to be challenging [2], but it can be applied directly to the models developed by the user with the more user-friendly notations. In particular, we propose the application of refinement checking to the behavioral models extracted from a SysML model, which is a novel approach in the ISO26262 context, as discussed in the Related Work Section.

One last ingredient of our work is a technique for automatic generation of test cases from the formal requirements specifications expressed by means of behavioral models. These automatically generated test cases can be used for requirements-based testing, which is one of the testing methods recommended by ISO26262 in the right-hand side of the V models, and also as an alternative to refinement checking for upwards design-time verifications, when refinement checking is not feasible because of the excessive complexity of the formal models. While the automatic generation of test cases from formal behavioral specifications is not new in itself, this way of using it, made possible by the proposed approach is new.
Our focus in this paper is on discrete systems and related requirements. While the approach we are proposing could be extended to deal also with continuous-time systems or requirements involving quantitative time, such extensions are outside the scope of this paper.
The approach we are proposing exploits a number of techniques already developed in the past by other researchers: the extraction of formal models from UML/SysML behavioral diagrams, the verification of refinement on formal models, and the automatic generation of test cases from formal models. Our main contribution is the way they are joined together so as to comply with the recommendations of the ISO26262 standard about the use of formal methods (especially for design-time verification), while at the same time hiding most of the complexity of formal methods from the final user, thus achieving a toolset that can be used even by users without specific expertise in formal methods. While there are alternative proposals for achieving this kind of hiding, none of them achieves all the goals we do.
For demonstrative purposes, our ideas have been developed and integrated, in plugin form, into Topcased, an Eclipse based modeling environment that supports SysML, where all the details related to the formal verification processes are kept, as much as possible, behind the scenes and automatically handled by the tool.1 It is important to note, however, that the proposed tool-chain is not intended as a full replacement of all ISO-26262-related activities, rather as a possible way to support some of the formal-method-related parts. It can be considered as a core functionality that needs
---
1 The plugin is available for download at [https://github.com/netgroup-polito/VeTeSS-Topcased-Verification-Plugin](https://github.com/netgroup-polito/VeTeSS-Topcased-Verification-Plugin).
to be then combined with other toolsets in order to achieve a full ISO-26262-compliant process.
In the rest of the paper we cover all these aspects with the following agenda: Section II presents the proposed way for specifying safety requirements in the SysML context. Section III shows how refinement can be formally verified at design time when developing new safety requirements, according to the recommendations of ISO 26262, while section IV shows the proposed technique for automated generation of tests based on safety requirements. Some results about the application of the proposed approach to an industrial use case are presented in section V. Section VI discusses related work and, finally, section VII concludes the paper.
2. Safety requirements formalization
Formal verification is possible as far as formal specifications are available. In our case, the starting point for obtaining formal specifications is the SysML modeling notation, already in use in vast areas of the automotive industry. SysML is a UML-based semi-formal notation. It inherits from UML several features, and extends UML with other features that are specific for system modeling. One of the key extensions of SysML with respect to UML is the possibility to model requirements and their relationships. In SysML, the system structure is described by means of structural diagrams. The main ones are block diagrams, describing a system or part of it as interconnected blocks. Behavioral diagrams complete system models by allowing the specification of system behavior by means of various formalisms. All behavioral diagrams are inherited from UML: activity diagrams use a formalism similar to Petri nets, sequence diagrams use message sequence charts, state machines are based on hierarchical extended state machines, while use case diagrams are a way to represent interfaces and use cases. Finally, requirement diagrams are a way to represent system requirements and their relationships. Both requirement-to-requirement relationships and relationships between requirements and system model elements are possible. The main relationships that can be defined are:
- The derive relationship relates a derived requirement to one of its source requirements;
- The satisfy relationship relates a model element to a requirement that is intended to be satisfied by that element;
- The refine relationship relates a model element and a requirement where one of the two refines with greater detail the other. The refine relationship allows, among the other things, to associate behavioral models with requirements;
- The verify relationship relates a requirement to a test case that can be used to verify whether the requirement is satisfied.
Note that a requirement can derive from one or more source requirements and more requirements can derive from the same source requirement and a similar consideration holds for the other relationships.
A possible alternative to SysML is EAST-ADL [6], which is a rich framework designed specifically for the automotive systems and with ISO-26262 in mind. As the key language features, we exploit are present in both SysML and EAST-ADL, the method proposed here can be cast to use EAST-ADL instead of SysML. Despite the better specificity of EAST-ADL for automotive systems, it has still less tool support and diffusion. For this reason, we preferred using SysML for our proof of concept.
The way we propose for using SysML modeling for specifying system-level safety requirements in an ISO26262 project is shown in Fig. 2, where the yellow arrows represent derive relationships (e.g. technical safety requirements are derived from functional safety requirements) and red arrows represent satisfy relationships. On the system modeling side, decomposition relationships (the blue ones in Fig. 2) are used for representing the hierarchical decomposition of a system, and refine relationships (green) for connecting corresponding system blocks at different abstraction levels (for example, functional blocks to corresponding physical components). Note that here we propose to use the same refine relationship also used for binding a requirement to its corresponding system element or behavioral model, but to relate system models.
The key point of our proposal is that engineers in charge of defining safety requirements should specify them as SysML requirements, and, for each requirement that needs a formal specification, they have to provide an associated behavioral diagram that specifies the intended behavior of the system according to the requirement.
An example of an airbag requirement specification expressed at high abstraction level is shown in Fig. 3, in its textual form (left) and in the form of a behavioral diagram (state machine) that specifies the expected behavior of the system according to this requirement (right). In the sample of Fig. 3 a state machine with two events is used to express the requirement: start_cc represents the start of a critical collision while deploy represents the deployment of the airbag. The fact that the airbag must not deploy if no critical collision started can be represented by a machine with two states: one state represents the behavior of the system before the start of a critical collision while the second state represents the behavior of the system after that event. The fact that the deploy event is possible only in the second state and not in the first one captures the requirement.
Another example of how a more complex requirement can be modeled is demonstrated in Fig. 4. Starting from such requirements, more detailed requirements can then be developed, in order to specify the technical means by which the original requirements can be satisfied. The new, more detailed, requirements must refine the original abstract ones, and this refinement relationship can be checked, as discussed in the Section 3.
In our view, the behavioral diagram associated with a requirement is its authoritative specification, while the text is just its explanation. We assign a formal semantics to the UML behavioral diagrams associated with SysML requirements by translating them to CSP (Communicating Sequential Processes) [7,8], a language for the formal description of discrete-event sequential processes that run concurrently and that can communicate with one another. This way of assigning formal semantics to UML behavioral models is not new [9]: translation algorithms from behavioral diagrams to CSP already exist that resolve the few variation points left with those.
3. Formal verification of safety requirements derivation
3.1. The proposed refinement checking method
The basic idea of the verification approach we propose is that derived requirements have to refine their source requirements. If each requirement is associated with a behavioral model that specifies the intended behavior of the system according to that requirement, the behavioral models of requirements bound by the derive relationship can be compared, in order to check that the behavior of source requirements is correctly refined by the behavior of derived requirements. As in our approach SysML requirements are formally represented by CSP processes, and CSP has a refinement theory, this theory can be exploited to check refinement relationships. The formal verification of refinement relationships is called refinement checking [7] and it is a well-known formal verification technique in CSP.
Generally speaking, a refinement relationship can be any relationship that formalizes the concept of refinement, which ideally should hold between a specification and its implementation. If the specification is a requirement, and its implementation is a model of the system that should fulfill the requirement or a set of (more detailed) derived requirements, refinement checking can be used to verify that the system model or the derived requirements satisfy the original requirement.
For example, traces refinement between a more concrete model $M$ and a more abstract one $M^a$ holds if each execution trace (i.e. sequence of events) of $M$ is also an execution trace of $M^a$. Instead, the relationship does not hold if $M$ can have sequences of events that cannot occur in $M^a$.
Traces refinement is known to preserve all safety properties, i.e. all properties specifying that something unwanted will never occur. This means that if $M$ is a traces refinement of $M^a$, then $M$ satisfies all the safety properties satisfied by $M^a$. Another relationship that could be considered is simulation refinement. A simulation refinement of $M^a$ if $M$ simulates $M^a$ step by step, i.e. if each possible step in $M$ always corresponds to a possible step in $M^a$ and the steps in $M$ and $M^a$ lead to states again related by the same relationship. As it can be argued, simulation refinement is stronger than traces refinement, and traces refinement is implied by simulation refinement. Simulation refinement is known to preserve all linear temporal logic (LTL) properties (not only safety properties) and a large subset of all computational tree logic (CTL*) properties. Often, weakened versions of these relationships are also considered. For example, weak simulation refinement requires that only some of the steps (the observable ones) have a match in the other model. In this way, it is possible to correctly relate cases where one step in the abstract model corresponds to a sequence of steps in the refined model. Of course, in this case only properties that do not involve non-observable steps can be preserved.
As we are mostly interested in safety properties, traces refinement is enough for our purposes. Moreover, as we have to relate models at different levels of abstraction, we use weak traces refinement, which disregards the events classified as unobservable. In our case, events are considered observable only if they belong to the alphabet of the abstract model, while events occurring only in the refined model are considered unobservable, unless they are explicitly declared to match a corresponding different event in the abstract model, in which case the corresponding events are renamed to become the same event. In this way, a refined model is allowed to generate a number of unobservable events between any two observable events matching the abstract model.
As we allow that more requirements derive from an abstract requirement, in general we need to check that a collection of
requirements $R_1, \ldots, R_n$ correctly refines an abstract requirement $R_a$. The refinement checking problem can be formulated by checking that a CSP process $I$ is a weak traces refinement of another CSP process $P_a$, where $P_a$ represents the system behavior required by $R_a$ and $I$ represents the system behavior jointly required by $R_1, \ldots, R_n$, with the events that do not correspond to events of $P_a$ hidden. Process $I$ is computed as $I = (Q_1 \diamond a_1) \ldots (Q_n \diamond a_n)$, where $\diamond$ is the parallel composition operator of CSP, which implies synchronization on all shared events, $Q_i$ is the process that represents the system behavior required by $R_i$, with the events that should be mapped to $P_a$'s events properly renamed, $a_i$ is the set of events of $Q_i$ that should be hidden because they have no corresponding event in $P_a$, and $\nabla a_i$ is the operator that hides the events in $a_i$.
3.2. Integrating the proposed method into an ISO 26262 process
Because of its mentioned meaning, refinement checking can be used as a way to perform what ISO 26262 calls design-time verification of compliance. For example, ISO 26262 part 6 clause 6.4.7 specifies that the software safety requirements shall be verified to provide evidence for their compliance and consistency with the technical safety requirements. These design-times verifications can be done using formal methods (formal verification is recommended for the highest ASIL levels), provided the requirements or system models to be compared are formally specified. Let us assume that formal specification of requirements is done using SysML behavioral diagrams, as shown in Section 3.1, possibly adding a specification that some pairs of different events should be considered the same. Having these specifications, formal verification can be done by refinement checking, using weak traces refinement, and the classification of events into observable and unobservable ones as specified above.
A typical development process in the automotive industry is to use SysML for safety requirements specification and for expressing the initial system architecture. Then, a more detailed Simulink system model is developed. In order to extend our approach to perform refinement checking between the requirements and the Simulink model, one should extract a formal CSP model out of the Simulink model. An alternative, enabled by our approach, is to verify refinement by testing. In particular, it is possible to use a form of “back-to-back comparison testing”: test cases are derived from the SysML safety requirements and then applied to the Simulink model (after having converted them into a form accepted by Simulink). At a later stage, when C code is generated from the Simulink model, the same test cases can be applied to test the C code, after proper conversion of the involved events. This is a form of requirements-based testing, one of the test methods recommended by ISO26262.
3.3. Implementation of the proposed refinement checking method
Several refinement checkers based on CSP theory exist. In our Topcased plugin, verification is implemented by the tools provided by PAT (Process Analysis Toolkit) [10], which efficiently implements refinement checking according to this theory and also provides algorithms for automatic generation of CSP processes from UML behavioral diagrams.
The procedure followed by the plugin that we implemented is shown in Fig. 5. It works as follows:
- Derive relationships are identified in the model, and state machines (or other behavioral models) associated with the requirements bound by derive relationships are extracted from the model, by an XSLT transformation of the XML representation of the model.
- A corresponding CSP process is automatically generated from each extracted behavioral model. This is done by exploiting the algorithms provided by PAT to create CSP processes from UML behavioral diagrams.
- For each group of behavioral models bound by the derive relationship for which refinement has to be checked, a CSP verification model is built which includes the specification of the weak traces refinement relationship to be checked and of the involved CSP processes, built as explained in Section 3.1.
- PAT is invoked on the CSP verification model in order to perform refinement checking between the corresponding CSP specifications.
- Verification results (including counterexamples in case of errors found) are converted back to the SysML world and reported to the user by the plugin.
Considering refinement checking as part of our formal verification approach, the concrete toolchain needed to run a complete verification task (starting from the modeling phase and ending up with a verification outcome) is depicted in Fig. 6 (the boxes with blue background represent tools specifically developed for our purposes while the other boxes are already existing tools; the part about test case generation is not included in the picture but it will be discussed in Section 4).
As SysML is used for the specification of requirements and their associated behavioral models, any modelling tool that supports SysML and that can export models in XML format can be used. SysML is also used to express the derivation relationships that bind requirements (in this way the user can specify how new requirements have been derived from the previous ones) and satisfy relationships that bind requirements to the system model elements that implement them. The derivation relationships also enable requirements tracing, which is also required by ISO26262. The information about the mapping of the events occurring in the requirements bound by a derive relationship can be added to the derive relationship itself as an attribute in SysML (it is specified as a collection of event pairs).
The tool chain, which was described preliminarily in [11], is integrated in the Topcased environment where a specialized plugin is used to drive the whole verification process. More precisely, the plugin analyzes the SysML model and automatically extracts derivation relationships binding requirements.
The user can interactively decide for which of such relations refinement should be checked, by selecting the requirements involved in the verification. Then, for each selected derivation relationship, the plugin automatically extracts the behavioral models associated with the requirements bound by the relationship, translates them into CSP, and generates the input for PAT as already
Fig. 5. The refinement plugin verification workflow.
explained. Finally, PAT is automatically invoked and refinement is checked. The results (including counterexamples in case of failure) are finally reported to the user through the plugin itself.
The other possibility provided by the tool is to use testing in order to verify refinement checking. In this case, the tool automatically performs test case generation (more on this is presented in Section 4) from the behavioral model of the more abstract requirement and then executes the generated tests on the behavioral model of the more concrete requirement.
The screenshot in Fig. 11 shows how the GUI of the plugin appears. In this screenshot it is possible to see the panel where hierarchical requirements and their relationships are graphically modeled and the view of the Verification plugin in the lower pane with the Refinement Checking tab where the plugin shows the extracted derive relationships. In this tab, the user can make selections and start refinement checking verification. In the example shown in Fig. 11, about an airbag system use case, it is possible to see two requirements bound by the DeriveReqt relationship. The two requirements shown in the example have behavioral models, expressed as state machines attached to them. Each state machine is specified in a separate diagram, using the same modeling environment.
Fig. 9 shows the state machine diagram of the more abstract requirement (Deploy_should_be_preceded_by_critical_collision), which expresses a precedence relationship: the deploy event must always be preceded by the critical_collision event. The more concrete requirement (Deploy_within_two_time_ticks_after_collision) has a state machine shown in Fig. 8.
In order to verify that the refinement relationship holds between the two requirements (i.e. that Deploy_within_two_time_ticks_after_collision correctly refines Deploy_should_be_preceded_by_critical_collision) we have to select the Deploy_should_be_preceded_by_critical_collision abstract requirement in the list of relationships, as shown in Fig. 11, and push the Start verification button (the Refresh button is used to create the list of relationships or to update it after modifications to the model).
Fig. 7 shows the verification report, indicating that the refinement relationship does not hold. In order to understand why refinement does not hold it is possible to look at the counterexample (init -> [start] -> [collision] -> deploy) which is a sequence of events that may occur in the concrete behavior but not in the abstract one, thus invalidating refinement. Events enclosed in square brackets in the counterexample represent hidden events, i.e. events that are not considered because they are not shared by the two behavioral models. In this particular case, it is possible to see that deploy can occur without being preceded by critical_collision (it is preceded by collision, which is a hidden event). The problem arises because in the descriptions of the two requirements two different events have been used to represent a collision (collision in one case, critical_collision in the other case). The problem can be fixed by using the same collision event in the two requirements or by specifying that these two events should be considered the same in the verification of refinement. This can be done by selecting the refinement relationship and by adding the mapping of the two events. After this fix, if we repeat refinement checking, we get the result that the relationship holds (valid).
The CSP verification model generated by the plugin for this verification task is shown in Listing 1. In it, the implementation process corresponds to the process indicated as I in Section 3.1 while the first two defined processes are the ones automatically generated from the two state machines.
4. Automated generation of requirements-based test cases
Testing is the main verification technique recommended by ISO 26262. Fig. 10 illustrates the process for testing a system under test (SUT) against a set of requirements (requirements-based testing):
first, a test suite, i.e. a set of test cases covering all the safety requirements, is created. A test case consists of input stimuli and the expected outcome. Test execution runs the SUT feeding it with the inputs specified by each test case and compares the SUT output against the expected one. Coverage measurement assesses whether the test suite is sufficiently complete; if not, further test cases have to be created so as to reach the target coverage. As an alternative to manual test case generation, Model-Based Testing (MBT) consists of deriving test cases from an abstract model (for requirements-based testing, a model of the requirements has to be used). This section shows how the formal behavioral models derived from SysML models (and associated to safety requirements) are used in our approach for automatic generation of test cases that can be used for requirements-based testing and for verifying software safety requirements according to ISO 26262. The size of the set of generated test cases can be subsequently optimized by means of simulation-based algorithms that prune redundant test cases. Note that requirements-based testing is just one of the several test methods recommended by ISO-26262. The use of a variety of test methods contributes to greater diversity and better opportunity to catch errors.
Most of the existing literature about MBT of reactive systems starting from formal models is based on Finite State Machine (FSM) and Labeled Transition System (LTS) models [12]. As these models are very general, many other specification formalisms (e.g. process algebras, petri nets, extended/hierarchical state machine models), including the ones supported by SysML, can be interpreted according to these two basic models. This opens the possibility to apply the same MBT techniques to a variety of modeling languages. As already mentioned, even if we consider UML and UML-based specification languages, which are semi-formal, it is possible to derive corresponding formal models from some parts of the UML models, provided the semantic variation points in the UML models are resolved in some way. For example, using this approach, it is possible to give a formal semantics to UML state machines, which enables their interpretation in terms of LTSs.
One limitation of FSM based methods is that they typically consider only deterministic machines. Of course, nondeterministic machines can be turned into deterministic machines, but at the cost of state explosion. This feature makes FSM-based methods inadequate for large nondeterministic models. One good point of
FSM-based methods, however, is that they have been highly optimized with the search for minimal tests [13]. LTS methods are more general in that they deal with nondeterministic and infinite-state systems. With large or infinite-state systems, lazy (on-the-fly) evaluation is typically used. Because of their ability to deal with nondeterministic and infinite-state systems, LTS-based methods seem more appropriate for our context. In particular, one of the LTS-based theories that seems most appropriate is the one that deals with I/O LTSs (chapter 7 of [12]). This theory includes the definition of several implementation relationships and methods to build test suites.
4.1. MBT with I/O LTSs
According to the theory of MBT with I/O LTSs, the behavioral model of the SUT associated with a safety requirement (i.e. the specification) is converted into an I/O LTS (an LTS with labels divided into input, output and internal). The model must be such that it does never refuse inputs (all inputs are available in all states; this can be obtained by completing an incomplete specification by saying, for example, that non-specified inputs are ignored, i.e. by adding self-loops for non-specified inputs in all states). If the model has quiescent states (i.e. states where no outputs can occur) these are marked by adding a self-loop to that state, labeled with a special $\delta$ label (this could be interpreted as the expiration of a timeout in case the environment is waiting for an output).
Fig. 12 shows an example of an I/O LTS that does never refuse inputs, with two inputs ($?c$ and $?nc$) and two outputs ($!as$ and $!ar$), and the additional $\delta$ events already added.
Test generation can target one or many different implementation relationships. The simplest relationship is traces refinement (see Section 3). The most used relationship is ioco (input-output conformance) [14]. This relationship is defined considering the traces of the specification (with the inclusion of the special event $\delta$). If, after one of these traces, the outputs that the implementation can perform are a subset of the outputs that the specification can perform after the same trace, the relationship holds. This relationship is weaker than traces refinement (traces refinement implies ioco) because ioco does not constrain the implementation in any way after the traces that the specification cannot execute. However, if both the implementation and the specification have the same alphabet of events, do never refuse inputs, and are completed with events, then the two relationships coincide. Each test case generated from a model is again an I/O LTS with final states that are labeled as success, fail (and inconclusive). This LTS has inputs and outputs reversed w.r.t. the specification. In each state it can
either emit exactly one output (i.e. an input to the system) or receive any input (i.e. any output from the system) or the special event that corresponds to δ (the timeout that indicates quiescence of the system). Applying a test case means executing it step by step until a final state is reached. The label of the final state determines the result of the test case. If the system is nondeterministic, each test case should be repeated several times and we can say that the test case has been passed only if all runs end up with the pass result.
4.2. Toolchain for MBT
In our approach, MBT is supported by performing test case generation from the behavioral models associated with safety requirements. These models are automatically completed with inputs (so that they can never refuse to perform inputs) and with δ events. When using MBT for testing refinement, the SUT model is also completed in the same way, and events that occur only in the implementation are considered as internal (i.e. nor input neither output). In this way, we make sure ioco and traces refinement coincide.
The toolchain for performing MBT in our demonstrative Topcased plugin is based on CADP/TGV [15], an already existing tool which can generate test cases for testing the ioco relationship on I/O LTS models automatically. The output of TGV is a collection of test cases, each one represented by an I/O LTS with three sets of trap states: Pass, Fail and Inconclusive, that represent the verdict. The input of TGV consists of two I/O LTSs: a specification and a test purpose. The specification is a model of the expected behavior of the SUT. A test purpose is the representation of the part of behavior of the SUT that must be taken into consideration for test generation. This can be used, for example, in order to limit the size of each resulting test case. A test purpose must be complete, i.e. it must be such that all events must be possible in all states, and it must include two sets of special states called trap states: the set of accept states and the set of refuse states. Each accept or refuse state must include self-loops for all the events (this is why it is called a trap state). The meaning of an accept state is that, when it is reached, the behavior we are interested in has been observed. Instead, a refuse state is one that, when reached, means the observed behavior is not relevant for the test. In both cases the test must be stopped. If an accept state is reached and all outputs from the SUT have been among the expected ones (as specified in the specification), an accept verdict is generated. Otherwise, if a refuse state is reached and all outputs from the SUT have been among the expected ones, an inconclusive verdict is emitted. Finally, a fail verdict is generated if the SUT generates unexpected outputs, but this remains implicit in the output I/O LTS (if the output is not present, this means fail). TGV includes the possibility to complete incomplete test purposes by adding self-loops for all the missing events. Moreover, TGV automatically adds δ events as necessary. The generation of δ events is performed by TGV when it combines the specification and the test purpose into a single I/O LTS. For test case generation, TGV uses a lazy evaluation technique that lets it limit the amount of memory consumed. TGV can take inputs specified in several input languages and convert them into the I/O LTS form. Unfortunately, TGV cannot take CSP as input. However, it can take LOTOS\(^2\) [16], which is another formal specification language similar to CSP. As LOTOS was inspired by CSP, its process algebra is very similar to CSP. Note that TGV was selected as the best fit to our problem, as we didn’t find MBT tools capable of performing test case generation based on the ioco relationship that can take directly CSP as input.
As we already have CSP models generated from SysML behavioral models, we created a conversion tool from CSP to LOTOS, in order to enable the use of CADP TGV for MBT test case generation. As in LOTOS the distinction between input and output events may not be possible, a separate file is used by TGV in order to give this specification (i.e. whether each event has to be considered as input or output). This is also generated automatically by the converter. Finally, in order to limit the manual work of the user as much as possible, an automatic test purpose generator has been created. Test purposes can then be edited by the user if necessary. The complete MBT toolchain resulting from this approach is shown in Fig. 13.
This basic method has been integrated into our plugin for the Topcased [17] environment along with the refinement checking tool. Having these two tools in the same plugin makes code reuse straightforward and provides a single environment where users can develop software safety requirement models in SysML, check refinement relationships among requirements using the refinement checking tool and generate test cases starting from the safety requirements models.
5. Experimental results
An evaluation of the approach has been done by means of the demonstrative toolchain on a use case proposed by CRF (Centro Ricerche Fiat), the FCA (Fiat Chrysler Automobiles) Research Center, within the VeTeSS (Verification and Testing to Support Functional Safety Standards) European Project (https://artemis-ia.eu/project/43-vetess.html).
VeTeSS developed standardized tools and methods to verify the robustness of safety-relevant systems, particularly against transient common-cause faults. CRF’s use case selected for the project was an electric gear selector for HEV/EV (e-shift [18]): the system provides mechanical locking or unlocking of the transmission when the parking mode is selected (by the driver or automatically), avoiding unwanted movement of the vehicle when stopped. The electric gear selector is composed of a Vehicle Control Unit (implementing the control strategies), a number of switches (sensing of Parking, Drive, Rear and Neutral buttons) and a parking lock actuator (actuating the command to a park pawl motor). Two of the identified safety goals were analyzed in the project: avoiding an unwanted unlocking of the parking brake (SG#1) and avoiding an unwanted activation of the parking brake when the car is moving (SG#2). Starting from an already existing model of the e-shift system and a natural language expression of its safety requirements, a corresponding SysML model has been created, including the formalization of safety requirements according to the proposed approach. This work has been done by a team of CRF’s engineers having background in SysML but not in formal methods, with the support of the tool developers from the Turin Polytechnic.
Unfortunately, for the time being, software safety requirements are not available for the e-shift use case. Only system-level requirements are available (functional and technical safety requirements). For this reason, the evaluation has been done using the available requirements. This means that compliance and consistency have been checked according to our approach between functional safety requirements and technical safety requirements. Similarly, test cases have been generated from technical safety requirements rather than from software safety requirements. However, we think this kind of experiment is still significant for demonstrating and evaluating the approach, and it is also relevant for software, considering that the test cases derived from the technical safety requirements can be used for software-in-the-loop testing. Even if not all the available safety requirements have been formalized, a significant subset of them has been formalized in SysML, with their associated behavior. For these requirements, the plugin has been able to check refinement relationships, and for technical safety requirements it has been able to generate test cases, as expected. The subset of formalized requirements includes safety goal SG#2, 9 functional safety requirements, and the 18 technical safety requirements derived from them. These include all the requirements related to the D button. For one of the requirements (TSR#008) the test cases generated by the tool have been manually translated into Simulink-related time histories. As an example, the test case generation for one of the technical safety requirements (TSR#011) is presented here. The text of the requirement is: “If the system is in P mode, VCU shall set Shifter_pos signal to D mode (i.e. event shift_pos_to_D can occur) only in PState2, i.e. only when the result of the last acquisition/validation of the brake pedal status has been valid-pressed. While considering this requirement alone, the output that has to be observed is event shift_pos_to_D, while all the other events can be considered as inputs. Accordingly, when deriving test cases for this requirement, shift_pos_to_D is classified as output while all the other events are classified as inputs. The generation of the test cases with a default test purpose set with a maximum length of the test patterns equal to 100 produces a test case I/O LTS composed of a total of 26,900 steps (i.e., transitions of the I/O LTS). The time taken by TGV to generate the test cases (with the default test purpose set to a maximum test length of 100) is in the order of few seconds. Considering that a maximum test length of 100 is already a fairly high value, this result gives a positive assessment about the scalability of the tool used for test generation. This experimental work
<table>
<thead>
<tr>
<th>Events</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>P_in</td>
<td>The P driving mode is entered</td>
</tr>
<tr>
<td>D_in</td>
<td>The D driving mode is entered</td>
</tr>
<tr>
<td>R_in</td>
<td>The R driving mode is entered</td>
</tr>
<tr>
<td>N_in</td>
<td>The N driving mode is entered</td>
</tr>
<tr>
<td>B_valid_pressed</td>
<td>The result of the acquisition/validation of the brake pedal status is communicated and this result is valid-pressed</td>
</tr>
<tr>
<td>B_valid_unpressed</td>
<td>the result of the acquisition/validation of the brake pedal status is communicated and this result is valid-unpressed</td>
</tr>
<tr>
<td>B_invalid</td>
<td>the result of the acquisition/validation of the brake pedal status is communicated and this result is invalid</td>
</tr>
<tr>
<td>shifter_pos_to_D</td>
<td>the Shifter_pos signal is set to D mode</td>
</tr>
</tbody>
</table>
The latter state is reached only after event B_valid_pressed, i.e. only when the result of the last acquisition/validation of the brake pedal status has been valid-pressed. As evident from the diagram, this machine expresses the fact that the Shifter_pos signal can be set to D mode while when the state is “Other”, the result can be valid-unpressed or invalid. The upper state machine models the driving mode by means of two states: PMode and OtherMode. Inside PMode there are two sub-states: PState1 and PState2. Fig. 14. The formalization of TSR#011 from the e-shift use case.
Please cite this article as: D. Makartetskiy, G. Marchetto, R. Sisto et al., (User-friendly) formal requirements verification in the context of ISO26262, Engineering Science and Technology, an International Journal, https://doi.org/10.1016/j.jestch.2019.09.005
allowed us to get a confirmation that refinement checking can be applied with success to a realistic industrial use case. As requirements behavioral models are not so complex, the time taken by refinement checking is absolutely affordable (each verification takes seconds to complete). In the experimentation with the e-shift use case, refinement checking proved to be a tool useful for obtaining coherent and precise requirements models. In fact, modeling errors were spotted either by performing simulation (made possible by the integration with PAT) or by performing refinement checking. The formal models were obtained after some check-fix iterations. The main issues that had to be corrected during these iterations were related to wrong uses of the modeling language. The modeling work also led to the detection of a redundancy in the set of functional safety requirements: two of the original requirements were found to be equivalent, i.e. to have the same behavioral model. The textual formulation of the e-shift requirements was not precise enough for their formalization, and some of the implicit underlying assumptions made by requirements engineers had to be understood and made explicit in order to proceed with formalization. The formalization work necessary as a pre-condition for performing verification by means of refinement checking gave the opportunity to improve the precision of safety requirements, while refinement checking provided the confidence that derivations were sound or spotted conceptual errors or lack of necessary assumptions in requirements formalization. One of the main limitations observed by CRF’s engineers is related to the difficulty of formalizing requirements as state machines or as one of the other behavioral models available in SysML. However, CRF agreed, in their final evaluation report, that although the effort for the formalization of requirements as state machines is considerable, it was feasible and it made formal verification possible, thus improving the quality of the process. Without this approach and tool support, formal verification would not have been possible, because of the lack of specific skills in formal methods. The benefits of having performed this modeling and formal verification step that the CRF team reported as most useful are the resulting non-ambiguity, consistency, and coherence of the obtained requirements set: safety requirements have precise meaning, and each one derives correctly from the higher-level ones. By employing the proposed formal verification tool, this result could be achieved with acceptable effort. Another result is that the team of engineers was able to complete all the formal specification and verification tasks of this project with limited support and guidance from the tool developers, which confirms that the proposed toolchain can be used by engineers with background in SysML. The main thing that they learned from the process is that a formal specification and verification step can really help to improve the quality of requirements.
6. Related work
After the publication of ISO 26262 some proposals have appeared in the literature about how to introduce formal methods in ISO 26262 compliant development processes. However, only in some cases these works address the problem of making the use of formal methods user-friendly and fully automated, by hiding the complexity of formal notation and reasoning to the final user.
For example, [19] presents a methodology that includes formal verification of refinement relationships between safety requirements and their software implementations. Differently from our work, it requires that requirements are expressed directly in the formal language of the verification tool, and the tool (a theorem prover) is not fully automatic. Another work [20] provides support for the verification of safety requirements by exploiting syntactic contract conditions. The approach proposed in [20] as a way to limit the exposure of the user to formal languages consists of avoiding a full formalization of requirements. In this way, however, formal verification remain possible only partially, while our approach allows a full formalization and verification of requirements. Instead, [21] proposes the use of CSP-based automated verification tools in order to formally check safety requirements. While the paper envisages the usefulness of translating safety requirements into CSP automatically, this is left as future work. [22] presents a tool called SESAMM which hides the complexity of formal specifications by exploiting specification patterns. The user specifies requirements in terms of patterns and the latter are then translated automatically into formal notation. While the SESAMM approach is a possible valid alternative to our approach to create formal requirements specifications in a user-friendly way, currently SESAMM does not address the problem of refinement checking as we do, i.e. it cannot check automatically that a derived requirement correctly implements a more abstract one.
Among the works that use formal methods and address user-friendliness and automation in a way more similar to what we propose, [23] presents a methodology based on expressing requirements and system models in UML and translating them automatically into formal notations that can then be used for verification by model checking. Although there are similarities between our approach and the one proposed by [23], e.g. the extraction of formal models from UML behavioral diagrams, there are also substantial differences: we consider SysML rather than UML, which allows us to represent requirements derivations, and we use refinement checking rather than model checking. In this way, we can compare requirements at different abstraction levels, and we avoid to expose the user to a specialized formalism for requirements (in [23], requirements have to be specified by means of pre and post conditions). In addition, we introduce the possibility of a smooth transition from refinement checking to testing, via automatic generation of requirements-based test cases.
Another work related to our one is [18], where the same e-shift use case has been used for evaluation. However, this paper proposes a technique for improving test coverage, which is complementary to our approach rather than alternative to it.
In the rest of this section, we give an overview of related work in the area of refinement checking. Theories of refinement have been developed for several formal specification languages (e.g. [24–26]). Among these languages, CSP [7,8] has gained particular interest and popularity, also because of the availability of widespread techniques and tools for automated checking of refinement in CSP. The CSP theory of refinement has been used in several fields (software, hardware and system development) with the aim of verifying the compliance of implementations with specifications or the compliance of specifications with other corresponding more abstract specifications. However, as CSP is typically outside the common background of engineers, some attempts have been made in order to hide CSP to final users. This can be achieved by translating the models used for specification into CSP. For example, [28] presents an approach for using CSP-based refinement checking for verifying mobile phone applications: properties are expressed as constrained English sentences that can be automatically translated into CSP and another CSP model is automatically built from the code of the application. Then refinement checking is used in order to verify that the code fulfills the properties. Another example is [29] where OCCAM programs are automatically translated into CSP in order to apply refinement checking. Our approach is similar to these ones, but the context (ISO 26262 safety requirements) is totally different.
Focusing on UML-based specification formalisms, some attempts have been made to facilitate refinement checking of UML models, by automatically deriving CSP processes from (parts of) UML models. For example, [30] presents a CSP semantics for a subset of UML that includes UML state machines while [31,32] deal with automatic translation of UML state machines and UML
activity diagrams respectively into CSP. Given the rich literature in this field, in our work we do not provide alternative ways for generating CSP from UML behavioral diagrams but we exploit the already existing approaches.
7. Conclusions
Starting from the observation that electronic and programmable automotive systems are becoming more and more complex while playing an increasingly crucial role, we proposed an automated approach to formal modeling and verification of requirements according to the recently issued standard ISO 26262. We acknowledge that formal verification techniques are often seen as complex and highly sophisticated methods that may not be easily applicable to concrete industrial use cases. In this work we have addressed exactly this challenge by only minimally exposing the theoretical complexity of the approach. In fact, system models and behaviors are expressed by means of SysML, a well-known modelling language that most people with an industrial background are already familiar with. According to our approach, demonstrated as a plugin implementation in the Topcased environment, formal models are extracted from the SysML requirements specifications, by resolving variation points. These models can then be used to formally verify, in an automated way, that requirements, with their corresponding behavioral diagrams, expressed at different levels of abstraction, are related by the correct relationships specified at system design time. Moreover, starting from the same formal models, it is possible to automatically generate test cases that can be used for requirements-based testing, an alternative way to verify refinement relationships.
The fact that the proposed methodology hides the complexity of formal notations to the user is an important result about usability. In order to also prove the validity of our solution in real world use cases, we applied the methodology and its demonstrative tool chain to one main example derived from industrial use cases, which is an e-shift use case proposed by FCA. According to the results of the experiment, in which a team of engineers from CRF without specific training in formal methods performed safety requirements specification and verification, the proposed approach was evaluated feasible and user friendly enough by the engineers, also showing adequate performance of the automated tools employed. At the same time, it was recognized by the engineers involved that the formalization of requirements, even with the proposed approach based on state machines, requires considerable effort. However, this effort permitted the achievement of a formal verification of requirements which would not be possible to obtain otherwise without employing personnel with specific training in formal methods.
We leave as future work a more extensive evaluation of the proposed approach and toolchain on other use cases and with other teams of engineers.
Declaration of Competing Interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
Acknowledgments
The work described in this paper has been partially supported by the VeTeSS European research project (grant agreements no. 295311).
References
[14] G. Bahig, A. El-Kadi, Formal verification of automotive design in compliance to influence the work reported in this paper.
|
{"Source-Url": "https://iris.polito.it/retrieve/handle/11583/2785894/311398/1-s2.0-S2215098619306147-main.pdf", "len_cl100k_base": 11826, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 39598, "total-output-tokens": 14574, "length": "2e13", "weborganizer": {"__label__adult": 0.000507354736328125, "__label__art_design": 0.0006389617919921875, "__label__crime_law": 0.0005407333374023438, "__label__education_jobs": 0.0015993118286132812, "__label__entertainment": 0.0001285076141357422, "__label__fashion_beauty": 0.0002980232238769531, "__label__finance_business": 0.0005879402160644531, "__label__food_dining": 0.0004901885986328125, "__label__games": 0.0012149810791015625, "__label__hardware": 0.0031490325927734375, "__label__health": 0.0006279945373535156, "__label__history": 0.0005545616149902344, "__label__home_hobbies": 0.0001914501190185547, "__label__industrial": 0.0021305084228515625, "__label__literature": 0.00044465065002441406, "__label__politics": 0.00040984153747558594, "__label__religion": 0.0007395744323730469, "__label__science_tech": 0.329833984375, "__label__social_life": 0.0001360177993774414, "__label__software": 0.01303863525390625, "__label__software_dev": 0.63818359375, "__label__sports_fitness": 0.0004508495330810547, "__label__transportation": 0.004001617431640625, "__label__travel": 0.0003001689910888672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67175, 0.03652]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67175, 0.36592]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67175, 0.92003]], "google_gemma-3-12b-it_contains_pii": [[0, 778, false], [778, 5376, null], [5376, 11651, null], [11651, 18198, null], [18198, 22113, null], [22113, 28700, null], [28700, 32762, null], [32762, 35357, null], [35357, 38168, null], [38168, 44909, null], [44909, 49635, null], [49635, 57878, null], [57878, 66992, null], [66992, 67175, null]], "google_gemma-3-12b-it_is_public_document": [[0, 778, true], [778, 5376, null], [5376, 11651, null], [11651, 18198, null], [18198, 22113, null], [22113, 28700, null], [28700, 32762, null], [32762, 35357, null], [35357, 38168, null], [38168, 44909, null], [44909, 49635, null], [49635, 57878, null], [57878, 66992, null], [66992, 67175, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67175, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67175, null]], "pdf_page_numbers": [[0, 778, 1], [778, 5376, 2], [5376, 11651, 3], [11651, 18198, 4], [18198, 22113, 5], [22113, 28700, 6], [28700, 32762, 7], [32762, 35357, 8], [35357, 38168, 9], [38168, 44909, 10], [44909, 49635, 11], [49635, 57878, 12], [57878, 66992, 13], [66992, 67175, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67175, 0.05814]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
ba09302eb38c61fde313e2094115fae2af36e498
|
<table>
<thead>
<tr>
<th><strong>Title</strong></th>
<th>Interactive Teachable Cognitive Agents: Smart Building Blocks for Multiagent Systems</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Author(s)</strong></td>
<td>Subagdja, Budhitama; Tan, Ah-Hwee</td>
</tr>
<tr>
<td><strong>Date</strong></td>
<td>2016</td>
</tr>
<tr>
<td><strong>URL</strong></td>
<td><a href="http://hdl.handle.net/10220/41917">http://hdl.handle.net/10220/41917</a></td>
</tr>
<tr>
<td><strong>Rights</strong></td>
<td>© 2016 IEEE. Personal use of this material is permitted. Permission from IEEE must be obtained for all other uses, in any current or future media, including reprinting/republishing this material for advertising or promotional purposes, creating new collective works, for resale or redistribution to servers or lists, or reuse of any copyrighted component of this work in other works. The published version is available at: [<a href="http://dx.doi.org/10.1109/TSMC.2016.2531656">http://dx.doi.org/10.1109/TSMC.2016.2531656</a>].</td>
</tr>
</tbody>
</table>
Interactive Teachable Cognitive Agents: Smart Building Blocks for Multiagent Systems
Budhitama Subagdja and Ah-Hwee Tan, Senior Member, IEEE
Abstract—Developing a complex intelligent system by abstracting their behaviors, functionalities, and reasoning mechanisms can be tedious and time consuming. In this paper, we present a framework for developing an application or software system based on smart autonomous components that collaborate with the developer or user to realize the entire system. Inspired by teachable approaches and programming-by-demonstration methods in robotics and end-user development, we treat intelligent agents as teachable components that make up the system to be built. Each agent serves different functionalities and may have pre-built operations to accomplish its own design objectives. However, each agent may also be equipped with in-built social-cognitive traits to interact with the user or other agents in order to adapt its own operations, objectives, and relationships with others. The results of adaptation can be in the form of groups or multiagent systems as new aggregated components. This approach is made to tackle the difficulties in completely programming the entire system by letting the user teaches or exemplifies its components towards the desired behaviors in the situated context of the application. We exemplify this novel method with cases in the domains of human-like agents in virtual environment and agents for in-house caregiving.
Index Terms—Learning Systems, Cooperative Systems, Software Engineering.
I. INTRODUCTION
Developing a system consisting of interacting elements may require considerable efforts to specify how it behaves appropriately according to its desired properties. Commonly, the system's behavior and functionality are carefully considered and designed before it is realized in the running context. This issue is conventionally tackled by abstracting the problem and the system using a programming or modeling language. In most current software engineering practices, the abstractions are constructed through coding processes which then the desired system can only be separately executed or deployed.
Different engineering paradigms, like structured, functional, or object orientation methodologies, offer means to manage the intricacies by promoting modularity. Contemporary models like component-based, services-oriented architecture, and cloud computing have also offered reusability and flexibility. Another new paradigm considers multiple autonomous agents working together in the system. They interact and communicate with each other in the same environment. Multiagent System [18] can be considered as a set of computational agents each with its own objectives. They interact and communicate with each other in the same environment.
Although the above approaches have offered encapsulation that hides the developer from the intricate details letting one to focus on more important matter, the assumptions are still that the abstraction or program code are detached from the running context.
In this paper, we present a radical approach of software engineering in which the human user interacts directly with smart components that make up the system in its running context. The component can be considered as a situated (semi-) autonomous agent that can be taught by the user through instructions and examples. This approach is not just simplifying the development process but also allowing it to be conducted during its deployment. The system can be taught through instructions or demonstration while it interacts with the real user in the relevant context. Inspired by teachable and programming by demonstration approaches like in smart applications [12], [7] and robotics [2], the challenges to tackle include how to deal with incompleteness, inconsistency, and error-prone instructions or demonstrations provided by the user. The uncertainty of the instructor intention requires the learner to make guesses, inferences, predictions, or sometimes ask for clarification which are also the common issues to tackle in designing collaborative user interface [15], [12], [13].
The contributions provided in this paper are the software framework for developing interactive multiagent systems allowing end-users or non-technical experts to be dominantly involved in the development process by teaching or instructing each elementary unit (building block) that makes up the system. The teachable feature is applied not just to serve the user needs or tasks but also to allow a non-technical instructor to specify how each component of the system behaves and relates to each other. The instructor can communicate with each component or a group of components directly in order to instruct, inform, or ask something related to the tasks or operations in hand at runtime. To simplify the process, each component is attributed with intuitive mental notions (e.g belief, desire, intention) and procedural knowledge (e.g rules or plans) similar to BDI agent model [14] so that it can be perceived as an autonomous agent that can reason and understand the tasks by the instructor.
Parts of the novelty of the proposed approach include embeddable capabilities of learning and teachable features to a pre-existing domain level component with specific operations and functionalities so that it can be associated with mental notions of itself and other agents. Thus, the instruction can
be targeted to particular components so that they can reason about and coordinate with each other. Similar notions are used to represent users and instructors so that the teachable features can handle multiple targeted end-users and collaborating instructors as well. Each component may also deal with uncertainties in the instructions by pro-actively asking the instructor for confirmation or clarification. It is worth noting that the proposed framework does not emphasize the intelligence capability of a single component to solve the problem. Instead, the use of multiple components and their interactions with the instructor and each other as a whole may produce the solution to the complex domain problem.
As proofs-of-concept, we demonstrate how the framework can ease the development of adaptive software or applications in their actual runtime context. Simulations of virtual campus and aging-in-place demonstrate that the components can be taught to respond in various ways to different contexts of end-user behavior in virtual environment.
This paper is organized as follows. Section II discusses existing related works. Section III describes the proposed framework and the mechanisms of the teachable components. Section IV exemplifies the implemented models.
II. RELATED WORK
Teachable systems and applications for end user development have been around for decades to enable a lay person to demonstrate the process in accomplishing the tasks of using the application [12], [7]. The system’s responses to the demonstration can range from a shallow-level of macro-recording to a deep generalization of the user actions. Usually, software applications employing this feature are made to learn procedures which are commonly performed manually by the user.
Most of them are made as assisting agents that watch the user interaction "over-the-shoulder" while creating the model of the user and the plan to accomplish the task. These agents require a model of cognition to reason about the user intention and the tasks taught to accomplish. Various types of cognitive architecture (e.g SOAR [11], ACT-R [1], BDI (Belief Desire Intention) framework [14]) have been used as the reasoning engine that drives the reasoning processes of the agents. Some of these cognitive models may also support learning by generalizing the decisions and outputs to deal with the unanticipated conditions. For example, in SOAR [11], new production rules may be created that summarize the processes that solve the impasse conditions. Other models suggest adaptation of procedural knowledge or recipes in BDI architecture through the execution of meta-level plans initiated by similar impasse conditions [16] or by induction of decision trees [8]. All these learning are assumed to be conducted autonomously in which the agent decides when to learn and to generalize knowledge by itself based on particular algorithms or programmed knowledge. The reasoning processes comprised in the learning still need to be described using a particular symbolic representation or programming language, even though the language itself can be generic, abstract, and expressive for many different real situations.
Most, if not all, of teachable applications with cognitive models mentioned above are made to be able to adapt with the needs of a single user. In this case, the main assumption is that there is only a single intelligent agent handling all the processes of learning from the user and the applications of all the learnt knowledge. Consequently, all computational and adaptation burdens must be handled by a single entity of computational agent. Moreover, the goal of the learning (or demonstration) is mainly to help or support the tasks of the end-user.
In robotic domain, programming by demonstration has been considered to be the approach beyond learning for a particular task. Since a robot may include a complex intertwining set of operations, demonstrating a robot requires more variations of interactions and mechanisms [2]. In contrast to teachable software or applications, the aim of a demonstrable robot is usually to aid the development of the robot behavior rather than to help the end user to accomplish the tasks. Beyond a single agent that "watches over-the-shoulder", robotic programming by demonstration has been considered to include multiple robots to be taught simultaneously in a coordinated fashion [6], [3]. In this case, the robots must identify the instructor intention and coordinate with each other to realize the desired objectives. The current multi-robots learning still adopts the autonomous learning that the user or external human interventions must be minimal. Although it can relieve the user from extensive involvements in the development process, letting agents learn by themselves may also produce undesirable effects. Given that incoming information or examples may be incomplete or erroneous, it is useful to let the user know about the actual conditions internally so that user can react to it and fix the problem immediately. Instead of relying on itself, the agent may get help from the user or a human participant.
In online and interactive programming by demonstration, the robot may also provide feedback in terms of social cues to help the developer to understand the internal state of the robot without looking at the specific trace of its running program. For example, one approach employs emotive cues on the robot’s embodiment to indicate the condition of learning [4] (e.g thinking, confused, excited) so that the teacher may adapt his/her teaching strategy when needed. Active Learning (AL) approach can also be employed to let the robot use different types of queries asked at the right context [5].
The proposed teachable framework in this paper adopts a similar objective to most demonstrable robotics approaches that the teaching-learning process is to simplify and ease the development of robots behavior but to employ it in software or application development. We employ BDI model to let the components in the system predict and anticipate the user intention from instructions and provide meaningful feedbacks regarding the development. The instructions can be targeted to particular components or groups of component while they are predicting the user’s intention and inferring the operations to learn. This approach lets the whole system to be developed through a collaborative process among the smart components and the user.
III. AGENT ARCHITECTURE AND TEACHABLE FRAMEWORK
In this section, we describe the teachable framework which includes the software architecture, learning mechanism, and protocols. A teachable component is a wrapper object that encloses a domain-specific object or service that may interact directly with the domain environment. It encapsulates all methods and functionalities related to the task domain.
A. Agent Architecture
A teachable component is an active instantiation of a running object or program that can be customized or reconfigured by the user at runtime. The component may sense and take action on its domain environment autonomously. However, the user may communicate with the component to instruct or teach new tasks on the run. A domain specific object is enclosed within the component to serve some prescribed functionalities. Over time, the object may become more autonomous that some operations may be initiated or suppressed when certain conditions or events occur.
Figure 1(i) illustrates the teachable wrapper as an agent. As a part of the teachable component, agent façade controls the operations and execution of the domain object. It may receive status update or feedback from the domain object as a result of an operational call or control. It also makes the component teachable by the user (developer) and is able to communicate with other agents.
The façade maintains a collection of data structures representing BDI [14] mental notions (belief, desire, intention, and schema). The agent also maintains a finite trace of events and actions in episodic buffer. The trace facilitates learning and keeps the dialogs with the user and other agents in context. Figure 1(ii) shows the internal architecture of the agent façade with all the data structures. It receives all incoming events of the domain specific object. It can also access possible actions produced by the domain object to manipulate or update the state of the domain environment. In this way, the façade knows every signal received and every action initiated by the domain object. On the other hand, the façade may control the domain object by initiating an action directly without the corresponding events to trigger. It may also suppress or halt the execution initiated by the domain object.
Event and Assertion Representation
An event or action can be stated as an assertion. An assertion consists of attributes each specifies a condition that holds at a moment. An assertion \( P = \{p_1, ..., p_m\} \) is a set of attributes and \( P \in \mathcal{V} \) in which \( \mathcal{V} \) is the set of all possible assertions. Attribute \( p_i \in P \) can be expressed as \( p_i = (v(p_i), \eta(p_i)) \) wherein \( \eta(p_i) \) is the name or identifier of \( p_i \) and \( v(p_i) \) is the value or content of \( p_i \). For example, \( p_i \) can be expressed as \( \{\text{age} : 50\} \) to represent an attribute specifying that age is 50. \( v(p_i) \) can be a number or a text data. An attribute can also recursively be a list of assertions. This nested attributes-values representation make the assertion expressive enough to describe situations in the world and internal states of agents.
To measure how much an assertion implies or contained by another, implicitive match \( m_P \) can be defined such that, given two different assertions \( P_i \) and \( P_j \), \( m_P \) can be measured as follows
\[
m_P(P_q, P_r) = \frac{1 - |\delta(v(p_k^q), v(p_k^r))|}{\sum_{k=1}^{N} |v(p_k^q)|},
\]
where \( |v| \) is the absolute value of \( v \) and \( |v(p)| \) is the total value or magnitude of attribute \( p \). For a number-typed attribute \( p \), it can be simply written as \( |v(p)| = v(p) \). However, a different type of value may require a different way to evaluate. The magnitude of a text or string attribute can be equivalent to its number of characters or word. \( \delta(v(p_k^q), v(p_k^r)) \) above measures the difference between \( v(p_k^q) \) and \( v(p_k^r) \). For number-typed values, the difference can be \( \delta(v(p_k^q), v(p_k^r)) = v(p_k^q) - v(p_k^r) \). For text or string attributes, it can be based on the number of characters co-occured in both assertions with similar order. When the assertion consists of nested attributes, the difference and the total value can be measured recursively.
The implicitive match enables one assertion to be evaluated in an inexact manner to know whether it implies another or not. One assertion can be defined to approximately imply another for a certain matching treshold such that
\[
P_q \Rightarrow_P P_r \iff m_P(P_q, P_r) \geq \rho.
\]
In this case, \( \rho \) is the vigilance parameter or the matching threshold that \( P_q \) can be considered to (approximately) imply \( P_r \). For example, \( P_q \Rightarrow_P P_r \) holds when both \( P_q \) and \( P_r \) have the same assertion \{ \text{subject} : "user01", \text{age} : 25, \text{gender} : "female" \}. \( P_q \Rightarrow_P P_r \) still holds when \( P_q = \{ \text{subject} : "user01", \text{age} : 25 \} \). With a smaller \( \rho \), a small discrepancy may still be tolerated, so that, for instance \( P_q \Rightarrow_P 0.75 P_r \) still holds when \text{age : 20} is in \( P_r \).
Given two different but similar assertions \( P_q \) and \( P_r \), their values can be generalized by the function Gen\((P_q, P_r)\) such that
\[
\text{Gen}(P_q, P_r) = \{ p_k^q : v(p_k^q) \leftarrow \text{gen}(p_k^q, p_k^r) \}
\]
\[
\text{gen}(p_k^q, p_k^r) = \begin{cases}
v(p_k^q) & \text{if } v(p_k^q) = v(p_k^r) \\
? & \text{if } v(p_k^q) \neq v(p_k^r) \\
\text{null} & p_k^q \notin P_r,
\end{cases}
\]
where "?' is a don't-care condition that the attribute will always match (and be bounded) with any value of implicitive match. The null value indicates the omissioin of the corresponding attribute from the generalized set. For example, if \( P_q = \{ a : 10, b : 5, c : 15 \} \) and \( P_r = \{ a : 10, b : 3 \} \), then \( \text{Gen}(P_q, P_r) = \{ a : 10, b : ? \} \).
The generalization function Gen\((P_q, P_r)\) enables learning a new assertion based on the generalization of two different assertions \( (P_q \) and \( P_r) \).
BDI Mental Representation
Belief
The Belief data structure can be considered as a collection of assertions believed to hold or happen. For example, a belief
1The curve brackets for attributes are omitted for brevity.
assertion \{\text{start} : 10.30, \text{location} : \text{"corridor"}\} may denote that the agent believes that starting at time 10.30, the location is in \text{"corridor"}. It is retrospective when 10.30 indicates time in the past or it may be predictive if it is in the future. The assertion may also describe the action or operation conducted including its parameters or arguments. For example, \{\text{do} : \text{"walk"}, \text{distance} : 5, \text{unit} : \text{"step"}\} indicates that the agent has just walked 5 steps. The belief assertion may also be associated with another individual agent or group including the description of other mental states. For example, \{\text{belief} : \{\text{do} : \text{"walk"}, \text{distance} : 5, \text{unit} : \text{"step"}\}, \text{agent} : \text{"agent-01"}\} denotes the agent believes that another agent \text{agent-01} believes it has just walked 5 steps. Here, the \text{walk} action is not about its own action but the action of the other (\text{agent-01}). The \text{agent} attribute refers to the group of agents having the corresponding mental notion. In the example above, \text{agent} is a singleton referring to a single agent (\text{agent-01}). As illustrated in Figure 1(ii), the information about all known agents are maintained in \text{Groups} so that the agent’s assertions may refer to another agents as well.
**Desire**
The \textit{Desire} data structure consists of assertions each represents something not held yet or still wanted to be achieved. For example, a desire assertion \{\text{do} : \text{"walk"}, \text{distance} : 5, \text{unit} : \text{"step"}\} means that the agent has a desire to walk 5 steps, though it does not happen yet. The agent will no longer have the same desire when the assertion is already believed (or held in the \textit{belief} data structure). Just like in \textit{belief}, a desire assertion may refer to another agent’s (or group’s) mental states.
**Intention**
The \textit{intention} structure can be represented in two forms as follows:
- \textit{rule-based} intention with attributes specifying triggering conditions and the actions that will be initiated or executed when triggered. The general structure is as follows:
\[
\{\text{trigger-cond} : \{< \text{trigger attributes} >\}, \\
\text{actions} : \{< \text{actions that follows} >\}\}
\]
- \textit{plan-based} intention with attributes specifying the desired condition to achieve, precondition that makes it applicable (or executable), and the actions sequence to execute. Its general structure is as follows:
\[
\{\text{goal} : \{< \text{conditions to achieve} >\}, \\
\text{precond} : \{< \text{pre-conditions} >\}, \\
\text{actions} : \{< \text{actions to execute when applicable} >\}\}
\]
An incomplete assertion of intention (e.g., a rule assertion without the trigger attribute or a plan goal without actions) will initiate a search process or reasoning to complete the assertion. For example, when \{\text{goal} : \{\text{location} : \text{"classroom"}\}\} is put in the \textit{intention}, a search process will be initiated to find the \text{actions} part (e.g., through means-end reasoning, or asking the instructor to inform or to teach the actions). In this case, the assertion of \textit{intention} may contain actions specification for immediate execution or desired conditions pending achievement. The \text{actions} attribute may have a structure as follows:
\[
\{\text{actions} : \{< \text{sequence} : \{< \text{action} n >, ..., < \text{action} m >\} >\}\}
\]
\textit{Schema}
Similar to \textit{intention}, the \textit{schema} repository consists of rules and/or plans. A schema assertion can be a generalized or abstracted version of assertions in \textit{intention}. In other words, an intention is an instantiation of a schema as a recipe for actions. Given \text{P}_i as an assertion of intention instantiated from a schema assertion \text{P}_s, it holds that \text{P}_s \Rightarrow \text{P}_i. In this teachable framework, the target of learning are new updated schemas. A plan-based schema may be selected and instantiated as an intention when its goal attribute is implied by a desire selected in the intention and its precondition implies those in \textit{belief}.
**Deliberation and Execution Cycle**
As a BDI agent, all the data structures are continually interpreted and updated in a deliberation cycle [14]. It consists of basic operations such as \textit{belief updating}, \textit{generating options} to achieve, \textit{deliberation} by weighing the options, \textit{means-end reasoning}, and \textit{execution control}. The continual interpretation suggests that operations included in the execution cycle above are conducted concurrently. A step of operation or control may wait and require another operation to finish. However, independent operations can be executed concurrently. This also allows incoming input to be received and processed asynchronously.
Let \text{B}, \text{D}, \text{I}, \text{E}, \text{II}, and \text{M} be the collection of belief, desire, intention, schema, and episodic buffer respectively corresponding to the structures in Figure 1(ii). Algorithm 1 shows the abstract pseudo-code of the adapted deliberation cycle. Belief \text{B} is updated based on events from the environment and other related agents (E and \text{E}_A). In general, the execution loop goes through the normal cycle of basic operations in the deliberation cycles as mentioned above.

Instructor Intervention and Disruption
As shown in Figure 2(ii), the agent façade continually generate options regarding its own states and the other agents’ reflecting Algorithm 1. When the user instructs the agent to
do some actions, the user intervenes the running deliberation and the control process. The interventions may disrupt the on-going process of deliberation and execution, especially when they constitute changes to mental data structure (e.g., inserting, changing, removing items in $B$, $D$, $I$, $II$, or events). Due to the incomplete or erroneous message in the intervention, the instruction may not be correctly interpreted or false response can be generated to a disruption. For any event received from or about another agent, there are several possibilities regarding the meaning or intention in the message as follows:
1) The instructor just instructs the agent to do something without requiring it to learn anything. It can be a wrong or false instruction made by a mistake. It may also be made just for immediate testing or something irrelevant to learning.
2) The instructed action should be learnt but the whole presentation is due to complete since it may be a part of a long presentation sequence and the current instruction may still be on-going.
3) The instructed action is made as a response to a former particular condition or situation.
4) The instructed action updates or corrects a currently on-going actions or intentions.
5) The observed or informed action from another agent (or the instructor) is received as the action to follow or imitate.
The facade must detect a disruption when the user gives an instruction to the agent. The kind of disruption may range from simply an interruption that may halt an on-going planned execution temporarily to an intention that potentially keeps the agent from achieving another existing one. Once a disruption is detected, the agent may ask the instructor for confirmation or clarification while indicating the potential implications.
Besides user interventions, disruptions can be sourced from the internal deliberation cycles like failures in searching for the applicable schema or in executing actions. Different types of disruptions can be defined as external or internal disruptions as follows:
1) External disruption is coming from an external source of the agent like the instructor message, domain environment, or other agents communication that modifies (insert, remove, or update) $B$, $D'$, $D$, $I$, $I'$, or $II$. Different types of disruption event include mutual exclusive (mx), contradictory (contra), insertion (insert), and similarity (similar) indicating conflicting actions, contradictory assertions, insertion of a new assertion $P_i$, ($B^{old} \models_i B \cup P_i$), and a similarity (or a difference) between a new incoming assertion with an existing one in the corresponding intention or schema respectively.
2) Internal disruption is coming from the internal process of deliberation cycle. Different types of internal disruption include failed planning and failed execution indicating that no matching applicable plan can be found for desire assertions $D^*$ that $D^* \subset D$ and there are failed intentions $I^-$ that $I^- \subset I$ respectively.
A disruption is indicated as a disrupt type event. The disruption message contains not just the main incoming event description (event attribute) but may also include the current disrupted or affected assertion. For example,
\[
\{\text{event-type:”disrupt”, distype:”contra”, event:”instruct”, event:{do:”insert”, belief:{weather:”sunny”}}}, \text{affected:}{\text{belief:”weather:”rainy”}}\}
\]
indicates a possible contradiction when the agent is instructed to make belief that the current weather is sunny while currently it believes that it is rainy instead.
Algorithm 2: Interactive Learning Cycle
1 WHILE True
2 FOR every external disruption event $e \in E \cup E_A$
3 inform the instructor about the disruption, and ask for a response
4 WAIT until the instructor responds with event $e_i$
5 IF $e_i$ is an instruction to perform an action
6 ask what cause the choice of the instructor action
7 inform the instructor possible causes based on similar rule schemas $P_i^\pi$
8 WAIT until the instructor responds with event $e'_i$
9 IF $e'_i$ indicates a selection of $\pi^e \in P_i^\pi$
10 generalize $\text{actions}(\pi^e) \leftarrow \text{Gen}(\text{actions}(\pi^e), \text{actions}(e_i))$
11 ELSE IF $e'_i$ indicates an assertion $P_i^\pi$ as the cause of action in $e_i$
12 generate rule $P_i^\pi$ with $P_i^\pi$ as the trigger, and $\text{actions}(e_i)$ as the actions
13 insert the new schema $P_i^\pi \leftarrow P_i^\pi \cup \Pi$
14 ELSE IF the instructor indicates the actions are not finished yet
15 append the action to the sequence as $\text{actions}(e_i)$
16 ELSE BREAK
17 FOR every internal disruption event $e^* \in E \cup E_A$
18 IF $e^*$ indicates a failed planning for $D^*$
19 ask the instructor to show how to achieve the goal in $e^*$ by actions $\pi^e$
20 REPEAT
21 indicate all applicable $\pi^e \in \Pi$, in which $\text{goal}(e^*) \models \pi^e$
22 WAIT until the instructor responds with event $e_i$
23 IF $e'_i$ is to do action $P_i$
24 append $P_i$ to $\pi^e$
25 IF $e^*$ indicates a selection to $e^*$ as a plan to achieve $\text{goal}(e^*)$
26 generalize $\text{goal}(\pi^e) \leftarrow \text{Gen}(\text{goal}(\pi^e), \text{goal}(e_i))$; BREAK
27 IF $e^*$ indicates a selection to $e^*$ as an intermediate goal for $\text{goal}(e^*)$
28 append $\text{goal}(e^*)$ to $\pi^e$
29 IF $e^*$ is instruction to follow or imitate agent $i$
30 append observed action $P_i$ of agent $i$ as its own action to $\pi^e$
31 UNTIL $\text{goal}(e^*)$ is achieved or the instruction is dropped/canceled
32 IF $\text{goal}(e^*)$ is achieved
33 IF $\text{goal}(e^*)$ is achieved by another agent $j$ ($j$ can be the instructor)
34 append asking $j$ to achieve $\text{goal}(e^*)$ as a step in $\pi^e$
35 set $\text{goal}(\pi^e) \leftarrow \text{goal}(e^*)$; IF $\text{new} \leftarrow P_i \leftarrow \Pi$; BREAK
36 IF $e^*$ indicates a failed execution of planned actions in $I^-$
37 ask what is the cause that make the plan in $e^*$ failed
38 inform the instructor possible preconditions based on similar plan schemas
39 WAIT until the instructor responds with event $e_i^-$
40 IF $e_i^-$ indicates a condition that the plan in $e^*$ can be applicable
41 modify the plan schema in $e^*$ with the condition in $e_i^-$ as the precondition
Learning Schemas
Learning can be initiated by inserting a new intention to obtain information for generating schemas so that the disruption may be resolved and the computational burden to obtain and resolve the issues may be reduced in a similar situation in the future. Since the mechanism in the BDI architecture allows several intentions or goals to be active in parallel, the learning intention enables learning to be conducted concurrently with the main deliberation cycle. Consequently, the teaching process can be continuous and interactive as well while the domain specific tasks are conducted simultaneously.
Some domain independent rules can be constructed to learn rule-based schemas, but some other may be designed to acquire plan-based schema on-the-fly. As a schema, a learning rule can be made to trigger a sequence of actions allowing it to engage a long dialog or conversation with the user.
To simplify the matter, the overall learning rules are described as abstract execution cycles in Algorithm 2. In the algorithm, the learning process is considered as interactive processes between the learner and the instructor. When the event indicating disruptions or unanticipated conditions is received, the agent informs the potential issue to the instructor and asks for more advices to guide the resolution. Based on the instructor feedback, new rules or procedures can be learnt. A rule-based schema can be learnt by asking the instructor about what cause the action chosen by the instructor to resolve the disruption (as shown in Algorithm 2 line 3 to 16). On the other hand, when no matching schema can be found for a particular selected desire (as a condition initiating the disruption event), the instructor can teach the agent the series of actions to perform to achieve it (Algorithm 2 line 18 to 35). Similarly, when a plan execution fails, the instructor may respond by informing the agent the condition that should be held to prevent the failure (Algorithm 2 line 36 to 41) so that it can be used as the precondition attribute of the learnt plan-based schema.
Learning a schema may include generalization of attributes. In Algorithm 2, a selection of a similar schema as informed by the agent will be followed by generalization of the corresponding schema. For example, generalization of actions (line 10) is conducted after the selection (line 9). Another generalization is on the goal of a plan-based schema (line 26).

Fig. 3. (i) teaching agents to interact with multiple users; (ii) collaborative teaching by instructor and other participants.
When asked for advices, the instructor may also perform something or letting another agent to achieve the goal. In this case, the agent may socially learn by adding a step of action to ask for help from another more capable agent (or from the instructor) in the schema. As shown in Algorithm 2, when the goal is observed to be achieved by another agent (line 33), asking the other agent to achieve the goal (line 34) will be learnt as an action step in the schema. Learning the action steps to take to achieve the goal may also be based on the imitation or copying another agent’s actions.
Algorithm 2 (line 29 to 30) shows that the agent may be instructed to imitate the actions of another agent rather than generating the action by itself. However, the effectiveness of this imitative action depends highly on the specific implementation of the domain level component. The capability of observing and recognizing the actions and intentions of another agent or component is assumed to be domain specific. However, the capability to recognize the activity from other agents may still be learnt at the façade level through user instructions.
By associating an agent’s identity with an attribute of an assertion, an agent can learn to associate its tasks with another’s. This also enables the teaching-learning process to conduct in its social context that other parties may also interact with. As exemplified further in the next section, it allows the instructor to teach the agent on-the-run to interact with or to serve another user. It is worth noting that since the learning cycle as shown in Algorithm 2 is realized as intentions, the actual process is conducted concurrently with the main BDI cycle and other domain level processes.
### IV. Scenarios and Case Study
As proofs-of-concept, the teachable framework is applied to two different domains of application. The first domain is the teachable human-like NPCs (Non-Player Characters) in NTU Co-Space wherein the framework is exemplified as an approach of developing autonomous NPCs that roam and interact with user avatars in a custom-built virtual reality environment. It is to exemplify the interactive incremental process of learning that the component (as an agent) acquires new rules and plan-based schemas from the user instructions. The second domain is the aging-in-place simulation in which several agents act as in-house caregivers by providing advices and recommendations to the user in daily living. This second domain demonstrates the acquisition of rules or knowledge to deal with exceptions. The framework is exemplified based on scenarios that show a domain expert teaching the agents to collectively and cooperatively advise and persuade the occupant towards well-being and healthier lifestyle.
#### A. NTU Co-Space
NTU Co-Space is a multi-user online virtual environment representing a real actual place in the world including events happening in it (in this case the NTU campus) [9]. The user may explore the environment by controlling a human-like avatar to roam the environment and perform certain tasks. Inside the virtual environment, the user may meet and interact with other users’ avatars. However, it is also possible to encounter a number of (semi-) autonomous human-like NPC (Non-Player Character) each with its own personality, agendas, and tasks to perform [10].
To develop autonomous behaviors of the NPCs, the teachable framework can be applied so that rules and procedural schemas can be instructed at runtime. In the NTU Co-Space, the instructor can take over the control of the NPCs movements and actions. The instructor can also select any object in the virtual environment (e.g by mouse pointing and clicking) to obtain the options of what can be done with or to the object...
for selection. For example, when the instructor makes the NPC select an object (e.g., a coin) in the environment, the user interface shows the options of possible actions that can be applied to it. The instructor can also observe the agent’s mental state and may enter a command directly in a command line interface while performing some actions in the environment. Figure 4(i) shows the user interface in NTU Co-Space for monitoring and control of the agent. When an object is selected, a dialog is opened showing the options like in Figure 4(ii). Similarly, when another agent (or another user) is selected, options will be displayed (Figure 4(iii)) but with more elaborated items to select.
NTU Co-Space is implemented using Unity 3D game engine\(^2\). The parallelism aspect in the framework is made possible by the inherent feature of Unity 3D framework in which different scripting modules and game assets can have independent execution cycles.
In what follows, scenarios and illustrative examples in the use of the framework in NTU Co-Space will be explained from simple navigational tasks to complex interaction and collaboration.
**Simple Navigation Task**
---
**Scenario 1:** Simple Navigation Task
**Scene 1:** The instructor selects a desired location for the agent (the user points and mouse-clicks a location in the environment to set it as a desired condition of the agent).
**Scene 2:** Agent 1 selects the desire, finds a schema to achieve it, and execute the intentions.
**Scene 3:** Agent 1 moves towards the goal location (based on the intention selected).
**Scene 4:** The instructor intervenes the journey by turning the agent’s orientation following the side of an obstacle.
**Scene 5:** A disruption event fires, Agent 1 informs the user: “achieving at desired location is disrupted by following-object-side.”
**Scene 6:** The instructor continues following the pole side.
**Scene 7:** Agent 1 asks the instructor “why did you instruct me to following-object-side?”
**Scene 8:** The instructor selects the obstacle object building-part so that the agent perceives it and associates it with the reason of following-object-side action (disruption).
**Scene 9:** Generate rule schema and learn \{trigger-cond: \{object-type: "building-part", "actions": \{do: "following-object-side"\}\} \}
**Scene 10:** Agent 1 has a desire to be at frontdesk and an intention to move towards it.
**Scene 11:** Agent 1 moves towards frontdesk as the goal location.
**Scene 12:** In the middle of the path, Agent 1 updates its belief that \{object-type: "building-part", "actions": \{do: "following-object-side"\}\} is detected.
**Scene 13:** Agent 1 executes "following-object-side" to move around the obstacle before continuing the move towards the goal.
---
The first scenario (Scenario 1) shows a simple use of the teachable framework to develop a rule-based schema. This scenario illustrates how a new rule-based behavior schema can be acquired through a combination of interaction and instruction. In particular, the user wants to make the NPC develop a schema for avoiding obstacles supporting the existing navigation strategy to move from one place to another. Moving in a straight line towards the destination may fail since there can be objects or obstacles along the way potentially blocking the straight path (Figure 5). The agent needs a mechanism to avoid the obstacles.
To teach the agent the avoidance strategy, the instructor can take over the control intervening the on-going execution (Scene 4). The intervention creates disruption that initiates the agent’s attention to the actions taken over by the instructor (detected as following-object-side by the agent in Scene 5). As a part of the interactive learning strategy, the agent asks the reason of that particular intervention to the user (Scene 7). Based on the user response, a new rule (schema) can generated as in Scene 9. Based on the learnt schema, the agent will execute the same action following-object-side the next time it encounters building-part to avoid the obstacle (Scene 12-13).
---
\[^2\]http://unity3d.com/
---
**Interactive Planning**
The second case (Scenario 2) demonstrates the teachable feature for developing inter-agent activities beyond learning the internal schema. In this scenario, a group of two NPCs is taught to interact and serve an approaching player, as an avatar (left-hand side of Figure 6a). Both NPCs have different capabilities and particular knowledge to interact with the player.
---
**Scenario 2:** Interactive Planning
**Scene 1:** Player 1 approaches Agent 1 and Agent 2.
**Scene 2:** Player 1 asks: “I want to go to the thesis section in this library?”
**Scene 3:** Agent 1 replies Player 1: “You may go there”, and insert the intention to make Player 1 at location thesis-section.
**Scene 4:** An internal disruption event of Agent 1 fires, Agent 1 fails to find a matching schema for the desire.
**Scene 5:** Agent 1 asks the instructor: “How can I make Player 1 at location thesis-section?”
**Scene 6:** The instructor asks Agent 2 to make Player 1 at location thesis-section.
**Scene 7:** Agent 2 sets the intention to make Player 1 at location thesis-section, finds a matching schema, and initiates the intention execution.
**Scene 8:** Agent 2 asks Player 1: “Follow me!”, and move to the intended location while Player 1 follows.
**Scene 9:** Eventually Agent 2 and Player 1 arrive at location thesis-section.
**Scene 10:** Agent 1 receives the event that Player 1 is at location thesis-section indicating the desire has been achieved.
**Scene 11:** Agent 1 appends the action to ask Agent 2 to make Player 1 at location thesis-section as the step of action to in the schema to achieve the same goal.
---
The scenario demonstrates group reliance in planning. Here, it is assumed that only Agent 1 as a virtual librarian NPC can interpret the user inquiry (Figure 6) as shown in Scene 2 and 3. It adopts the predicted goal of the user to be at the particular...
location (thesis-section) as shown in Scene 3. Since no schema is available to directly achieve the player goal, Agent1 asks the instructor for possible actions to achieve it. However, the instructor responds the inquiry by asking Agent2, instead, to realize the goal (Scene 6). In this case, Agent1 is taught by the instructor to ask for help from another agent in the group. In this case, Agent2 is asked by Agent1 to respond according to the user needs (Scene 9-11). This feature of learning delegating actions is the part of the learning mechanism as shown in Algorithm 2 line 32 to 33.
The scenario above demonstrates the learning to delegate some tasks to another agent. This approach of learning can also be useful when the system includes multiple users letting the agents learn directly from the real context of the system use. In this second scenario, however, only a single agent learns even though the schema learnt involves another agent.
\[\text{Agent2, Agent3, Agent4, and Agent5 altogether must be at location West_Lobby, each member would try to make every other member to be at the same place besides itself. Some members in the group can be instructed to pursue their actions (Agent1 and Agent5 in Scene 4) but some others may be made to imitate others letting them learn from each other (Scene 6). In the end, all members learn from each other (Scene 9).}\]
\[\text{Scenario 3: Group Learning}\]
\[\text{Scene 1: The instructor set the group (consisting of Agent1, Agent2, Agent3, Agent4, and Agent5) to have desire to be at location West_Lobby}\]
\[\text{Scene 2: Internal disruptions fire from all members of the group since no exact matching schema can be found to achieve the goal; every member informs the user about the disruption}\]
\[\text{Scene 3: Agent1 and Agent5 indicate plan schemas that can bring (only) oneself to be at West_Lobby but not together with the other members}\]
\[\text{Scene 4: The instructor select the partially match schemas and let Agent1 and Agent5 execute them}\]
\[\text{Scene 5: Agent1 and Agent5 execute the schemas and move to the location West_Lobby}\]
\[\text{Scene 6: The instructor instruct Agent2, Agent3, and Agent4 to follow (imitate) Agent1 and Agent5}\]
\[\text{Scene 7: All members arrive at the destination location West_Lobby}\]
\[\text{Scene 8: Agent1 and Agent5 generalize their goal schemas to include all members of the group}\]
\[\text{Scene 9: Other members learn the schemas to be at West_Lobby together}\]
\[\text{Fig. 7. Teaching collaboration among members of the group.}\]
**Group Learning**
When several agents are grouped together, they may behave like a single entity but with more complex goals and contexts than any individual. When the user asks a group of agent to achieve a goal, the outcomes may likely be very different when the same request is given to a single agent. For example, the desire of Agent1 to be at location West_Lobby may only make Agent1 move to the location (if the right schema is available) or ask the instructor for help. The instructor can just control the agent to navigate to the location as described in Algorithm 2 line 21 to 34. However, if the desire is given to the group so that, for example, Agent1, Agent2, Agent3, Agent4, and Agent5 altogether must be at location West_Lobby, each member would try to make every other member to be at the same place besides itself. Some members in the group can be instructed to pursue their actions (Agent1 and Agent5 in Scene 4) but some others may be made to imitate others letting them learn from each other (Scene 6). In the end, all members learn from each other (Scene 9).
the same capability to recognize other agents activities.
The scenarios from the NTU Co-Space case study above suggest that teaching can be conducted in both level of internal process within a single agent and at a group level to learn interdependencies among different agents in the group. The user may start with some sketches of initial grouping of components which can either be internal activity states or entire agents. However, the internal ones may anytime be created, removed, or replaced by the execution mechanism of the agent architecture. In the level of individual agents, the components or modules are persistent and may instantiate for the entire system lifetime.
One important feature of the framework as shown in the scenarios above is teaching the agents to serve or interact with the target end users directly at runtime in the situated environment as illustrated in Figure 3(i). When the deployed system will be used by or interacting with different users, this model of agents as trainees enables the learning by instruction to be conducted in the proper context.
**B. Teachable Caregiving Agents for Ageing-in-Place**
We also apply the framework for developing coordination mechanisms of multiple assistive agents in a simulated smart-home environment in the domain of in-house caregiving for elderly (Aging-In-Place) [17]. The virtual home environment is built with a virtual elder occupant residing as the subject. The virtual occupant is initially built to follow a routine habit of daily task. Four computational agents are included in this case. Two agents collect data from the virtual environment and produce beliefs about the subject’s activity of daily living. The other two are health-caring agent and butler agent that concern the subject’s health (physical and mental) and quality of daily life (happiness, emotion, and social) respectively.
In the simulation, the artificial occupant is made as an avatar in which its behavior can be controlled manually by the user or can follow a programmed script. The implementation of the occupant’s avatar is similar to the NPCs in NTU Co-Space. However, it also consists of an assembly of virtual assistant agents each is designed to serve the user for different aspects of caregiving. Different agents may take particular roles ranging from updating perceptual information to persuading the user. An agent by itself is fully functional as an application which can be deployed independently. Two different persuasive agents have been implemented. **Smart butler** is a virtual assistant resided in a mobile device (smartphone or tablet) that focuses on daily activities, social connections, and sustainable living. It mostly takes the role as a reminder and recommender in relation to daily living and social events. On the other hand, **Virtual nurse** is a virtual assistant running in a dedicated computing device or personal computer displayed with human-like appearance. It can communicate naturally with the user using voice-based interaction. The main role of the nurse is a healthcare advisor that gives advice and persuades the user regarding choices of healthier lifestyle.
Figure 8 shows the multi-agent system for aging-in-place wherein heterogeneous smart applications interact with each other as assistant agents through the shared repositories. The agents can be heterogeneous in which each one may have particular specialties and capabilities. Each agent can work independently to address a particular issue by monitoring and interacting naturally with elderly. The domain also allows collaborative instructions involving other parties of human participants (Figure 3(ii)).
The teachable model is embedded into two of the agents above that act as advisors. The domain expert can control the agents in advising the occupant. Figure 8(ii) shows the screenshot of the simulation with 3D virtual environment GUI in a web browser (implemented with Unity 3D and HTML5). Figure 8(ii) shows that the instructor can observe the options, predictions, and scheduled intentions on the activity timeline display. The domain expert can also interact directly with the agents as an instructor using a natural language interface. In the dialog, the instructor may indicate the selection of an agent belief or intention by choosing the activity bar in the timeline. The corresponding activity can be suppressed or modified on the fly.
Here are example scenarios excerpted from the interaction between the domain expert as the instructor and the advisor agents in providing the appropriate advices to the virtual occupant.
**Rule Generalization**
**Scenario 4: Rule Generalization**
| Scene 1: | virtualnurse advises the occupant to take a medicine: "Hi, it’s time for you to take the medicine". |
| Scene 2: | smartbutler believes: the occupant is less active. |
| Scene 3: | smartbutler advises the occupant: "It’s a good time to get some fresh air. Going out perhaps?". |
| Scene 4: | The instructor selects the recent smartbutler advising action (by selecting it in the timeline) and stops its operation. |
| Scene 5: | smartbutler receives a disruption event about its the stopping operation. |
| Scene 6: | smartbutler asks the instructor: "why did you stop my dialog asking: 'It’s a good time to get some fresh air. Going out perhaps?' to the occupant?". |
| Scene 7: | smartbutler indicates a similar rule that previously a dialog ‘it’s a good time to exercise now’ is stopped because virtualnurse reminded the occupant to take the medicine. |
| Scene 8: | The instructor selects the similar rule as indicated so that smartbutler generalizes the rule and the association becomes stopping advising any activity whenever virtualnurse reminds her to take the medicine. |
| Scene 9: | smartbutler asks the instructor: “Do you mean IF I detect that Virtual Nurse advise the occupant to take medicine, THEN I drop my intention to recommend activity? (Yes/No)”.
| Scene 10: | The instructor responds by answering ‘Yes’ and smartbutler learn by generalizing the rule to suppress its recommendation. |
This scenario demonstrates the generalization of actions description based on a previously learnt rule in the context of conflict detection and resolution. In Scenario 4, an advice provided by smart butler is conflicting with the virtual nurse’s. While virtual nurse is intending to let the occupant immediately take the medicine, smart butler suggests the occupant to go out instead (Scene 3) which likely may cancel out the intended effect of taking the medicine on time (Scene 1).
When the instructor stops the advising intention of smart butler (Scene 5), a disruption event is generated leading smart butler to question the reason of intervention to the instructor...
In the scenario, smart butler has previously learnt a similar rule which is also resulted when the instructor stopped its operation. As a general strategy for learning, smart butler indicates this similarity to the instructor (Scene 7).
The conflict can be resolved by letting smart butler to generalize its previously learnt rule on stopping the provision of a specific advice given the same condition of the virtual nurse activity (Scene 9). In this case, smart butler always suspend or stop the advice provision to the occupant whenever virtual nurse reminds the occupant to take the medicine.
**Recognizing False Alarm**
**Scenario 5: Recognizing False Alarm**
Scene 1: The occupant walks to the living room and lying down on the sofa.
Scene 2: smartbutler believes: occupant falls (agent detects lying pose as fall condition); virtualnurse believes: occupant is on the sofa in the living room (the agent can locate position more precisely in the living room).
Scene 3: smartbutler opens a dialog with the occupant: “are you okay sir? are you hurt?”.
Scene 4: The instructor selects the recent smartbutler action (from the timeline) and stops its operation so that the disruption event is received by smartbutler.
Scene 5: Smart Butler ask the instructor: “why did you stop my dialog asking: ‘are you okay sir? are you hurt?’ to the occupant?”.
Scene 6: The instructor selects the belief of smartbutler (in the shared timeline) that the occupant fell and remove it from the timeline (which is again signaling a disruptive event to smartbutler).
Scene 7: Smart Butler asks the instructor: “why did you remove my belief that the occupant falls?”.
Scene 8: The instructor selects the belief of smartbutler (in the shared timeline) that the occupant is on the sofa in the living room to indicate the cause.
Scene 9: smartbutler associates the condition that virtualnurse believes that occupant is on the sofa in the living room with the removal of belief that the occupant falls”.
Scene 10: smartbutler asks the instructor: “Do you mean IF I detect that smartbutler believes that the occupant is on the sofa in the living room, THEN I remove my belief that the occupant falls? (Yes/No)”.
Scene 11: The instructor responds by answering ‘Yes’ and smartbutler learn the new rule to update its belief.
In this scenario, the smart butler can be taught to suppress its own belief (detecting fall based on the lying pose) based on the other agent’s belief (Virtual Nurse) of the occupant’s location. In this case, the functionality of the domain module can be extended by incorporating beliefs or perception of another agent in the domain.
The smart butler agent has a limited capability to identify some critical conditions of the occupant. As shown in Scene 2, it concludes a fall condition only based on the occupant’s pose. It may generate a false warning and potentially a false response like in Scene 3.
The user can teach smart butler to suspend or cancel the response like in Scene 4 which triggers a disruption event and initiates the agent’s inquiry about the reason (Scene 5). Since no more information from the sensors can be derived by smart butler, the condition for cancelation can be the other agent’s action. As shown in Scene 9, smart butler put the identification of the occupant’s location by virtual nurse as a condition to cancel the default response of a critical warning.
**Cooperative Persuasion Dialog**
In this scenario, the instructor can teach more than one agents to cooperate in persuasion tasks. Smart butler may ask for help to the instructor whenever it fails to achieve the goal by itself. In Scene 3 Scenario 6, smartbutler asks the instructor for help since there is no more schema for persuading the occupant when the occupant is not interested. A cooperative behavior can be taught by instructing virtual nurse (Scene 4) to help smart butler by persuading the occupant (Scene 5) so that virtual nurse may learn to start to help the smart butler when it is asked for (Scene 8).
When virtual nurse successfully persuade the occupant, smart butler may detect the condition (Scene 10) and ask the instructor for confirmation to learn a new action to ask virtual nurse for help (Scene 11).
The rule learnt by virtual nurse above is still specific to the condition and intention of smart butler in the particular scenario. However, when a similar situation happens (e.g the occupant loses her interest to eat healthy food), the same rule may be put as an option so that virtual nurse can learn to always help smart butler whenever it asks for.
All scenarios on Ageing-In-Place domain show that relationships and connectivity among the agents enable incremental and scalable learning by a single component. Many agents can be taught together not just to do domain tasks independently but also to coordinate with each other. The agents can be taught together as a team. In a similar setting, more than one instructors may also be involved to teach the agents based on the same principles. Each instructor may take the control of a different agent while teaching it and collaborate with the other instructors.
**Scenario 6: Cooperative Persuasion Dialog**
**Scene 1:** smartbutler advises the occupant to do exercise as it is detected that the occupant has been sitting down too long: "It's a good time to do a little stretching".
**Scene 2:** The occupant does not follow what is advised and still sitting for long.
**Scene 3:** smartbutler can not find another plan to persuade the occupant and asks others for help to make the occupant intend to do the workout.
**Scene 4:** The instructor instructs the virtual nurse to intend that the occupant do the exercise.
**Scene 5:** virtual nurse knows how to motivate the occupant (has the schema) and starts persuading her: "do you know, working out for few minutes can reduce the effect of....".
**Scene 6:** virtual nurse receives disruptive event (instruction to insert an intention) and asks the instructor "why did you instruct me to make the occupant intend to do the exercise?"
**Scene 7:** The instructor selects the recent request for help by smartbutler.
**Scene 8:** virtual nurse asks the instructor: "Do you mean IF I detect that smartbutler ask for help to achieves that the occupant intend to do exercise, THEN I intend that the occupant intends to exercise? (Yes/No)"
**Scene 9:** The instructor responds 'Yes' and virtual nurse learns the rule.
**Scene 10:** smartbutler detects that virtual nurse has persuaded the occupant and the intention is achieved.
**Scene 11:** smartbutler asks the instructor: "The schema to achieve that the occupant intends to exercise includes asks virtual nurse to help to achieve the occupant intends to exercise? (Yes/No)"
**Scene 12:** The instructor responds 'Yes' and smartbutler learns the plan.
### V. Conclusion
We have presented a framework for developing situated interactive systems wherein the components of the system can be considered as autonomous agents that can be configured and teachable by the user. The framework offers a methodology of developing a system allowing end users or non-technical experts to teach the components at runtime. Each teachable component is an encapsulated set of domain level attributes and actions but possessing generic mental attributes like beliefs, desires, and intentions. In every step of its execution cycle, the teachable agent may indicate possible operations, goals, and intentions letting the instructor to decide if some intervention is necessary. During the learning, the agent may also indicate possible rules or procedural schemas that can be learnt based on similar knowledge that are pre-existing or learnt in the past. The instructor can teach not just the domain level operations but also ways to reason, to make decision, and to relate with other agents (or other human participants).
We have exemplified the interactive learning processes in our custom-built virtual characters in NTU Co-Space environment. The scenarios demonstrate how learning incrementally acquire knowledge and how imperfect or incomplete instruction can be dealt with similarity matching and interactivity. The framework has been applied to a virtual aging-in-place environment wherein a virtual occupant and some persuasive agents are teachable. The case study shows that the proposed framework allows a caregiver, as the domain expert, to integrate diverse intelligent capabilities through teaching and interactions. The scenarios also show that this instructional-based learning can be applied beyond a single agent but can be used to teach a couple or even a group of agents to coordinate and perform some tasks together.
There are many outstanding aspects and issues deserve further exploration and study. More comprehensive investigation including user evaluation is necessary to get more complete picture of the effectiveness of this approach for developing a large scale system or application.
### REFERENCES
|
{"Source-Url": "https://dr.ntu.edu.sg/bitstream/handle/10220/41917/Interactive%20Teachable%20Cognitive%20Agents-Smart%20Building%20Blocks%20for%20Multiagent%20Systems.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 13774, "olmocr-version": "0.1.48", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 45257, "total-output-tokens": 15796, "length": "2e13", "weborganizer": {"__label__adult": 0.0005679130554199219, "__label__art_design": 0.001946449279785156, "__label__crime_law": 0.0006213188171386719, "__label__education_jobs": 0.05224609375, "__label__entertainment": 0.0003352165222167969, "__label__fashion_beauty": 0.0003457069396972656, "__label__finance_business": 0.0008172988891601562, "__label__food_dining": 0.0006418228149414062, "__label__games": 0.0035152435302734375, "__label__hardware": 0.00208282470703125, "__label__health": 0.0013761520385742188, "__label__history": 0.0011358261108398438, "__label__home_hobbies": 0.0004248619079589844, "__label__industrial": 0.0010595321655273438, "__label__literature": 0.0012540817260742188, "__label__politics": 0.0005841255187988281, "__label__religion": 0.000903606414794922, "__label__science_tech": 0.279541015625, "__label__social_life": 0.0004496574401855469, "__label__software": 0.030059814453125, "__label__software_dev": 0.6181640625, "__label__sports_fitness": 0.0005555152893066406, "__label__transportation": 0.001087188720703125, "__label__travel": 0.0004315376281738281}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66650, 0.01688]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66650, 0.6333]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66650, 0.90262]], "google_gemma-3-12b-it_contains_pii": [[0, 1028, false], [1028, 6491, null], [6491, 12968, null], [12968, 19364, null], [19364, 24877, null], [24877, 25097, null], [25097, 32191, null], [32191, 37950, null], [37950, 43981, null], [43981, 47633, null], [47633, 54394, null], [54394, 58987, null], [58987, 66650, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1028, true], [1028, 6491, null], [6491, 12968, null], [12968, 19364, null], [19364, 24877, null], [24877, 25097, null], [25097, 32191, null], [32191, 37950, null], [37950, 43981, null], [43981, 47633, null], [47633, 54394, null], [54394, 58987, null], [58987, 66650, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66650, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66650, null]], "pdf_page_numbers": [[0, 1028, 1], [1028, 6491, 2], [6491, 12968, 3], [12968, 19364, 4], [19364, 24877, 5], [24877, 25097, 6], [25097, 32191, 7], [32191, 37950, 8], [37950, 43981, 9], [43981, 47633, 10], [47633, 54394, 11], [54394, 58987, 12], [58987, 66650, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66650, 0.05281]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
9aa57dc290243c69e82c212e45eecdf52c9f6907
|
Towards a Formal Foundation to Orchestration Languages
Mirko Viroli
Abstract
We introduce a formal framework for studying the semantics of orchestration languages for Web Services. Taking BPEL4WS language as reference case study, we define syntax and semantics of a core language to derive the interactive behaviour of a business process out from a BPEL4WS specification. This is realised by developing a process algebra which, other than usual operators for choice, sequential and parallel composition, features constructs of imperative programming languages, such as iterative cycles and variable assignment. These are meant to focus on the very notion of correlation, which is exploited by BPEL4WS to define a business process as the concurrent behaviour of several process instances.
Keywords: Orchestration languages, web services, process algebra.
1 Introduction
One of the hot topics in the Web Services technology is the development of orchestration languages. Orchestration languages specify relationships and constraints over the occurrences of interactions between existing Web Services: the resulting behaviour is called a business process. Orchestration engines can then be developed that take a specification and automatically implement the new Web Service realising the business process. Relying on orchestration languages is argued to support the development of complex services in a more coherent and robust way [16,20], simplifying their analysis, design, and deployment. Some orchestration languages emerged as proposals for a standardis-
ation in the Web Services technology, such as BPEL4WS (Business Process Execution Language for Web Services) by a consortium including Microsoft, IBM, Siebel System, BEA and SAP [21], and BPML (Business Process Management Language) by Sun Microsystems, Intalio, Sterling Commerce, and CSC [2].
The notion of Web Services orchestration is generally coupled with that of Web Services choreography: as orchestration is more concerned with the coordination of different Web Services, choreography is about the interaction protocol exposed by a single Web Service or business process. The two notions, however, are not completely distinct. For instance, BPEL4WS can be used both to describe orchestration and choreography issues; Starting from a core part defining abstract processes, two small extensions are introduced to deal with executable processes modelling orchestration issues, and with business protocols modelling choreography issues. On the other hand, BPML deals with orchestration issues only, building on top of the WSCI standard for choreography [3]. As we recognise the tight relationship and overlap between the two concepts, in this paper we choose to take BPEL4WS (sometimes BPEL for short) as a case study for studying the very notion of Web Services orchestration — even though at this time it is not clear which of the two will actually become standard. However, we believe that a significant part of our study and methodology could be applied to BPML as well, the details of which are left for future researches.
On top of a number of existing and loosely coupled Web Services — possibly implemented by different vendors and residing in different organizations — an orchestration language is then used to specify a complete, robust, and coherent business process out of them. In particular, such a language is meant to define the behaviour of a Web Service coordinating existing activities, by enforcing the exploitation of given interaction protocols, supporting different work sessions — also called process instances —, supporting long-running transactions, providing facilities to manage exceptions, and so on. From a Software Engineering perspective, the general task of an orchestration Web Service is not new, but is traditionally referred to as a coordination activity [9,13,19] — namely, ruling and governing interactions of different software components. Many existing coordination models have been studied and engineered since the introduction of the archetype coordination language LINDA [12] — JavaSpaces [11], TuCSoN [22], KLAIM [10] and Manifold [1] to mention a few —, some feature and idea of which have in fact be borrowed by orchestration languages.
In general, the coordination task is a particularly crucial one in a business scenario, since it is meant to include the logics that makes a set of different
software components become a *whole system* — an engineered artifact reliably and effectively serving its intended purposes. Therefore, it comes not as a surprise that coordination models and languages have been the subject of a thorough formal study, with the goal of precisely describing their semantics, proving their properties, and driving the development of correct and effective implementations. Significant examples are the process algebraic approach to Linda of [6], and the formal framework for coordination services of [23]. Most existing works in this direction rely on process algebra techniques, since they provide a convenient framework for formalising coordination models, for their intrinsic ability to handle the notion of interaction and of concurrent behaviour.
A similar approach is then promising for orchestration languages as well [16,15], with the primary goal of improving their existing specifications, which — as any other prose document — might sometimes be ambiguous, too compact on relevant aspects and/or too verbose on less interesting ones. Nevertheless, in the course of providing a formal model to orchestration languages such as BPEL, one observes that process algebras have been indeed considered as a reference, but new and interesting issues have been added which are worth being investigated. Most notably, other than typical process algebraic operators for sending and receiving messages, and composing activities in a concurrent, exclusive or sequential way, imperative constructs were introduced such as iteration cycles, variables and assignment, as well as ad-hoc mechanisms to deal with separation of a business process into different and isolated process instances. So, the goal of this paper is to study the relationships between all these constructs, providing a formal account to the meaning of BPEL specifications and to the behaviour of the corresponding business processes.
This is achieved by introducing a core language for BPEL4WS focussing on a strict subset of its features, and formally describing its (abstract) syntax and its operational semantics. The goal of this study is not to study the formal properties of some feature introduced by BPEL, as e.g. in [7,5]. Rather, following the intuition behind other core languages for the mainstream technology — Featherweight Java [14] being a remarkable example — our goal is to isolate a subset of the language, providing a precise, formal description of its semantics. In particular, in this paper we identify correlation as the novel mechanism that is worth to be investigated, as it is at the core of the relationship between a business process and process instances characterising the whole orchestration idea. This core language can thus act as a description tool completing the official specification, avoiding ambiguity and underspecification, and to enable formal study of properties — e.g. typing issues or behavioural aspects. Moreover it can serve as a basis for extensions studying
either other features of BPEL4WS (such as compensation and fault handlers), or proposals for adding new mechanisms.
The remainder of this paper is organised as follows. Section 2 briefly describes the BPEL4WS orchestration language, introducing a classical example of business process used to handle shipping of items, which is used throughout the paper as a case study to show the details of the model. Section 3 explains the goals and scope of our formal model, introducing the abstract syntax we use in place of true BPEL specifications. Section 4 provides an operational semantics to the core language, taking into account the necessary execution aspects of business processes, including process instances and variable assignment. Finally, Section 5 provides concluding remarks and discusses perspectives of future works.
2 Orchestration with Business Process Languages
2.1 BPEL4WS
BPEL4WS is an XML-based specification language for describing business processes orchestrating the interaction of different, existing and possibly dynamically emerging Web Services. As such, it builds on top of the WSDL language for describing the interface of Web Services [8]. This is specified in terms of port types, actions, and messages – which e.g. in an object oriented settings would roughly correspond to the interface types, the method names, and the method types, respectively. In particular, as far as BPEL is concerned, actions can have two kinds of interactive behaviour: one-way, when they are asynchronously invoked without waiting for any reply, or request-reply, in the case where a reply is actually expected.
A BPEL4WS specification is made of four declaration parts: the partner links, the variables, the correlation sets, and the activity realising the business process.
Partner links identify the relationship of the business process with the other Web Services it interacts to, by specifying the port types for both process/web-service and web-service/process interactions. It is worth noting that an orchestration language never directly refers to a specifically installed Web Service, but it rather refers to generic port types, which are to be bound at deployment-time or even dynamically at run-time. This abstraction is particularly relevant, since it enables also those scenarios where pools of Web Services are dynamically bound and unbound to a business process depending on load-balancing issues.
The key idea of a business process is that its global task is divided into different sessions, called process instances, each responsible for carrying on a
separate service or work for each user — whether this is a human or another service. To support this scenario, variables can be defined that can carry XML data values and messages, and which are used to define the state of each process instance. Most notably, variables can also contain partner links, that is, abstract references to other services: similarly to the π-calculus where channels are used to exchange names of channels [18], this mechanism is useful to express dynamic interconnecting structures.
Correlation sets are then introduced to identify those interactions that are pertinent to a given process instance, which is necessary in order to correctly dispatch messages between the various concurrent sessions. Each correlation set is a set of properties, which are aliases for parts of messages and are treated similarly to write-once variables: at a given time, for each process instance a number of correlation sets are active, and the values associated to all their properties uniquely identify the process instance. For instance, all the messages related to a given customer’s request must carry the same unique identifier, e.g. the order ID.
Finally, an activity is specified that describes the precise behaviour of the business process. Activities are generally built by composing basic ones through structured ones. Basic activities include the acts of sending and receiving requests and replies (invoke, receive, and reply), which can specify one or more existing correlation sets they must adhere to, or new correlation sets to be initialised. Among other basic activities, there are variable assignment (assign), synchronisation of internal concurrent activities through private links (source and target), waiting for a timeout (wait), and raising faults (throw). Structured activities realise sequential composition (sequence), guarded choice (pick), parallel composition (flow), iteration cycles (while), and multiple cases (switch).
2.2 A Case Study
As a reference case study, in this paper we consider the shipping service described in the official specification of BPEL4WS [21] (Section 16.1). In spite of its simplicity, this example covers most of the language features we are interested in, including correlation sets, variables, and flow control structures.
This example describes a Web Service realising a service handling the shipment of orders requested by customers, which are themselves modelled as Web Services. Two types of shipments are handled: a customer may require the orders to be atomically shipped, in which case a single ship notice callback is sent to the customer; or it may specify an uncompleted order, in which case the items are shipped in different stages, sending a different ship notice each time.
Following the schema presented in previous section, the BPEL specification defines partner links, variables, correlation sets and the business activity. Only one partner link is specified here representing the customer service: the customer invokes the service by a one-way request named shippingRequest, the service provides notices by executing one-way invocations to the customer, by action named shippingNotice. Shipping request messages are made of three parts: an orderID integer, a complete boolean specifying whether the request is to be treated atomically or not, and an itemsTotal integer denoting the number of items to be shipped. Shipping notice messages are made of the orderID integer and the itemsCount integer, representing the number of items currently shipped. Three variables are used in this business process: shipRequest for storing the received message, shipNotice for storing the message to be sent, and itemsShipped for counting the amount of items already shipped. Only one correlation set is defined which contains the property orderID: process instances are then uniquely characterised by the same order identifier. Finally, the activity realising the business process is of the kind shown in Figure 1. There, underlined parts do not represent actual XML code, but are rather placeholders informally describing a more complex XML code, whose details are not reported for the sake of brevity.
The algorithm realised is as follows. As the request is received, if its complete part flag is true a reply is immediately invoked with the same itemsCount. Otherwise, a while iteration is executed. Each time, itemsCount part of the shipNotice message is assigned to the special identifier opaque, which means that the result of the assignment is non-deterministic — modelling e.g. the interaction with some back-end service which is not interesting to model. Correspondingly, a message is sent to the customer notifying the number of items shipped. When this number reaches the total amount requested by the customer, the process instance terminates. In particular, all the invoke and receive activities specify are linked to the correlation set, so that interactions carrying the same orderID are bound to the same process instance, representing a session of work with a customer.
3 A Formal Specification of BPEL4WS
In this paper we introduce a formal model for the behaviour of orchestration services adhering to BPEL4WS specifications, providing a formal account to the existing informal specification [21]. BPEL4WS indeed features a relatively large and heterogeneous set of constructs, mechanisms and details: providing a full formalisation is out of the scope of this paper. Rather, following the usual research approach in the context of programming languages [14,6], we find
useful to focus on a smaller yet significant subset of the language, providing a core language of the features of interest.
3.1 Modelling Choices
Our goal here is to study the very notion of process instance, that is, the idea that a single business process is actually constituted by different sub-processes, each representing a different interaction session. This aspect, represented in BPEL by the mechanisms of correlation sets and of variable assignments, is at the root of the whole orchestration approach, and it thus deserves a careful investigation. Moreover, such a study gives us the chance to deepen the
relationships between programming constructs typical of the process algebra approach (such as parallel composition and choice), others of imperative languages (variables and their assignments), along with the novel declarative approach to process instances introduced through correlation sets.
Thus, our core language intentionally neglects a number of interesting aspects such as timeouts, fault handlers, compensation handlers, reconfigurability of partner links, XML data representation, and so on. Including these mechanisms would not be relevant to the end of studying the aspects we are here interested in; rather, they can be introduced later on top of our language in a mostly orthogonal way, so as to provide a complete formal account of BPEL4WS.
Syntactically, the language we introduce is an abstract version of a subset of BPEL4WS: even though most constructs have a one-to-one translation into the core language, sometimes the mapping needs some accessory work which is only informally described for simplicity of treatment. The operational semantics follows the standard approach of labelled transition systems over process algebras, describing how a behaviour specification moves to another as internal computations or interactions with the environment occur. Following the abstraction used by BPEL4WS when describing partner links, we do not describe the details of interactions with other Web Services and related properties such as synchrony, directness, transport protocol, and the like. Rather, any interaction is characterised by (i) its meaning (invocation/reply), (ii) its direction (sent or received by the business process), (iii) the involved peer (the partner link), and (iv) the content (the message carried).
The language we introduce is not equipped by the necessary additional formal structure to check for the semantic correctness of a specification, e.g. verifying that variables are used before initialised, correlation sets are not initialised twice, and so on. As this would lead to a quite remarkable modelling tool, whose importance for the Web Services technology is e.g. discussed in [16], it is not analysed here for it would likely be the subject of our future research. As a result, we also avoid to take into account the parts of a specification dealing with declaration of properties, variables, correlation sets, port types, etcetera, focusing instead on their exploitation and their influence on the business process run-time behaviour.
3.2 Abstract Syntax
Let $u$ be a meta-variable ranging over integer and boolean values, $v$ over variables (of all values), and $p$ over properties (forming correlation sets). Meta-variable $l$ ranges over end-points, which can be conceptually seen as triples of a partner link, an action name, and a direction: they uniquely identify the
\begin{align*}
w &::= v \mid p & \text{Variables and properties} \\
e &::= \text{opaque} \mid u \mid v \mid f(\overline{v}) & \text{Expressions} \\
s &::= 0 \mid & \text{Empty specification} \\
&\quad \text{send}(l, \overline{v}, \overline{w}) \mid & \text{Sending a message} \\
&\quad \text{recv}(l, \overline{v}, \overline{w}) \mid & \text{Receiving a message} \\
&\quad \text{while}(e)\{a\} \mid & \text{Iteration structure} \\
&\quad \text{switch}(e)\{a : a\} \mid & \text{Switching structure} \\
&\quad \text{assign}(v, e) \mid & \text{Variable assignment} \\
&\quad \text{source}(\lambda) \mid \text{target}(\lambda) \mid & \text{Internal links operations} \\
&\quad a; a \mid (a \parallel a) \mid a + a & \text{Sequence, parallel composition, and choice} \\
a &::= s & \text{Activity}
\end{align*}
channel through which an interaction occurs. Given any meta-variable \(x\), we let \(\overline{x}\) range over sequences of \(x\) elements (such as \(\langle x_1, x_2, \ldots, x_k \rangle\)); correspondingly, \(x_i\) is the \(i^{th}\) element of one such sequence, \(x \in \overline{x}\) is used to state that \(x = x_i\) for some \(i\), and symbol \(\bullet\) is used for the void sequence. The syntax of the language we introduce is shown in Figure 2. Notice that while structured activities resembling very well known process algebraic operators are represented by the standard theoretic notation, we used for the other activities an abstract syntax resembling BPEL language.
Meta-variable \(w\) ranges over both variables and properties: their assignment to values defines the current state of a given process instance. Expressions can here be the \texttt{opaque} identifier — which at assignment-time may non-deterministically assume any value —, boolean or integer values, variables, or a composition of expressions through some mathematical function or operator \(f\). For instance, we allow the expression \(+ (v, 1)\) — also written using the infix notation \(v + 1\) for clarity — to stand for the sum of the value associate to \(v\) and 1, and similarly write e.g. \(v > 10\), \(v \geq v'\), \(v + 5 = 8\) and so on.
Figure 3 describes how the concrete XML syntax of activities relates to the abstract one. In the left-hand side, we used \(\underline{x}\) to denote the XML representation describing the corresponding right-side meta-variable \(x\) — e.g. \(\underline{a.1}\)
stands for the right-side symbol $a_1$, which defines an activity.
Structured activities \texttt{sequence} and \texttt{flow} are mapped to successive application of standard binary operators \texttt{;} and \texttt{||} for sequential and parallel composition, respectively. Similarly, \texttt{pick} is mapped onto a choice operator \texttt{+}, guarded by the occurrence of a message exchange for each different choice. Activities \texttt{while}, \texttt{link}, \texttt{source}, and \texttt{assign} have a one-to-one mapping, while
switch correspond to a successive application of a single-case construct switch. The activities invoke and reply are used to send invocations or replies, and are mapped to the same construct send — their difference is meant to be recorded into the two end-points l, which have opposite direction. Conversely, activity receive is mapped onto construct recv. Finally, since an invoke specifying an input and an output message refers to a request-reply primitive, it is mapped to a sequence of a send and a recv.
The only part which needs a more accurate description should be the management of correlations, which leads to the extra-argument w in the activities related to message exchanges send and recv. As a first example consider a simple invoke with no correlations, sending a given structured message. Without loss of generality, in our abstract syntax we always see messages as made of a sequence of values, we therefore denote by v a variable holding messages, and by v_i the corresponding variable over its i-th subpart (or field). For instance, the one-way invoke activity without correlations
\[
\text{<invoke ... inputVariable=varName> </invoke>}
\]
is expressed as send(l, \(\overline{v}_{\text{varName}}, \overline{v}_{\text{varName}}\)). The first argument is the message receiver end-point, the second is the variable that will contain the received message, while the third contains information on correlations: when no correlations exist this is exactly the same as the second argument.
Now suppose the message has type msg, it is made of three parts part1, part2, and part3, it is denoted by variable \(\overline{v} = (v_1, v_2, v_3)\), and suppose that the following correlation set is specified inside the invoke activity:
\[
\text{<correlations> <correlation set=cName ...> <correlations>}
\]
By the definitions
\[
\text{<correlationSet name=cName properties="p1 p2">}
\]
\[
\text{<bpws:propAlias propName=p1 messageType=msg part=part1 ...>}
\]
\[
\text{<bpws:propAlias propName=p2 messageType=msg part=part2 ...>}
\]
we define cName as a correlation set made of the properties p1 and p2, which are linked to the first and second part of message msg. This correlation set will characterise those process instances exchanging messages with given values in the first and second part of the msg messages. The corresponding abstract syntax is now send(l, \(\overline{v}_1, v_2, v_3\), \(\overline{p}_1, p_2, v_3\)). In particular, the third argument \(p_1, p_2, v_3\) says that while the third part of the message is not related to any correlation set, for it is exactly variable \(v_3\), the first two parts are properties \(p_1\)
and \( p_2 \), and are then correlated to the process instance. So, if in the current process instance \( p_1 \) is bound to value \( u_1 \) and \( p_2 \) to \( u_2 \), then the first and second part of the message are automatically set to \( u_1 \) and \( u_2 \). Dually, in \( \text{recv}(l, \langle v_1, v_2, v_3 \rangle, \langle p_1, p_2, v_3 \rangle) \), only a message carrying \( u_1 \) and \( u_2 \) in the first and second part can be received by the process instance. This is why we generally denote a message sending as \( \text{send}(l, v, w) \) and similarly for message reception.
### 3.3 Abstract Syntax of the Shipping Service
To provide some more details on our abstract syntax, we describe the specification of the shipping service shown in Section 2.2.
Two end-points are used: \( l_n \) represents action \text{shippingNotice} invoked on the customer, and \( l_r \) is used for invocation of action \text{shippingRequest} by the customer. Symbol \( v_r \) is used for variable \text{shipRequest}, containing received request messages, which is made by the three parts \( v_r^1 \), \( v_r^2 \), and \( v_r^3 \) representing \text{orderID}, \text{complete}, and \text{itemsTotal}. Symbol \( v_n \) is used for variable \text{shipNotice}, containing the messages to send, which is made by the two parts \( v_n^1 \) and \( v_n^2 \), representing \text{orderID} and \text{itemsCount}. Then, symbol \( v^i \) is used for variable \text{itemsShipped}. Property \( p \) of the correlation set is used for the \text{orderID}. The abstract syntax of the shipping service is then quite directly obtained from the BPEL specification, as shown in Figure 4. From the first glance, the reader might enjoy its compactness over the actual specification, as well as its intuitive structure.
### 4 Semantics
#### 4.1 Extended Syntax
The syntax described in the previous section is the surface syntax that can be used to describe in an abstract way BPEL specifications. On the other
hand, to provide an operational semantics describing the actual behaviour of orchestrating Web Services, we also need this syntax to be able to represent the state of a business process at a given time. In particular, the notions of current variable assignment and of process instance have to enter the picture, since they play a fundamental role in the model we intend to define. So, as common practice in functional and concurrent programming languages [14,24], we extend the syntax to deal with run-time aspects. The production for symbol $a$ is changed as follows:
$$a ::= 0 \mid (\tau \mapsto \tau)s \mid !a \mid a \parallel P$$
In a term $(\tau \mapsto \tau)s$, notation $(\tau \mapsto \tau)$ is called a store and is used to specify that in the activity specification $s$, variable or property $w_i$ is associated to value $u_i$, for any $i$. Notation $(\tau \mapsto \tau)(\tau \mapsto u)$ is used in the following with the same meaning of $(\tau, w \mapsto \tau, u)$. Symbol $!a$ means that the activity $a$ can be spawned (replicated) and then executed infinite times, while operator $\parallel$ is for composition of process instances. In particular, while stores are used to model the current state of a process instance (both in terms of variables and correlation sets), replication is used at the top level to deal with process instances. Notice that we have two operators for parallel composition: $\parallel$ for composing different process instances, and $\parallel$ to compose different activities inside the same process instance: they are to kept distinct since stores do not propagate through $\parallel$ but not through $\parallel_P$. The computational model is then as follows: if $s$ is the activity syntactically obtained by a BPEL process specification, $!(\bullet \mapsto \bullet)s$ is the initial state of the business process, which spawns a new process instance with initially void store each time the first message of each work session is received.
### 4.2 Congruence Rules and Auxiliary Operators
As a first step towards defining operational semantics, we refine the abstract syntax by introducing the congruence rules reported in Figure 5, specifying those terms which are to be considered syntactically equivalent. These rules, giving semantic details about replication [C-SPN], parallel composition [C-PAR], flow [C-FLW], choice [C-CHO], and sequential composition [C-SEQ] are quite standardly derived from the process algebraic style (e.g. of CCS [17] and BPA [4]).
Before introducing operational semantics, we clarify the management of stores and variables. The main difference between variables and properties is tackled by introducing a partial operator $\oplus$ for modelling store update, enforcing the idea that properties are constants: into a process instance the
value of correlation sets identifies the process identity, which never changes. This operator is defined as:
\[
(\overline{w} \mapsto \overline{u}) \oplus (v \mapsto u) \triangleq (\overline{w} \mapsto \overline{u})(v \mapsto u)
\]
\[
(\overline{w} \mapsto \overline{u})(p \mapsto u) \oplus (p \mapsto u) \triangleq (\overline{w} \mapsto \overline{u})(p \mapsto u)
\]
\[
(\overline{w} \mapsto \overline{u}) \oplus (p \mapsto u) \triangleq (\overline{w} \mapsto \overline{u})(p \mapsto u) \quad \text{if} \quad p \notin \overline{w}
\]
The first definition states that variable assignment always update the store, the second and third that updating a property assignment is allowed only if an equivalent assignment already occurs in the store. We use this definition to enforce the idea that messages sent and received by a given process instance must conform to the correlation set, since e.g. notation \((p \mapsto u) \oplus (p \mapsto u')\) does not make sense when \(u \neq u'\).
For simplicity, the notation for stores is abused writing \((\overline{w} \mapsto \overline{u}) \oplus (\overline{w}' \mapsto \overline{u}')\) as a shorthand for \((\overline{w} \mapsto \overline{u}) \oplus (w_1' \mapsto u_1') \oplus (w_2' \mapsto u_2') \oplus \ldots \oplus (w_k' \mapsto u_k')\), where \(k\) is the size of \(\overline{w}'\) and \(\overline{u}'\).
Evaluation of expression \(e\) under the store \((\overline{w} \mapsto \overline{u})\) is defined by notation \(\{\overline{w}/\overline{u}\}e\), with semantics:
\[
\{\overline{w}/\overline{u}\}u \triangleq u \quad \{\overline{w}/\overline{u}\}w_i \triangleq u_i \quad \{\overline{w}/\overline{u}\}f(\overline{v}) \triangleq f(\{\overline{w}/\overline{u}\}\overline{v})
\]
\[
\{\overline{w}/\overline{u}\}opaque \triangleq u \quad v \notin \overline{w} \Rightarrow \{\overline{w}/\overline{u}\}v \triangleq u
\]
Orderly, values are evaluated to themselves, variables and properties to their associated value, functions by propagating the evaluation to their arguments, the opaque identifier or a variable not already initialised to any value \(u\) (non-deterministically). Notice that the notation for evaluation is again abused by using \(\{\overline{w}/\overline{u}\}\overline{v}\) to evaluate all expressions \(\overline{v}\), and is used similarly for evaluating either integer and boolean expressions.
4.3 Operational Semantics
As common for concurrent languages \cite{17,6,23}, operational semantics is defined here by a labelled transition system \( \langle A, \rightarrow, I \rangle \), where \( A \) is the set of activities (states of the system to model), ranged over by meta-variable \( a \), and \( I \) is the set of labels representing interactions, ranged over by meta-variable \( \alpha \) with syntax:
\[
\alpha ::= \tau \mid l!\overline{\nu} \mid l?\overline{\nu}
\]
This transition system is used to determine how the state of the business process evolves as interactions with the partners occur, writing \( a \overset{\alpha}{\rightarrow} a' \) for activity (state) \( a \) moving to \( a' \) by interaction \( \alpha \). \( \tau \) is the silent action, modelling an internal computation inside the business process; \( l!\overline{\nu} \) represents the business process sending a message to the end-point \( l \) specifying message \( \overline{\nu} \), and similarly \( l?\overline{\nu} \) represents receiving a message from end-point \( l \). The rules defining transition relation \( \rightarrow \) are shown in Figure 6.
Rule [PAR] defines the semantics of operator \( ||P \) in terms of interleaved concurrency, and allows us to focus, from here on, on the behaviour of a single
\[
\begin{array}{ll}
a ||P a' \overset{\alpha}{\rightarrow} a'' ||P a' & \text{if } a \overset{\alpha}{\rightarrow} a'' \\
(w \mapsto \overline{u})(s_0 + s_1) \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})s'_0 & \text{if } (w \mapsto \overline{u})s_0 \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})s'_0 \text{ [PCK]} \\
(w \mapsto \overline{u})(s_0 || s_1) \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})(s'_0 || s_1) & \text{if } (w \mapsto \overline{u})s_0 \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})s'_0 \text{ [FLW]} \\
(w \mapsto \overline{u})(s_0;s_1) \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})(s'_0;s_1) & \text{if } (w \mapsto \overline{u})s_0 \overset{\alpha}{\rightarrow} (w' \mapsto \overline{v})s'_0 \text{ [SEQ]} \\
(w \mapsto \overline{u})(source(\lambda);s || target(\lambda);s') \overset{\tau}{\rightarrow} (w \mapsto \overline{u})(s || s') & \text{[LNK]} \\
(w \mapsto \overline{u})while(e)\{s\} \overset{\tau}{\rightarrow} (w \mapsto \overline{u})s;while(e)\{s\} & \text{if } \{\overline{w}/\overline{u}\}e = true \text{ [WH]} \\
(w \mapsto \overline{u})while(e)\{a\} \overset{\tau}{\rightarrow} (w \mapsto \overline{u})0 & \text{if } \{\overline{w}/\overline{u}\}e = false \text{ [NWH]} \\
(w \mapsto \overline{u})switch(e)\{s : s'\} \overset{\tau}{\rightarrow} (w \mapsto \overline{u})s & \text{if } \{\overline{w}/\overline{u}\}e = true \text{ [SW]} \\
(w \mapsto \overline{u})switch(e)\{s : s'\} \overset{\tau}{\rightarrow} (w \mapsto \overline{u})s' & \text{if } \{\overline{w}/\overline{u}\}e = false \text{ [NSW]} \\
(w \mapsto \overline{u})assign(v,e) \overset{\tau}{\rightarrow} (w \mapsto \overline{u}) \oplus (v \mapsto \{\overline{w}/\overline{u}\}e)0 & \text{[ASG]} \\
(w \mapsto \overline{u})send(l,v,\overline{w}_p) \overset{l!(\overline{w}/\overline{v})}{\overrightarrow{\nu}} (w \mapsto \overline{u}) \oplus (\overline{w}_p \mapsto \{\overline{w}/\overline{u}\}v)0 & \text{[SND]} \\
(w \mapsto \overline{u})recv(l,v,\overline{w}_p) \overset{l?\overline{v}}{\overrightarrow{\overline{w}_p}} (w \mapsto \overline{u}) \oplus (\overline{v} \mapsto \overline{u}' \overline{w}_p \mapsto \overline{u}')0 & \text{[REC]}
\end{array}
\]
Fig. 6. Operational semantics
process instance of the kind \((\overline{w} \mapsto \overline{u})s\) at a time. Rules \([\text{PCK,FLW,SEQ}]\) describe the semantics of choice, flow, and sequential composition: the standard algebraic behaviour of such operators is adopted, along with the idea that each transition may affect the store of the enclosing process instance. Two different concurrent activities in the same process instance can synchronise by a source and target link \(\lambda\), as shown in rule \([\text{LNK}]\).
Given the above rules, we can now deal with the execution of the other basic activities one at a time, without the need to consider their mutual influence. The structured activity \textbf{while} is executed by evaluating the boolean condition \(e\) in the current store: if this is true \(([\text{WH}])\) the action \(s\) is executed first and then the \textbf{while} activity is executed again, otherwise \(([\text{NWH}])\) no other local activity has to be executed — but e.g. the sequential continuation can carry on by rule \([\text{SEQ}]\). The behaviour of the \textbf{switch} structure is similar, the first case is evaluated, and if its condition is satisfied \(([\text{SW}])\) the corresponding activity \(s\) is executed, otherwise the subsequent case is considered \(([\text{NSW}])\). Assigning an expression \(e\) to a variable \(v\) simply means to update the store by the new assignment of \(v\) to the value \(u\) which \(e\) is evaluated to \(([\text{ASG}])\).
Action \textbf{send} causes a message to be sent outside, whose content is the evaluation \(\{\overline{w}/\overline{u}\}\overline{v}\) of variable \(\overline{v}\) in the current store. As a result, the update \((\overline{w}_p \mapsto \{\overline{w}/\overline{u}\}\overline{v})\) is applied, which both checks for the conformance of the message with respect to the properties of existing correlation sets and adds new properties in the store, modelling the initialisation of new correlation sets \(([\text{SND}])\). Viceversa, by action \textbf{recv} a new message is received, so that its content \(u'\) is assigned to variable \(v\) by update \((\overline{v} \mapsto u')\). Moreover, the new update \((\overline{w}_p \mapsto u')\) is also applied, which controls whether the received values conforms to the existing properties where necessary, and adds the properties of new correlation sets. In particular, notice that an incoming message is necessarily associated to the proper process instance, according to the fact that it is allowed only within the process instance providing compatible correlation sets.
### 4.4 The Behaviour of the Shipping Service
To better understand the main underpinnings of our operational semantics, we show the evolution of the shipping service which results from the interaction with some customers. For brevity, we denote by \(s_T\) the specification shown in
Figure 4, by $s_{sw}$ and $s_{wh}$ the switch and while activities inside it, that is:
$$s_T ::= recv(l_r, \overline{v}, \langle p, v^\prime_r, v^\prime_i \rangle); s_{sw}$$
$$s_{sw} ::= switch(v^\prime_r)\{ assign(v_n^\prime, send(l_n, \overline{v^\prime}, \langle p, v^\prime_i \rangle)) : assign(v^\prime, 0); s_{wh} \}$$
$$s_{wh} ::= while(v^\prime < v^\prime_i)\{ assign(v^\prime_n, opaque); send(l_n, \overline{v^\prime}, \langle p, v^\prime_n \rangle); assign(v^\prime, v^\prime + v^\prime_n) \}$$
As a case we consider the following evolution:
- The initial state of the business process is $a_0 = !(\bullet \rightarrow \bullet)s_T$, that is, any copy of the specification $s_T$ is ready to be spawned whose initial store is void.
- At a given time, a customer sends a shipping request of the kind $\langle 101, true, 5 \rangle$, asking for the atomic shipment of 5 items, specifying the ID 101:
$$a_0 \xrightarrow{l_r?'\langle 101, true, 5 \rangle} a_0 || p, a_1,$$
$$a_1 = (\overline{v} \mapsto \langle 101, true, 5 \rangle)(p \mapsto 101)s_{sw}$$
This is obtained first by spawning a new process instance by congruence rule [C-SPN], which receives the request by operational rule [REC] (executed in the context of rule [SEQ]). The effect of this execution is that the store will contain the variable $v_r$ for the received message, while the correlation set property $p$ defining the identity of the process instance is bound to 101.
- Concurrently, a new customer sends the request $\langle 180, false, 3 \rangle$, asking for the possibly non-atomic shipment of 3 items, using ID 180; a new process instance is therefore created similarly to the previous case:
$$a_0 \parallel p, a_1 \xrightarrow{l_r?'\langle 180, false, 3 \rangle} a_0 \parallel p, a_1 \parallel p, a_2,$$
$$a_2 = (\overline{v} \mapsto \langle 180, false, 3 \rangle)(p \mapsto 180)s_{sw}$$
Notice that two process instances are now currently active, each with own state of the store, characterised by different orderID.
- The executions of $a_1$ and $a_2$ are isolated. Without losing generality, as we are in the context of interleaved concurrency, we can suppose that the execution of the first process instance $a_1$ carries on until completion, that is (i) evaluating the switch condition, (ii) assigning the variable and then
(iii) performing the invocation:
\[
\begin{align*}
a_1 & \xrightarrow{\tau} \\
(\mathcal{F} \leftarrow (101, true, 5))(p \mapsto 101)& \text{ assign}(v_2^n, v_2^n) \text{; send}(l_n, \overline{F}^n, (p, v_2^n)) \xrightarrow{\tau} \\
(\mathcal{F} \leftarrow (101, true, 5))(p \mapsto 101)(v_2^n \mapsto 5) & \text{; send}(l_n, \overline{F}^n, (p, v_2^n)) \xrightarrow{t_nl(101,5)} 0
\end{align*}
\]
In the last interaction, notice that the first message part 101 is obtained by evaluating variable \( v_1^n \) which is not initialised: however, from all the possibilities 101 is chosen because is the only matching the current value of correlation set property \( p \) (rule [SND]).
- Similarly, we report the evolution of the second process instance, which deals with a non-atomic shipment of 3 items. We first suppose that the business process ships 1 item:
\[
\begin{align*}
a_0 & \parallel_P a_2 \xrightarrow{\tau} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180) \text{ assign}(v^i, 0); s_{wh} \xrightarrow{\tau} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180)(v^i \mapsto 0)s_{wh} \xrightarrow{\tau} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180)(v^i \mapsto 0) \text{ assign}(v_2^n, opaque); \text{ send}(l_n, \overline{F}^n, (p, v_2^n)); \text{ assign}(v^i, v^i + v_2^n); s_{wh} \xrightarrow{\tau} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180)(v^i \mapsto 0)(v_2^n \mapsto 1) \text{ send}(l_n, \overline{F}^n, (p, v_2^n)); \text{ assign}(v^i, v^i + v_2^n); s_{wh} \xrightarrow{l_nl(180,1)} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180)(v^i \mapsto 0)(v_2^n \mapsto 1) \text{ assign}(v^i, v^i + v_2^n); s_{wh} \xrightarrow{\tau} \\
a_0 & \parallel_P (\mathcal{F} \leftarrow (180, false, 3))(p \mapsto 180)(v^i \mapsto 1)(v_2^n \mapsto 1)s_{wh}
\end{align*}
\]
Notice that after this evolution the interaction state is moved back to the initial state \( s_{wh} \), even though the store is changed reflecting e.g. the shipment of 1 item. If at the next step the business process ships 2 items the
process instance terminates, through the evolution:
\[
a_0 \parallel_P (v^r \mapsto \langle 180, \text{false}, 3 \rangle)(p \mapsto 180)(v^i \mapsto 1)(v^n_2 \mapsto 1)s_{wh} \xrightarrow{\tau} \\
\]
\[
a_0 \parallel_P (v^r \mapsto \langle 180, \text{false}, 3 \rangle)(p \mapsto 180)(v^i \mapsto 1)(v^n_2 \mapsto 1)
assign(v^n_2, \text{opaque}); send(l_n, v^n_2); assign(v^i, v^i + v^n_2); s_{wh} \xrightarrow{\tau} \\
\]
\[
a_0 \parallel_P (v^r \mapsto \langle 180, \text{false}, 3 \rangle)(p \mapsto 180)(v^i \mapsto 1)(v^n_2 \mapsto 2)
send(l_c, v^n_2); assign(v^i, v^i + v^n_2); s_{wh} \xrightarrow{l_n!(180, 2)} \\
\]
\[
a_0 \parallel_P (v^r \mapsto \langle 180, \text{false}, 3 \rangle)(p \mapsto 180)(v^i \mapsto 1)(v^n_2 \mapsto 2)
assign(v^i, v^i + v^n_2); s_{wh} \xrightarrow{\tau} \\
\]
\[
a_0 \parallel_P (v^r \mapsto \langle 180, \text{false}, 3 \rangle)(p \mapsto 180)(v^i \mapsto 3)(v^n_2 \mapsto 2)s_{wh} \xrightarrow{\tau} a_0
\]
5 Conclusion and Future Works
In this paper we applied typical techniques for formalising syntax and semantics of imperative and concurrent programming languages to define a core language for BPEL4WS orchestration language. To the best of our knowledge, in spite BPEL exploits very well known process algebraic constructs, this is the first attempt to provide a comprehensive model taking into account all these heterogeneous features, and precisely modelling a significant portion of BPEL.
Nevertheless, we believe our work could pave the way for further investigations. First of all, an observational semantics could be introduced to enable formal verification of properties. Then, following the methodological approach for orchestration languages proposed in [16], a type system could be introduced for our core language, allowing to statically check for the correct exploitation of variables and properties, and for analysing the composition of a business process with the collaborating Web Services. Also, it would be interesting to further enlarge the modelled portion of BPEL until a substantial completion. Other than issues such as timing and faults, a challenging and interesting feature is compensation handling, which has recently being investigated [7,5], and it is likely to be formalised by a smooth extension to the model presented here. Finally, as an operational semantic approach is proved feasible here, we are also interested in deepening the relationship between BPEL specification and implementations, for instance evaluating the exploitation of some coordination infrastructure such as TuCSoN [22] as a platform for orchestration engines.
References
[14] Igarashi, A., B. C. Pierce and P. Wadler, Featherweight Java: A minimal core calculus for Java and GJ, ACM Transactions on Programming Languages and Systems 23 (2001), pp. 396–450.
|
{"Source-Url": "https://core.ac.uk/download/pdf/82827850.pdf", "len_cl100k_base": 11259, "olmocr-version": "0.1.49", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 67442, "total-output-tokens": 13766, "length": "2e13", "weborganizer": {"__label__adult": 0.0003268718719482422, "__label__art_design": 0.0003662109375, "__label__crime_law": 0.00030875205993652344, "__label__education_jobs": 0.0005497932434082031, "__label__entertainment": 7.110834121704102e-05, "__label__fashion_beauty": 0.0001329183578491211, "__label__finance_business": 0.00035762786865234375, "__label__food_dining": 0.00032639503479003906, "__label__games": 0.0003638267517089844, "__label__hardware": 0.0005960464477539062, "__label__health": 0.0004725456237792969, "__label__history": 0.0002188682556152344, "__label__home_hobbies": 6.705522537231445e-05, "__label__industrial": 0.0003731250762939453, "__label__literature": 0.00029969215393066406, "__label__politics": 0.0002701282501220703, "__label__religion": 0.00034999847412109375, "__label__science_tech": 0.0250244140625, "__label__social_life": 7.939338684082031e-05, "__label__software": 0.007411956787109375, "__label__software_dev": 0.9609375, "__label__sports_fitness": 0.00020802021026611328, "__label__transportation": 0.0005006790161132812, "__label__travel": 0.00018918514251708984}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49116, 0.02403]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49116, 0.33665]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49116, 0.85698]], "google_gemma-3-12b-it_contains_pii": [[0, 1564, false], [1564, 4413, null], [4413, 7417, null], [7417, 9997, null], [9997, 12760, null], [12760, 15568, null], [15568, 16186, null], [16186, 19014, null], [19014, 21431, null], [21431, 21962, null], [21962, 24619, null], [24619, 26608, null], [26608, 29420, null], [29420, 31785, null], [31785, 35335, null], [35335, 38211, null], [38211, 40536, null], [40536, 42732, null], [42732, 45351, null], [45351, 48393, null], [48393, 49116, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1564, true], [1564, 4413, null], [4413, 7417, null], [7417, 9997, null], [9997, 12760, null], [12760, 15568, null], [15568, 16186, null], [16186, 19014, null], [19014, 21431, null], [21431, 21962, null], [21962, 24619, null], [24619, 26608, null], [26608, 29420, null], [29420, 31785, null], [31785, 35335, null], [35335, 38211, null], [38211, 40536, null], [40536, 42732, null], [42732, 45351, null], [45351, 48393, null], [48393, 49116, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49116, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49116, null]], "pdf_page_numbers": [[0, 1564, 1], [1564, 4413, 2], [4413, 7417, 3], [7417, 9997, 4], [9997, 12760, 5], [12760, 15568, 6], [15568, 16186, 7], [16186, 19014, 8], [19014, 21431, 9], [21431, 21962, 10], [21962, 24619, 11], [24619, 26608, 12], [26608, 29420, 13], [29420, 31785, 14], [31785, 35335, 15], [35335, 38211, 16], [38211, 40536, 17], [40536, 42732, 18], [42732, 45351, 19], [45351, 48393, 20], [48393, 49116, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49116, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
83bf5886be67c7df7e377ee7baae7db0ef671d44
|
ABSTRACT
Static bug finders have been widely-adopted by developers to find bugs in real-world software projects. They leverage predefined heuristic static analysis rules to scan source code or binary code of a software project, and report violations to these rules as warnings to be verified. However, the advantages of static bug finders are overshadowed by such issues as uncovered obvious bugs, false positives, etc. To improve these tools, many techniques have been proposed to filter out false positives reported or design new static analysis rules. Nevertheless, the under-performance of bug finders can also be caused by the incorrectness of current rules contained in the static bug finders, which is not explored yet. In this work, we propose a differential testing approach to detect bugs in the rules of four widely-used static bug finders, i.e., SonarQube, PMD, SpotBugs, and ErrorProne, and conduct a qualitative study about the bugs found. To retrieve paired rules across static bug finders for differential testing, we design a heuristic-based rule mapping method which combines the similarity in rules’ description and the overlap in warning information reported by the tools. The experiment on 2,728 open source projects reveals 46 bugs in the static bug finders, among which 24 are fixed or confirmed and the left are awaiting confirmation. We also summarize 13 bug patterns in the static analysis rules based on their context and root causes, which can serve as the checklist for designing and implementing other rules and/or in other tools. This study indicates that the commonly-used static bug finders are not as reliable as they might have been envisaged. It not only demonstrates the effectiveness of our approach, but also highlights the need to continue improving the reliability of the static bug finders.
1 INTRODUCTION
The increasing complexity of modern software systems has complicated both the development of new software features and the maintenance of source code. Techniques that can detect and reduce bugs are very beneficial to help developers improve software quality. To achieve this goal, static bug finders that analyze code characteristics without program execution such as SonarQube [9] and Findbugs [20], have been widely used to find bugs in software [4, 7, 47, 50]. These tools mainly leverage predefined heuristic analysis rules to scan source code or binary code of a software project, and report violations to these rules as warnings to be verified. Most of static bug finders can infer a wide variety of bugs, security vulnerabilities, and bad programming practices [14, 50, 57].
Previous studies have shown that static bug finders can help in detecting software defects faster and cheaper than human inspection or software testing [5, 24]. They have been widespread adopted by professional software developers, and regularly integrated in contemporary open source projects and commercial software organizations [26, 43, 62]. For example, Errorprone and Infer has been automatically applied to code changes to support manual code review at Google and Facebook, respectively [3]. However, the advantages of static bug finders are overshadowed by such issues as uncovered obvious bugs [16, 55], false positives [24, 30], etc. To improve these tools and enhance their usability, different lines of studies have been proposed.
Several researchers proposed to utilize prioritization strategies to make it easier for developers to spot the more actionable warnings [18, 19, 27, 32, 57]. Other researchers employed feedback-based rule design for mitigating false positives [42, 48], e.g., Errorprone used unactionable warnings labeled by developers [48], and FeeFin refined the rules by the development practice of open source projects [42]. Another line of studies focused on designing project-specific rules that mined from specific projects to improve the detection accuracy [8, 10, 17, 23, 31, 34], e.g., PR-Miner [31] and NAR-Miner [8] mined programming rules and detected violations with frequent itemset mining algorithms. All above mentioned practices focused on improving current static bug finders by adjusting the warning results based on existing static analysis rules or designing new rules. However, the under-performance of bug finders can also be caused by the incorrectness of current rules contained in these static bug finders, which is not explored yet.
In this work, to assess the correctness of static analysis rules of static bug finders, we propose a differential testing approach...
to detect bugs in the rules of four widely-used static bug finders, i.e., SonarQube, PMD, SpotBugs, and ErrorProne, and conduct a qualitative study about the bugs found in these tools.
The assumption of our approach is that static analysis rules from different bug finders that target at the same type of bugs should have consistent bug detection results (i.e., warnings) on the same inputted software projects. Specifically, our work starts from retrieving paired rules that target at the same type of bugs among different static bug finders. We then run the static bug finders on a large set of experimental projects and check whether there are inconsistencies between the reported warnings of these paired rules. To retrieve paired rules across static bug finders for differential testing, we design a heuristic-based rule mapping method, which combines the similarity in rules’ description and the overlap in warning information reported by the tools.
To evaluate our approach, for the four examined bug finders, we treat SonarQube and PMD as a pair (which scan source code of software projects to detect bugs), while SpotBugs and ErrorProne as a another pair (which scan binary code of software projects to detect bugs). Our heuristic-based rule mapping method retrieves 74 pairs of rules for SonarQube and PMD, while 30 pairs of rules are retrieved for SpotBugs and ErrorProne. We use 2,728 open source projects from an existing publicly available dataset as the experimental subjects for detecting the inconsistencies in the warnings. Results show that 7,633 inconsistencies between the paired rules from different static bug finders have been revealed.
We then apply descriptive coding, a qualitative analysis method, on the detected inconsistencies to identify the buggy rules in the static bug finders and categorize these bugs to derive bug patterns. 46 bugs in the static analysis rules across the four static bug finders are found, among which 8 are bugs in the implementations of rules that cause them to generate false positives, 38 are bugs that cause them to miss detect true bugs (i.e., false negatives). We further summarize 13 bug patterns in the static analysis rules based on the bugs’ context and root causes. For example, bug pattern fail in multiple calling operations which describes the static analysis rules would fail to warn the suspicious code when involving the multiple calling operations as json.exception().printStackTrace() (work for single calling operation as exp.printStackTrace()). These bug patterns can serve as the checklists for developers when designing and implementing other static analysis rules and/or in other static bug finders. We also localize these bugs and summarize three types of typical faults in the implementation of these static bug finders.
To evaluate the usefulness of this study, we report these found bugs to the development team, and 24 is fixed or confirmed and the left are awaiting confirmation. This study indicates that the commonly-used static bug finders are not as reliable as they might have been envisaged. It highlights the need to continue improving the reliability of the static bug finders, and suggests the feasibility of utilizing differential testing on these static bug finders.
This paper makes the following contributions:
- Our study finds 46 bugs about the implementation or design of static analysis rules, among which 24 are fixed/confirmed1.
- We propose a heuristic-based static analysis rule mapping method to retrieve paired rules that target at the same types of bugs across different static bug finders.
- We summarize 13 bug patterns in the static analysis rules based on their context and root causes, which can serve as the checklist for designing and implementing other rules.
2 METHODOLOGY
2.1 Examined Static Bug Finders
In this study, we explore the correctness of static analysis rules for four popular open source static bug finders as listed below.
1) SonarQube is one of the most widely adopted static bug finders that leverages pre-defined static analysis rules to help find bugs in the context of continuous integration. It supports more than 20 programming languages and has been adopted by more than 85,000 organizations or software projects. SonarQube provides developers with its own analysis rules and also incorporates rules from other popular bug finders, e.g., CheckStyle, PMD, and FindBugs. In this study, we only experiment with SonarQube’s own rules, i.e., 545 Java related rules in its rule repository2.
2) PMD is a source code analyzer maintained by open community. It finds common programming flaws like unused variables, empty catch blocks, and unnecessary object creation, etc. It supports Java, JavaScript, PLSQL, Apache Velocity, XML, etc. We include all its 304 Java related rules for experiment3.
3) SpotBugs is the spiritual successor of the pioneering FindBugs tool [21], carrying on from the point where it left off with support of its community. It is a bug finder which uses static analysis to look for bugs in Java code. It was originally developed by the University of Maryland, and has been downloaded more than a million times. We use all the 449 Java related rules for experiment4.
4) ErrorProne is a static bug finder for Java that catches common programming mistakes at compile-time. It is developed by Google and is integrated into their static analysis ecosystem [47]. We experiment with all its 333 Java related rules5.
The first two static bug finders work on the source code of software projects, while the last two tools require the compiled binary code of software projects. Since this difference might lead to the variations in the marked line of the suspicious code, we group the first two tools (i.e., SonarQube and PMD) as a pair and the last two tools (SpotBugs and ErrorProne) as the second pair to conduct the differential testing. Note that, this study focuses on the static bug detection of Java projects with Java related static analysis rules, which is one of the most commonly-used programming languages.
2.2 Experimental Projects
In order to fully explore the static analysis rules, we need a large set of projects whose source code is available and compilable (for collecting binary code). We also expect these projects having flaws
---
1Details are listed in https://github.com/wuchiuwong/Diff-Testing-01.
2https://rules.sonarsource.com/java
3https://pmd.github.io/latest/pmd_rules_java.html
5https://errorprone.info/bugpatterns
to cover as many static analysis rules as possible, so that the static bug finders can be triggered and the inconsistencies in their warning results can be potentially revealed.
To satisfy all above requirements, we choose to use the 50K-C projects repository [37], which contains 50,000 Java projects crawled from GitHub. Each project is attached with the dependencies required to compile it, and the scripts with which the projects can be compiled. All of them are active open source projects, so that there should be dozens of flaws which can trigger the static analysis rules.
We randomly download 3,000 projects from the repository, then employ their provided building framework SourceRerJBF to compile the source code[37]. 272 projects could not be successfully compiled because of such errors as incompatible character set. We use the remaining 2,728 projects with 1,565 KLOC (Kilometer Lines Of Code) in total, for the following experiment. Figure 1 presents the details of these projects with number of files in each project, average lines of source code per file in each project, and number of dependent jars for compiling the project. Note that, the maximum value of the first two series of data are respectively 1,877 and 3,370, and we cut off the figures to facilitate visualization. There are an average of 32 files in an experimental project, and each file has an average of 115 lines of source code.
### 2.3 Differential Testing of Static Analysis Rules
The primary idea of this study is to detect bugs in static bug finders through differential testing, i.e., by providing the same input to different implementations of the same functionality and observing the inconsistencies between the implementations. To achieve this goal, we treat each rule implemented in the static bug finder as a functionality of the bug finder, and treat the paired rules from different bug finders which target at detecting the same types of bugs as different implementations of the same functionality.
As demonstrated in Figure 2, this study first retrieves the paired rules between two static bug finders (Section 2.3.1), i.e., two rules target at the same types of bugs, then detects the inconsistencies between the bug finders when respectively running the paired rules with the same inputted software projects (Section 2.3.2). Based on the inconsistencies, it identifies the buggy rules in the static bug finders and categorizes them (Section 2.3.3), meanwhile it also localizes the found bugs in the static bug finders (Section 2.3.4).
#### 2.3.1 Retrieving Paired Rules
As showed in Section 2.1, each examined static bug finder has hundreds of rules, and there would be tens of thousands candidate pairs, e.g., 165,680 (545 × 304) pairs for matching each rule of Sonarqube to each rule of PMD. Manually mapping such large number of rules from different bug finders could be time- and effort-consuming. Besides, rules from different tools are described differently, e.g., rule `throwable.printStackTrace should not be called` in Sonarqube is described with 80 words with two code examples, while its paired rule `AvoidPrintStackTrace` in PMD has only 7 terms with one code example, which further increases the difficulty of rule mapping.
To cope with the above circumstance, we propose a heuristic-based rule mapping method which combines the similarity in rules’ description and the overlap in warning information reported by the tools. In detail, we first choose the potential rule pairs with the similarity of rules based on their textual descriptions and accompanied code examples. For each candidate rule pair, we then check the detailed warning information reported by the rules and filter out the less possible rule pairs, in which two rules with larger degree of overlap have higher possibility to be a pair. This is conducted with four mapping-rules which will be described below.
1) Choosing Potential Rule Pairs Based on Description Similarity
Generally speaking, each static analysis rule in these static bug finders is described with three fields: title, detailed description, and code examples, in which title and description demonstrate what types of bugs the rule targets at and how the analysis works, while code examples present the positive and negative examples to show when the rule is triggered. We concatenate the title and detailed description fields, and treat it as the textual content of the rule. To model the similarity between the descriptions of two rules from different aspects, we use three types of similarity metrics, i.e., term similarity to measure the text similarity of the rule’s textual content, semantic similarity to measure the semantic similarity of the rule’s textual content, and code similarity to measure the similarity of code examples. Details are as follows.
**Term similarity (Termsim).** The term similarity is measured with the Term Frequency and Inverse Document Frequency (TF-IDF). It is one of the most popular features for representing textual documents in information retrieval. The main idea of TF-IDF is that if a term appears many times in one rule and a few times in the other rules, the term has a good capability to differentiate the rules, and thus the term has high TF-IDF value. Specifically, given a term \( t \) and a rule \( r \), \( TF(t, r) \) is the number of times that term \( t \) occurs in rule \( r \), while \( IDF(t) \) is obtained by dividing the total number of rules by the number of rules containing term \( t \). TF-IDF is computed as: \( TF - IDF(t, r) = TF(t, r) \times IDF(t) \).
With the above formula, the textual content of a rule \( r \) can be represented as a TF-IDF vector, i.e., \( r = (w_1, w_2, ..., w_n) \), where \( w_i \) denotes the TF-IDF value of the \( i \)th term in rule \( r \). Then term similarity is calculated as the cosine similarity between the vectors of two rules.
**Semantic similarity (Semtsim).** The above mentioned TF-IDF similarity focuses on the similarity of rules considering the term matching. We also employ word embedding feature, which concerns more on the relationship of terms considering the context...
they appear, to better model the semantic similarity of two rules. Word embedding is a popular feature learning technique in natural language processing where individual words are no longer treated as unique symbols, but represented as a d-dimensional vector of real numbers that capture their contextual semantic meanings [6, 40].
We use the publicly available software\textsuperscript{6} to obtain the word embedding of a rule. With the trained word embedding model, each word can be transformed into a d-dimensional vector where d is set to 100 as suggested in previous studies [56, 58, 60]. Meanwhile, a rule can be transformed into a matrix in which each row represents a term in the rule. We then transform the rule matrix into a vector by averaging all the word vectors the rule contains as previous work did [56, 58, 60]. Specifically, given a rule matrix that has n rows in total, we denote the ith row of the matrix as \( r_i \) and the transformed rule vector \( v_d \) is generated as follows:
\[
v_d = \frac{\sum_i r_i}{n} \tag{1}
\]
With the above formula, each rule can be represented as a word embedding vector, and semantic similarity is calculated as the cosine similarity between the vectors of two rules.
For training the word embedding model, we collect 100,000 java related questions and answers from StackOverflow. We then combine these text with the rule description of the four examined tools, and utilize them for model training. The reason why we use these data is that previous studies have revealed that to train an effective word embedding model, a domain-specific dataset with large size is preferred. The size of our training dataset is 101 Megabytes.
Code similarity (\textit{Code}\textsubscript{sim}). The code examples of each rule contain the name of class and method targeted by the rule, which are indispensable sources of information for determining whether two rules share the same functionality. We first extract the class name and method name of each rule, separate them into terms with camel-back notation following existing study [1]. We then compare the two set of terms of \( rule_a \) and \( rule_b \) to derive the code similarity with the following equation.
\[
\text{Code}_{sim} = \frac{\text{terms in } rule_a \cap \text{terms in } rule_b}{\text{terms in } rule_a \cup \text{terms in } rule_b} \tag{2}
\]
The final description similarity between two rules is calculated as follows.
\[
\text{Description}_{sim} = (\text{Term}_{sim} + \text{Sem}_{sim}) \times \frac{\text{Code}_{sim} + 1}{2} \tag{3}
\]
We simply add the term similarity and semantic similarity together because existing researches suggested both of them are important [56, 60]. The code similarity, which is smoothed considering it might be 0, can be seen as a filter by which if two rules share large portion of class and method names, they are more likely to be paired, otherwise they are less likely to be paired even they are similar in textual content.
Based on the description similarity, we design \textit{mapping-rule a} to choose the potential static analysis rule pairs.
- \textit{(Mapping-rule a) Retriving pairs of mutual top-N similarity.} If \( rule_b \) is within \( rule_a \)'s top-N most similar rules and vice versa, we treat \( rule_a \) and \( rule_b \) as a candidate pair for further investigation, where \( rule_a \) and \( rule_b \) are respectively from a pair of static bug finders.
2) Filtering Out Less Possible Rule Pairs Based on Warning Information
We then run each static bug finder on the experimental projects collected in Section 2.2. For each reported warning, we record the triggered static analysis rule, the warned line(s) of code, the method and file where the warning occurs.
Based on the reported warning information, we then design \textit{mapping-rules (b,c,d)} to jointly filter out the less possible rule pairs from the potential rule pairs generated with \textit{mapping-rule (a)}. These three mapping-rules are designed considering the following two assumptions: 1) the paired rules should have large degree of overlap in their warnings; 2) considering one of the paired rules might have bugs, we allow their reported warnings can be partially overlapped.
- \textit{(Mapping-rule b) Pruning with one-to-one pair.} If the percentage of overlaps of the warned lines reported by \( rule_a \) and \( rule_b \) exceeds 80% of warned lines from each of the rules, we assume the candidate pair has extremely high possibility being the paired rules. Note that, to simplify our approach, we focus on one-to-one mapping among two sets of rules from different bug finders, thus we remove other candidate pairs related with \( rule_a \) and \( rule_b \). Another note is that, we choose the pair with the largest overlap ratio when multiple rule pairs satisfy the threshold.
- \textit{(Mapping-rule c) Pruning with difference in warning trigger times.} If the difference of warning trigger times for \( rule_a \) and \( rule_b \) exceeds 20 times, we assume these two rules can hardly related with the same functionality and remove the candidate pair.
- \textit{(Mapping-rule d) Pruning with difference in warning file.} If the overlap of warned files by \( rule_a \) and \( rule_b \) is lower than 2%, we assume these two rules can hardly related with the same functionality and remove the candidate pair.
We find a large portion of rules from SpotBugs and ErrorProne do not have code examples and exert a lower similarity; thus for this tool pair, we set N as 5 in \textit{mapping-rule a}, while set it as 3 for another tool pair (i.e., SonarQube and PMD). Other parameters
\[\text{https://code.google.com/archive/p/word2vec/}\]
in the mapping rules is determined empirically, which aims at automatically retrieving a reasonable number of candidate pairs for manual inspection. We will mention in the threats to validity that there do exist one-to-many mappings, however for facilitating the proposed differential testing, we only focus on one-to-one mapping between rules from different tools.
3) Retrieving Final Rule Pairs Manually
For all the remaining candidate paired rules after the above four mapping rules, we conduct a manual check to finally determine the paired rules. In detail, the first three authors independently check the candidate pairs, and determine whether the two rules have the same functionality based on the rules’ description and code examples. The results of their independent mapping have a Cohens kappa of 0.87, which is a substantial level of agreement [38]. They then discuss the disagreement online until the final consensus is reached.
2.3.2 Detecting Inconsistencies. Based on the retrieved paired rules, we check the inconsistencies in the warnings generated by the paired rules when running the static bug finders, i.e., whether the warnings reported by paired rules mark the same place in the source code. Since different rules would highlight the warnings at different granularities, e.g., a specific line of code or the whole method, we employ different criteria for the inconsistency detection for different paired rules.
Criterion 1, when both of the paired rules warn a specific line of code, we check whether the warned file and warned line coincide with each other between the paired rules, and treat the case in which the warned lines are different as the inconsistency.
Criterion 2, when one or two of the paired rules warn(s) the whole method, e.g., rule ReturnEmptyArrayRatherThanNull of PMD marks the entire method while its paired rule (Empty arrays and collections should be returned instead of null) in SonarQube only marks the return line (as the example shown below), we check whether the warned methods coincide with each other between the paired rules, and treat the case in which the warned methods are different as the inconsistency.
```
private float [] getReactionFlyShip (Ship ship) { // warn by PMD
float box[] = new float [8];
box[0] = ship.getAngle() / (2f * 3.14159f);
return null; // warn by SonarQube
}
```
2.3.3 Identifying and Categorizing Bugs. We apply a qualitative analysis method called descriptive coding [49][45] on the detected inconsistencies to identify the buggy rules in the static bug finders and categorize these bugs to derive bug patterns. Figure 3 demonstrates an example of how we analyze the inconsistencies and summarize bug patterns.
The detected inconsistencies are delivered to the first three authors respectively, and each of them manually checks them and identifies the bugs. Specifically, they first determine which of the paired rules is buggy, and whether the inconsistency involves a false negative bug (i.e., suspicious code is not warned) or a false positive bug (i.e., normal code is wrongly warned). We also find some inconsistencies are caused by the the imperfectness in the rule definition (see Section 3.2.2), therefore the authors also check the description of these static analysis rules to determine whether the bug is caused by the inaccurate implementation, or mainly because of the imperfectness in rule definition, to provide a more comprehensive view of these buggy rules. The authors then examine the context and root causes of the bug, and summarize bug patterns of these buggy rules, as shown in Table 4. The disagreement of the above analysis is discussed until common consensus is reached.
The categorization of the bug patterns might subject to the author’s personal judgement. We mitigate this limitation by recruiting two independent workers who are not authors of the paper. These two workers, with more than five years background in software development, independently evaluate if the derived bug pattern is meaningful and correct. We provide them with the bug pattern name, the involved buggy rule, random-chosen one consistent warning and two inconsistent warnings for each buggy rule. The two workers independently determined if each of the buggy rule belongs to the bug pattern, and whether the bug pattern is meaningful. Both workers agree with the categorization and most of the bug patterns.
3 EXPERIMENTAL RESULTS
3.1 Results of Rule Mapping
We first present the results of how many rules of each bug finder are triggered and the warning trigger times after running the bug finders on our experimental projects, with results in Table 1. We can see that 74% to 89% rules are triggered for SonarQube, PMD and SpotBugs, while for ErrorProne, 45% of its rules are triggered. We analyze the un-triggered rules of ErrorProne and find that most of them are related to the framework or package developed by Google itself, e.g., AutoValue, Dagger, etc., which are seldom used by general software projects, thus were not triggered. On average, 73% rules are triggered and each rule is triggered a median of 163 times, which suggests the generalizability of our experiments.
Following the rule mapping method described in Section 2.3.1, we retrieve the paired rules and list the results in Table 2, in which we present the number of remaining rule pairs after applying mapping rule (a-d). 74 rule pairs from SonarQube and PMD, and 30 rule pairs from SpotBugs and ErrorProne are finally determined as having identical functionality\textsuperscript{7}. The hitting rate of our mapping method is 51.5% (74/145 in Table 2) for paired tools SonarQube and PMD, 45.4% (30/66 in Table 2) for paired tools SpotBugs and ErrorProne. This indicates we can find one mapped rule pairs by examining
\textsuperscript{7}These paired rules are listed in https://github.com/wuchiuwong/Diff-Testing-01.
an estimate of two candidate pairs, which is quite cost-effective considering the tremendous number of total candidate pairs. It is almost impossible to measure the recall of our retrieved rule pairs, considering the large number of candidate pairs. We construct a small-scale ground truth set to roughly evaluate the recall. In detail, we choose the rule pairs which 1) the overlap of warned files by two rules is 100%; and 2) the warning trigger times are larger than 10 to reduce the noise. Based on the filtered rule pairs, we conduct the manual check as previous section and obtain the paired rules. Since these rule pairs are determined solely based on the warning information, they can be treated as orthogonal with the rule pairs retrieved by the proposed mapping method which are firstly determined with description similarity. Based on the constructed ground truth rule pairs, 56% (42/74) rule pairs for SonarQube and PMD are recalled, and 73% (22/30) rule pairs for SpotBugs and ErrorProne are recalled. This further indicates the effectiveness of our proposed mapping method which can help find sufficient number of rule pairs with little human effort.
### 3.2 Detected Bugs in Static Bug Finders
Overall, 7,633 inconsistencies (i.e., sum of occurrence times in Table 4, 5 and 6) are revealed from the two pairs of static bug finders on our experimental projects.
Following the qualitative analysis method presented in Section 2.3.3, we examine these inconsistencies and identify 46 bugs in the rules of the four static bug finders, i.e., 10 in SonarQube, 25 in PMD, 6 in SpotBugs, and 5 in ErrorProne, as shown in Table 3. Among the bugs, 38 are false negative bugs (i.e., the suspicious code is not warned by the tool), while 8 are false positive bugs (i.e., the clean code is warned by the tool). In addition, for false negative bugs, 29 bugs are caused by rule implementation, while 9 bugs are caused by rule definition; for false positive bugs, all of them are because of the rule implementation. We discuss the three types of bugs in the following three subsections respectively.
#### 3.2.1 False Negative Bugs (about Rule Implementation)
For the 29 false negative bugs about rule implementation, seven bug patterns are summarized following the procedure described in Section 2.3.3. Table 4 demonstrates a summarized view of these bug patterns, with the illustrative example, the involved static analysis rules and the occurrence times of the bug (i.e., the number of inconsistencies for triggering the bug). There are 3 remaining bugs, each of which belongs to a specific type, thus we put them in Others category, and leave them for future exploration. We then present the detailed analysis of an example pattern to facilitate understanding.
**P2) Fail in compound expression.** The involved rules in this pattern cannot work with compound expressions (i.e., two or more operands in an expression). For example, rule *QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT* from Spotbugs checks a literal boolean value (true or false) assigned to a boolean variable inside an if or while expression. Most probably this was supposed to be a boolean comparison using ==, not an assignment using =. Code example (a) shows the consistent case where both SpotBugs and ErrorProne can detect the suspicious code with the paired rules, while code example (b) shows the inconsistent case where only ErrorProne marks the suspicious code, i.e., the corresponding rule in SpotBugs has a bug. The compound expression in code example (b) triggers the bug of this rule in SpotBugs.
(Code example a.) Warning reported by both SpotBugs and ErrorProne.
```java
// birker−tism−master/src/tism/EdgeFsm.java
public void setDirected (boolean directed ) {
if ( directed = false ) throw new IllegalArgumentException("Fsm are always directed !"); // warn by SpotBugs and ErrorProne
}
```
(Code example b.) Warning reported by ErrorProne only.
```java
// lunchza−VisualHDD−VisualHDD−master/VisualHDD/src/visual/gui/ProgramWindow.java
public void setScanStatus (boolean b) {
if (scanning = b == false && canceled == true ) { // warn only by ErrorProne
scanning = false;
}
}
```
Table 2: Results of rule mapping
<table>
<thead>
<tr>
<th>Tool</th>
<th>Total pairs</th>
<th>candidate pairs</th>
<th>Pairs after applying rule a</th>
<th>Pairs after applying rule b</th>
<th>Pairs after applying rule c</th>
<th>Pairs after applying rule d</th>
<th>Final pairs</th>
</tr>
</thead>
<tbody>
<tr>
<td>SonarQube & PMD</td>
<td>165,680</td>
<td>145</td>
<td>367</td>
<td>145</td>
<td>74</td>
<td>25</td>
<td>424</td>
</tr>
<tr>
<td>ErrorProne & SpotBugs</td>
<td>149,517</td>
<td>6</td>
<td>387</td>
<td>264</td>
<td>66</td>
<td>30</td>
<td>367</td>
</tr>
</tbody>
</table>
Table 3: Detected bugs on four static bug finders
<table>
<thead>
<tr>
<th>Tool</th>
<th>False negative (about rule implementation)</th>
<th>False negative (about rule definition)</th>
<th>False Positive</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td>SonarQube</td>
<td>6</td>
<td>3</td>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>PMD</td>
<td>15</td>
<td>4</td>
<td>5</td>
<td>25</td>
</tr>
<tr>
<td>SpotBugs</td>
<td>4</td>
<td>1</td>
<td>4</td>
<td>6</td>
</tr>
<tr>
<td>ErrorProne</td>
<td>4</td>
<td>1</td>
<td>0</td>
<td>5</td>
</tr>
<tr>
<td>Overall</td>
<td>29</td>
<td>9</td>
<td>8</td>
<td>46</td>
</tr>
</tbody>
</table>
Table 4: False negative bugs (about rule implementation) in the examined static bug finders
<table>
<thead>
<tr>
<th>Bug pattern (# involved rules)</th>
<th>Description</th>
<th>Example</th>
<th>Involved rules (number of inconsistencies) / C indicates fixed/confirmed bug</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>P1. Fail in special data type (5)</strong></td>
<td>Rules fail to warn the suspicious code involving special data types</td>
<td>Rule Object should not be created only to getClass fails with Array, while works with ArrayList;</td>
<td>PMD: SingularField (82) SonarQube: String function use should be optimized for single characters (8) / C SonarQube: Objects should not be created only to getClass (5) / C PMD: RedundantFieldInitializer (3) / C SpotBugs: ICAST_BAD_SHIFT_AMOUNT (3)</td>
</tr>
<tr>
<td><strong>P2. Fail in compound expression (5)</strong></td>
<td>Rules fail to warn the suspicious code involving compound expression</td>
<td>Rule QBA_QUESTIONABLE _BOOLEAN _ASSIGNMENT fails when compound expression is involved, e.g., if (scanning > b == false);</td>
<td>ErrorProne: ToStringReturnsNull (28) SpotBugs: QBA_QUESTIONABLE _BOOLEAN _ASSIGNMENT (26) SpotBugs: SA_LOCAL_SELF_ASSIGNMENT (26) SonarQube: Variables should not be self-assigned (5) SonarQube: Fields should not be initialized to default values (3) / C</td>
</tr>
<tr>
<td><strong>P3. Fail in implicit operation (4)</strong></td>
<td>Rules fail to warn the suspicious code involving the implicit operation of the defined suspicious operation</td>
<td>Rule IntLongMath (Expression of type int may overflow before assigning to a long) fails when involving comparison operation (i.e., implicit assignment operation), e.g., if (score >= level * level * 1000);</td>
<td>ErrorProne: IntLongMath (135) / C SonarQube: Static fields should not be updated in constructors (7) / C SpotBugs: DMI_INVOKING_TOSTRING_ON_ARRAY (53) ErrorProne: ArrayEquals (11)</td>
</tr>
<tr>
<td><strong>P4. Fail in multiple calling operations (4)</strong></td>
<td>Rules fail to warn the suspicious code involving multiple calling operations</td>
<td>Rule AvoidPrintStackTrace fails when involving multiple calling operations, e.g., json.exception().printStackTrace();</td>
<td>PMD: CollectionIsEmpty (189) / C PMD: AvoidPrintStackTrace (20) / C PMD: ClassCastExceptionWithToArray (5) PMD: DontCallThreadRun (5) / C</td>
</tr>
<tr>
<td><strong>P5. Fail in separated expressions (3)</strong></td>
<td>Rules fail to warn the suspicious code involved in separated expressions</td>
<td>Rule UseProperty classLoader fails when involving separated expressions, e.g., Foo foo = new Foo(); classLoader classLoader = foo.getClassLoader();</td>
<td>PMD: UseProperty classLoader (68) / C ErrorProne: ToStringReturnsNull (28) / C PMD: InstantiationToGetClass (19)</td>
</tr>
<tr>
<td><strong>P6. Fail in unnecessary brackets (3)</strong></td>
<td>Rules fail to warn the suspicious code involving unnecessary brackets which changes AST of the code</td>
<td>Rule SimplifyConditional fails with if(rhs != null & & (rhs instanceof CodeLocation)), yet works when deleting the unnecessary brackets on 2nd condition;</td>
<td>PMD: ReturnEmptyArrayRatherThanNull (770) PMD: SimplifyConditional (109) SonarQube: Switch statements should not contain non-case labels (39) / C</td>
</tr>
<tr>
<td><strong>P7. Fail in variables (2)</strong></td>
<td>Rules fail to warn the suspicious code involving variables, while works with constant</td>
<td>Rule FinalFieldCouldBeStatic fails when assigning to an expression, e.g., private final double HPI = Math.PI = 3.14, yet works when assigning to a constant, e.g., protected final int margin = 3;</td>
<td>PMD: FinalFieldCouldBeStatic (209) PMD: AvoidDecimalLiterallnBigDecimalConstructor (20) / C</td>
</tr>
<tr>
<td>Others (3)</td>
<td>Others</td>
<td>N/A</td>
<td>PMD: AvoidThrowingNullPointerException (772) PMD: SimplifyBooleanExpressions (623) / C PMD: StringToString (215) / C</td>
</tr>
</tbody>
</table>
3.2.2 False Negative Bugs (about Rule Definition). For the 9 false negative bugs about rule definition, three bug patterns (as shown in Table 5) are summarized following the procedure described in Section 2.3.3. The bugs in the above subsection are caused by the inaccurate implementation of rules, while the bugs in this subsection are mainly because of the imperfection in rule definition. For example, we find the definition of some rules miss specific data types. We separate them to remind the tool developers about the
flaw in the design of these static analysis rules. We then present the detailed analysis of an example pattern to facilitate understanding.
**P8) Miss comparable method.** The rules in this pattern miss certain comparable method. Take the rule UseLocaleWithCaseConversions from PMD as an example. We present its rule description, as well as the description of its paired rule Locale should be used in String operations of SonarQube as follows.
- **PMD (UseLocaleWithCaseConversions):** When doing String::toLowerCase() or String::toUpperCase(), use an explicit locale argument to specify the case transformation rules.
- **SonarQube:** Locale should be used in String operations.
We can see that in the rule definition of PMD, only two string related methods are mentioned, while the third method format() is included in the rule definition of SonarQube. The results from the inconsistent detection by running these two static bug finders on experimental projects confirm that String::format() cannot be warned by PMD, which suggest the design of the rule UseLocaleWithCaseConversions from PMD is incomplete and could be buggy.
### 3.2.3 False Positive Bugs
For the 8 false positive bugs, three bug patterns (as shown in Table 6) are summarized following the procedure described in Section 2.3.3. We then present the detailed analysis of an example pattern to facilitate understanding.
**P11) Poor handling of method with same name.** Bugs related with the rules in this pattern occur because they warn the correct method which shares the same method name (yet different method signatures) with the defined suspicious method. Take the rule Thread::notify() from PMD as an example. This rule states its usually safer to call notifyAll() rather than notify() because the later one awakens an arbitrary thread monitoring the object when more than one thread is monitoring. The following code examples first present the consistent case where both PMD and SonarQube can detect the suspicious code in example (a), followed by the inconsistent case where PMD wrongly highlights the normal code in example (b), i.e., bug in PMD. We can see that although the method name is notify, it is not Object::notify() as defined in the rule, since these two methods have different method signatures. PMD does not filter this special yet misleading case, which suggests a potential bug in the rule of PMD.
(Case example a.) Warning reported by both SonarQube and PMD.
```java
public void memberFinished(Address addr) {
synchronized (members) {
members.remove(addr);
if (members.isEmpty()) {
members.notify(); // warn by both PMD and SonarQube
}
}
}
```
(Case example b.) Warning reported by PMD only.
```java
private void injectSimple(Object bean, InjectionContext context) {
... else if ((toSet && !child.definition.isEmpty()) {
getInjector().notify(getCanonicalName() + " + child definition + "
has been converted as null", null); // warn only by PMD
}
}
```
### 3.3 Typical Faults in Static Bug Finders Causing Buggy Rules
Besides detecting the bugs in static analysis rules of the bug finders, we further examine the source code of these static bug finders and localize the faults for these buggy rules listed in Tables 4, 5 and 6. Based on our analysis of the bug localization results, we summarize the following three types of typical faults.
**1) Inflexible design of rule implementation**
We notice that the implementation of 60% (15/25) detected buggy rules in PMD involves the XPath technology [2], which searches for specific expression on the Abstract Syntax Tree (AST) of the analyzed program. This implementation is less flexible and very sensitive to noisy data.
Take the rule SimplifyConditional from PMD as an example, we have presented the analysis in Section 3.2.1.6 where we show this rule fails when AST changes by adding the unnecessary brackets. When implementing this rule, as shown below, it would search the conditional statement (i.e., ConditionalAndExpression) and check whether it is the EqualityExpression (i.e., rhs != null) and InstanceOfExpression (i.e., rhs instanceof CodeLocation) respectively. When the
### Table 5: False negative bugs (about rule definition) in the examined static bug finders.
<table>
<thead>
<tr>
<th>Bug pattern (≠ involved rules)</th>
<th>Description</th>
<th>Example</th>
<th>Involved rules (number of inconsistencies) / C indicates fixed/confirmed bug</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>P8) Miss comparable method (4)</strong></td>
<td>Rules miss comparable method of the defined suspicious method</td>
<td>Rule UseLocaleWithCaseConversions fails with String::format(), while works with String::toLowerCase()/toUpperCase();</td>
<td>PMD: UseLocaleWithCaseConversions (464), ErrorProne: BoxedPrimitiveEquality (14) SonarQube: Java.lang.Error should not be extended (7) / C SonarQube: Execution of the Garbage Collector should be triggered only by the JVM (7) / C</td>
</tr>
<tr>
<td><strong>P9) Miss comparable data type or operation (3)</strong></td>
<td>Rules miss the comparable data type or operation of the defined suspicious ones</td>
<td>Rule ICAST_INTEGER_MULTIPLY_CAST_TO_LONG fails with shift operation, while works with multiply operation;</td>
<td>SonarQube: Redundant modifiers should not be used (1271) / C PMD: AvoidArrayLoops (362) / C SpotBugs: ICAST_INTEGER_MULTIPLY_CAST_TO_LONG (39)</td>
</tr>
<tr>
<td><strong>P10) Miss subclass or superclass (2)</strong></td>
<td>Rules miss the subclass or superclass of the defined suspicious class</td>
<td>Rule AvoidCatchingThrowable fails in the subclass of Throwable, e.g., catch (Error e);</td>
<td>PMD: ReturnEmptyArrayRatherThanNull (677) PMD: AvoidCatchingThrowable (41)</td>
</tr>
</tbody>
</table>
two expressions are no longer in parallel after adding the brackets, the rule would fail to work.
```java
protected List<MethodMatcher> getMethodInvocationMatchers(){
return Collections.singletonList(MethodMatcher.create().typeDefinition(
TypeCriteriasubtypeOf("java.lang.Object").name("getClass")
).withoutParameter());
}
```
### 2) Uncovering potential influenced statements
The four static bug finders employ similar strategies to implement the rules. In detail, given a specific rule, these bug finders first categorize all the statements in the code under analysis according to their functionalities, e.g., variable definition, variable assignment, conditional judgment, etc. Then they further visit the pre-defined potential problematic statements, and analyze them to determine whether there is a match, i.e., a warning is given.
Take the rule `IntLongMath` from ErrorProne (mentioned in Section 3.2.1.P3) as an example, the rule first locates the problematic statements, i.e., return, initialization, assignment (i.e., `matchAssignment` as shown in the code below). It then determines whether the result is `Long` type, and filter out the operations which can not result in overflow. However, when locating the problematic statements, it does not consider the `compare statement` which can also trigger the bug.
```java
@Override
public Description matchAssignment(AssignmentTree tree, VisitorState state) {
return check(ASTHelpers.getType(tree), tree.getExpression());
}
```
### 3) Missing considering special cases
Many faults are caused because of their neglecting in special cases. For the rule `Objects should not be created only to getClass` of SonarQube, it fails in the `Array` type as mentioned in Section 3.2.1.P1. The implementation code shown below demonstrates that this rule is designed for `java.lang.Object`, which does not include `Array`. More special cases should be included to ensure the robustness of these rules.
```java
[ConditionalOrExpression
EqualityExpression [EqualityOfOperator = "=="]
!NullLiteral and
InstanceOfExpression [PrimaryExpression = PrimaryExpression]
count (PrimarySuffix)
@ArrayDereference = "true"
] = 0
// Name[not(contains(@Image, ".")]
// @Image = ancestor::
// ConditionalAndExpression[EqualityExpression/PrimaryExpression/
// PrimaryPrefix/Name[@Image] and (count(InstanceOfExpression) + 1 =
// count(-1))
]]]>'
```
<table>
<thead>
<tr>
<th>Bug pattern (# involved rules)</th>
<th>Description</th>
<th>Example</th>
<th>Involved rules (number of inconsistencies) / C indicates fixed/confirmed bug</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>P11. Poor handling of method with same name (3)</strong></td>
<td>Rules wrongly warn the clean method which has the same name yet different method signatures with the defined suspicious method</td>
<td>UseNotifyAtLast Instead of Notify should warn Object.notify(), but wrongly warns notify(pattern) method in other class, e.g., <code>getEventThread().notify(output);</code></td>
<td>PMD: SuspectEqualMethodName (12) / C SonarQube: Object.finalize() should remain protected when overriding (6) / C</td>
</tr>
<tr>
<td><strong>P12. Setting over-sized scope (3)</strong></td>
<td>Rules wrongly warn the clean code which is beyond the scope of the defined suspicious case</td>
<td>AvoidThrowingNullPointerException wrongly warns the expression with <code>NullPointerException</code> yet without <code>Throwing</code> e.g., <code>Exception e = new NullPointerException("msg");</code></td>
<td>PMD: AvoidThrowingNullPointerException (18) / C SpotBugs: SF_SWITCH_NO_DEFAULT (11) PMD: AvoidCallingFinalize (6) / C</td>
</tr>
<tr>
<td><strong>P13. Neglecting corner case (2)</strong></td>
<td>Rules wrongly warn the clean code which is the corner case of the defined suspicious case</td>
<td>Missing_break_in_Switch wrongly warns the switch expression without break in the last case statement.</td>
<td>PMD: MissingBreakInSwitch (841) / C PMD: AvoidReassigningLoopVariables (188)</td>
</tr>
</tbody>
</table>
### 3.4 Usefulness Evaluation
To further demonstrate the usefulness of this study, for each detected bug, we create a bug report by describing the issue, the example code, and the analyzed reason, then report it to the development team through an issue report. Among the 46 detected bugs, 24 have been fixed or confirmed by the developers, and the left are awaiting confirmation. The fixed/confirmed bugs are marked in Table 4 to Table 6, and all the reported issues are listed on our website.\(^8\) The fixed and confirmed bugs further demonstrate the usefulness of this study in helping the developers improving these widely-used bug finders.
### 4 DISCUSSIONS AND THREATS TO VALIDITY
#### 4.1 Discussions
Checklist for static analysis rule design and implementation. Table 4, 5, and 6 summarizes the bug patterns in the implementation and design of static analysis rules. We also notice that most of these bug patterns involve rules target at different types of warnings and from different bug finders, which implies the generalizability of these bug patterns.
The bug patterns are actually the special cases which is ignored by the static analysis rules and cause them fail to warn the corresponding suspicious code or wrongly warn the clean code. We believe these bug patterns can serve as the checklist when one designs or implements new rules and/or in other static bug finders. Take bug pattern P2. *Fail in compound expression* as an example, we find some static analysis rules fail to warn the suspicious code involving compound expression. Equipped with such a bug pattern, one should pay careful attention to this special case when designing/implementing a new rule, and include related test cases to cover this special case, both of which can help improve the quality of newly implemented static analysis rules.
\(^8\)https://github.com/wuchiuwong/Diff-Testing-01
Customizing static bug finders to avoid execution of duplicate rules (i.e., paired rules). Many software organizations tend to configure multiple bug finders for detecting bugs with an assumption that different bug finders emphasize on detecting different types of bugs in the source code [35, 47]. For example, Github projects as Springfox9 and Roboguice10 employ both SpotBugs and PMD for code inspection [62]. Another example is SonarQube which incorporates static analysis rules from other bug finders, i.e., SpotBugs, PMD, cobertura, and CheckStyle (note that, we exclude these external rules in our experiment).
Our rule mapping results reveal a non-negligible portion of duplicate rules among the examined static bug finders, e.g., at least 24% (74/304) rules from PMD are the duplicates of the rules in SonarQube. However, most of the bug finders are used in default configuration [55], which results in the duplicate rules repeatedly running and brings in heavy overhead. A more feasible alternative would be customizing these bug finders to make the duplicate rules only execute once, and the mapped rule pairs retrieved in this study further provide the feasibility for the customization. The differential testing results of this study also provide the detailed guidelines to do so, e.g., choose the correct rule if one of them is buggy.
Multiple bug patterns of one rule or two paired rules. We notice that one static analysis rule (or two rules in a pair) can involve multiple bug patterns, i.e., having different types of bugs. For example, the rule AvoidThrowingNullPointerException of PMD is listed in both false negative bugs about rule implementation and false positive bugs. In the former case, the rule can not warn the suspicious code which throws the exception in method definition (see Table 4), while in the latter case, the rule wrongly warns the normal code with NullPointerException yet without throw operation (see details in Section 3.2.3.P12).
The second example is for the paired rules, i.e., IntLongMath of ErrorProne and ICAST_INTEGER_MULTIPLY_CAST_TO_LONG of SpotBugs. The former fails with the assignment operation (see details in Section 3.2.1.P3), and is listed in false negative bugs about pattern implementation. The latter only considers the multiply operation in the rule definition, while misses other related operation as shift (see details in Section 3.2.2.P9). These diversified cases increase the difficulty of testing these static analysis rules and further indicates the value of this study.
4.2 Threats to Validity
The first threat of this study is the selection of static bug finders, which may or may not be representative for a larger population. We experiment with four popular open source static bug finders, which are widely used in previous researches and industrial practice [4, 7, 57, 62], which we believe to be representative for the current state-of-the-art. Despite of this, there are other commonly-used static bug finders, e.g., Infer, CheckStyle, Coverity. The reason why do not utilize Infer or CheckStype is because they either have few static analysis rules (e.g., 25 rules in Infer) or focus more on the coding standards (i.e., CheckStyle), both of which limit us in finding plenty of mapping rules and detecting more inconsistencies. Besides, Coverity is a closed sourced bug finder with which we could not conduct the bug localization.
Another threat to validity is our methodology for mapping static analysis rules which could, in principle, miss some paired rules. To overcome the challenges that tens of thousands of candidate pairs needed to be examined, we design a heuristic-based rule mapping method. This could miss some true paired rules, yet make this mapping task can be done with reasonable human effort. We employ several empirical parameters in filtering the candidate rule pairs which might also influence the recall of paired rules. Nevertheless, based on the retrieved mapping rules, we have detected 46 bugs in the tools. Besides, we present the hitting rate and recall of rule mapping in Section 3.1 to show the reliability of the method.
In addition, this study does not include the one-to-many mapping rule combinations, since its potential candidate number is far too large, and there would be correspondingly more confusing cases. Future work will adopt other mechanisms as multi-input learning, to help automatically retrieve such kinds of rule combinations, so as to conduct differential testing and detect bugs on more rules.
5 RELATED WORK
The use of static bug finders for software defect detection is a common practice for developers during software development and has been studied by many researchers [14, 24, 41, 46, 63]. There were studies investigating the adoption of static bug finders within continuous integration pipelines [43, 54, 62]. Other studies focused on how these warnings are actually acted, and fixed [22, 36, 52]. Several researchers proposed to utilize prioritization strategies to make it easier for the developers to spot the more actionable warnings [18, 19, 27, 32, 57]. There were several researches employing feedback-based rule design for mitigating false positives [42, 48]. Another line of researches focused on designing project-specific rules that mined from specific projects to improve the detection accuracy [8, 10, 17, 23, 31, 34]. All above mentioned researches focused on improving current static bug finders by adjusting the warning results or designing new rules, while this study investigate the correctness of bug finders which can improve the detection accuracy fundamentally.
Differential testing is originally introduced by McKeeman which attempts to detect bugs by checking inconsistent behaviors across different comparable software or different software versions [39]. Randomized differential testing is a widely-used black-box differential testing technique in which the inputs are randomly generated [11, 15, 29, 33, 44, 51, 53, 59, 61]. Inconsistency detection has been used in other domains such as cross-platform [13], web browsers [12], document readers [28], and program variables [25]. Different from the above mentioned application scenarios, we apply differential testing to detect bugs in widely-used static bug finders which can improve the performance of bug detection.
6 CONCLUSION
Static bug finders are widely used by professional software developers, and regularly integrated in contemporary open source projects and commercial software organizations. They have been shown to be helpful in detecting software defects faster and cheaper than human inspection or software testing. To further improve the
reliability of static bug finders, this paper proposes a differential testing approach to detect bugs in the static analysis rules of four widely-used static bug finders. Our study finds 46 bugs about the widely-used static bug finders. Our study finds 46 bugs about the
|
{"Source-Url": "http://arxiv-export-lb.library.cornell.edu/pdf/2109.02245", "len_cl100k_base": 12720, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 42480, "total-output-tokens": 15660, "length": "2e13", "weborganizer": {"__label__adult": 0.00034689903259277344, "__label__art_design": 0.00024580955505371094, "__label__crime_law": 0.0003273487091064453, "__label__education_jobs": 0.0004565715789794922, "__label__entertainment": 4.303455352783203e-05, "__label__fashion_beauty": 0.00013566017150878906, "__label__finance_business": 0.00011658668518066406, "__label__food_dining": 0.00022983551025390625, "__label__games": 0.0005731582641601562, "__label__hardware": 0.0005326271057128906, "__label__health": 0.0002448558807373047, "__label__history": 0.00012886524200439453, "__label__home_hobbies": 5.710124969482422e-05, "__label__industrial": 0.00018978118896484375, "__label__literature": 0.00017261505126953125, "__label__politics": 0.0001952648162841797, "__label__religion": 0.00031065940856933594, "__label__science_tech": 0.0023651123046875, "__label__social_life": 6.324052810668945e-05, "__label__software": 0.004558563232421875, "__label__software_dev": 0.98828125, "__label__sports_fitness": 0.0002315044403076172, "__label__transportation": 0.0002818107604980469, "__label__travel": 0.00015234947204589844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 65141, 0.02434]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 65141, 0.4121]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 65141, 0.8759]], "google_gemma-3-12b-it_contains_pii": [[0, 4555, false], [4555, 11130, null], [11130, 17281, null], [17281, 22986, null], [22986, 28887, null], [28887, 33069, null], [33069, 39087, null], [39087, 44768, null], [44768, 50552, null], [50552, 57232, null], [57232, 65141, null], [65141, 65141, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4555, true], [4555, 11130, null], [11130, 17281, null], [17281, 22986, null], [22986, 28887, null], [28887, 33069, null], [33069, 39087, null], [39087, 44768, null], [44768, 50552, null], [50552, 57232, null], [57232, 65141, null], [65141, 65141, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 65141, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 65141, null]], "pdf_page_numbers": [[0, 4555, 1], [4555, 11130, 2], [11130, 17281, 3], [17281, 22986, 4], [22986, 28887, 5], [28887, 33069, 6], [33069, 39087, 7], [39087, 44768, 8], [44768, 50552, 9], [50552, 57232, 10], [57232, 65141, 11], [65141, 65141, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 65141, 0.11314]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
6deec091d7b6e63872bcb6b32df1f129c235ff65
|
The RIGHT Model for Continuous Experimentation
Fagerholm, Fabian
2017-01
http://hdl.handle.net/10138/175085
https://doi.org/10.1016/j.jss.2016.03.034
Downloaded from Helda, University of Helsinki institutional repository.
This is an electronic reprint of the original article.
This reprint may differ from the original in pagination and typographic detail.
Please cite the original version.
The RIGHT model for Continuous Experimentation
Fabian Fagerholm\textsuperscript{a,}*, Alejandro Sanchez Guinea\textsuperscript{b}, Hanna Mäenpää\textsuperscript{a}, Jürgen Münch\textsuperscript{a,c}
\textsuperscript{a}Department of Computer Science, University of Helsinki, P.O. Box 68, FI-00014 University of Helsinki, Finland
\textsuperscript{b}University of Luxembourg, 4 rue Alphonse Weicker, L-2721, Luxembourg
\textsuperscript{c}Faculty of Informatics, Reutlingen University, Alteburgstraße 150, D-72762 Reutlingen, Germany
Abstract
Context: Development of software-intensive products and services increasingly occurs by continuously deploying product or service increments, such as new features and enhancements, to customers. Product and service developers must continuously find out what customers want by direct customer feedback and usage behaviour observation.
Objective: This paper examines the preconditions for setting up an experimentation system for continuous customer experiments. It describes the RIGHT model for Continuous Experimentation (Rapid Iterative value creation Gained through High-frequency Testing), illustrating the building blocks required for such a system. Method: An initial model for continuous experimentation is analytically derived from prior work. The model is matched against empirical case study findings from two startup companies and further developed. Results: Building blocks for a continuous experimentation system and infrastructure are presented. Conclusions: A suitable experimentation system requires at least the ability to release minimum viable products or features with suitable instrumentation, design and manage experiment plans, link experiment results with a product roadmap, and manage a flexible business strategy. The main challenges are proper, rapid design of experiments, advanced instrumentation of software to collect, analyse, and store relevant data, and the integration of experiment results in both the product development cycle and the software development process.
*Corresponding author
Email addresses: fabian.fagerholm@helsinki.fi (Fabian Fagerholm), alejandro.sanchezguinea@uni.lu (Alejandro Sanchez Guinea), hanna.maanpaa@cs.helsinki.fi (Hanna Mäenpää), juergen.muench@cs.helsinki.fi, juergen.muench@reutlingen-university.de (Jürgen Münch)
1. Introduction
The accelerating digitalisation in most industry sectors means that an increasing number of companies are or will soon be providers of software-intensive products and services. Simultaneously, new companies already enter the marketplace as software companies. Software enables increased flexibility in the types of services that can be delivered, even after an initial product has been delivered to customers. Many constraints that previously existed, particularly in terms of the behaviour of a product or service, can now be removed.
With this newfound flexibility, the challenge for companies is no longer primarily how to identify and solve technical problems, but rather how to solve problems which are relevant for customers and thereby deliver value. Finding solutions to this problem has often been haphazard and based on guesswork, but many successful companies have approached this issue in a systematic way. Recently, a family of generic approaches has been proposed. For example, the Lean Startup methodology [26] proposes a three-step cycle: build, measure, learn.
However, a detailed framework for conducting systematic, experiment-based software development has not been elaborated. Such a framework has implications for the technical product infrastructure, the software development process, the requirements regarding skills that software developers need to design, execute, analyse, and interpret experiments, and the organisational capabilities needed to operate and manage a company based on experimentation in research and development.
Methods and approaches for continuous experimentation with software product and service value should itself be based on empirical research. In this paper, we present the most important building blocks of a framework for continuous experimentation. Specifically, our research question is:
RQ How can Continuous Experimentation with software-intensive products and services be organised in a systematic way?
To further scope the question, we split it into two sub-questions:
RQ1 What is a suitable process model for Continuous Experimentation with software-intensive products and services?
RQ2 What is a suitable infrastructure architecture for Continuous Experimentation with software-intensive products and services?
We give an answer to the research questions by validating an analytically derived model against a series of case studies in which we implemented different parts of the model in cooperation with two startup companies. The result is the RIGHT model for Continuous Experimentation (Rapid Iterative value creation Gained through High-frequency Testing). This model focuses on developing the right software, whereas the typical focus of software engineering in the past has been on developing the software right (e.g. in terms of technical quality). The model is instantiated in the RIGHT process model and the RIGHT infrastructure architecture model. Together, these instantiations address the need to integrate the requirements, design, implementation, testing, deployment, and maintenance phases of software development in a way that uses continuous empirical feedback from users.
The rest of this paper is organised as follows. In Section 2, we review related work on integrating experimentation into the software development process. In Section 3, we describe the research approach and context of the study. In Section 4, we first present our proposed model for continuous experimentation, and then relate the findings of our case study to it in order to illustrate its possible application and show the empirical observations that it was grounded in. In Section 5, we discuss the model and consider some possible variations. Finally, we conclude the paper and present an outlook on future work in Section 6.
2. Related work
Delivering software that has value – utility for its users – can be considered a primary objective for software development projects. In this section, we describe models for systematic value delivery and approaches for using experiments as a means for value testing and creation. In addition, we discuss related work with respect to experiments at scale.
2.1. Models for systematic value delivery
Lean manufacturing and the Toyota Production System [22] has inspired the definition of Lean software development. This approach provides comprehensive guidance for the combination of design, development, and validation built as a single feedback loop focused on discovery and delivery of value [25]. The main ideas of this approach, which have been emphasised since its introduction, are summarised in seven principles: optimize the whole, eliminate waste, build quality in, learn constantly, deliver fast, engage everyone, and keep getting better [24].
Lean Startup [26] provides mechanisms to ensure that product or service development effectively addresses what customers want. The methodology is based on the Build-Measure-Learn loop that establishes learning about customers and their needs as the unit of progress. It proposes to apply scientific method and thinking to startup businesses in the form of learning experiments. As the results of experiments are analysed, the company has to decide to “persevere” on the same path or “pivot” in a different direction while considering what has been learned from customers.
Customer Development [4] emphasises the importance of not only doing product development activities but also to learn and discover who a company’s initial customers will be, and what markets they are in. Customer Development argues that a separate and distinct process is needed for those activities. Customer Development is a four-step model divided into a search and an execution phase. In the search phase, a company performs customer discovery, testing whether the business model is correct (product/market fit), and customer validation, which develops a replicable sales model. In the execution phase, customer creation focuses on creating and driving demand, and
company building is the transition from an organisation designed to learn and discover to one that is optimised for cost-efficient delivery of validated products or services.
In light of the benefits that a methodology such as Lean Startup can provide, where controlled experiments constitute the main activity driving development, Holmström Olsson et al. [12] propose a target stage for any company that wishes to build a development system with the ability to continuously learn from real-time customer usage of software. They describe the stages that a company has to traverse in order to achieve that target as the “stairway to heaven”. The target stage is achieved when the software organisation functions as an R&D experiment system. The stages on the way to achieving the target are: (i) traditional development, (ii) agile R&D organisation, (iii) continuous integration, and (iv) continuous deployment. The authors first describe these four stages and then analyse them through a multiple-case study that examines the barriers that exist on each step on the path towards continuous deployment. The target stage is only described; the authors do not detail any means to overcome the barriers. A main finding from the case study is that the transition towards Agile development requires shifting to small development teams and focusing on features rather than on components. Also, it is relevant to notice that the transition towards continuous integration requires an automated build and test system (continuous integration), a main version control branch to which code is continuously delivered, and modularised development. Holmström Olsson et al. found that in order to move from continuous integration to continuous deployment, organisational units such as product management must be fully involved, and close work with a very active lead customer is needed when exploring the product concept further. The authors suggest two key actions to make the transition from continuous deployment to an R&D experiment system. First, the product must be instrumented so that field data can be collected in actual use. Second, organisational capabilities must be developed in order to effectively use the collected data for testing new ideas with customers.
Other works have studied some of the stages of the “stairway to heaven” individually. Ståhl & Bosch [27] have studied the continuous integration stage, pointing out that there is no homogeneous practice of continuous integration in the industry. They propose a descriptive model that allows studying and evaluating the different ways in which
continuous integration can be viewed. Eklund & Bosch [7] present an architecture that supports continuous experimentation in embedded systems. They explore the goals of an experiment system, develop experiment scenarios, and construct an architecture that supports the goals and scenarios. The architecture combines an experiment repository, data storage, and software to be deployed on embedded devices via over-the-air data communication channels. The architecture also considers the special requirements for safety in, e.g., automotive applications. However, the main type of experiment is confined to A/B testing, and the architecture is considered mainly from the perspective of a software development team rather than a larger product development organisation.
Holmström Olsson & Bosch [13] describe the Hypothesis Experiment Data-Driven Development (HYPEX) model. The goal of this model is to shorten the feedback loop to customers. It consists of a loop where potential features are generated into a feature backlog, features are selected and a corresponding expected behaviour is defined. The expected behaviour is used to implement and deploy a minimum viable feature (MVF). Observed and expected behaviour is compared using a gap analysis, and if a sufficiently small gap is identified, the feature is finalised. On the other hand, if a significant gap is found, hypotheses are developed to explain it, and alternative MVFs are developed and deployed, after which the gap analysis is repeated. The feature may also be abandoned if the expected benefit is not achieved.
2.2. **Systematic value creation through experimentation**
The models outlined above all aim to make experimentation systematic in the software development organisation. One important conceptual concern is the definition of experimentation. Experimentation has been established in software engineering since the 1980s. Basili et al. [3] were among the first to codify a framework and process for experimentation. Juristo et al. [14] and Wohlin et al. [31] present more recent syntheses regarding experimentation in software engineering. Taken together, these works show that “experimentation” in software engineering can be considered in a broad sense, including both controlled experiments but also more explorative activities which aim at understanding and discovery rather than hypothesis testing. For the purposes of this article, we consider experimentation to be a range of activities that can be placed
within a spectrum including controlled experiments as well as open-ended exploration. However, we emphasise that regardless of the placement within this spectrum, all methods require rigorous study designs and have a defensible and transparent way of reasoning and drawing conclusions from empirical data. They are not the same method being applied more or less carefully. The logic of controlled experiments relies on careful manipulation of variables, observation of effects, and analysis to test for causal relationships. Quasi-controlled experiments relax some of the requirements for randomised treatment. Case studies often include qualitative elements and their logic is different from controlled experiments: they generalise analytically rather than statistically [32]. Qualitative methods may also be used alone, such as through interview- or observation-based studies.
Experimentation may also be considered in terms of goals, and goals may exist on different levels of the product development organisation. On the product level, experimentation may be used to select features from a set of proposed features. On the technical level, experimentation may be used to optimise existing features. However, the model presented in this paper links experimentation on the product and technical level to the product vision and strategy on the business level. Experimentation becomes a systemic activity that drives the entire organisation. This allows for focused testing of business hypotheses and assumptions, which can be turned into faster decision-making and reaction to customer needs. Depending on the specific method used, the results of an experiment may suggest new information which should be incorporated into the decision-making process.
2.3. Considerations for running experiments at a large scale
Previous works have presented case studies that exhibit different aspects concerning continuous experimentation. Steiber [28] report on a study of the continuous experimentation model followed by Google, analysing a success story of this approach. Tang et al. [29] describe an overlapping experiment infrastructure, developed at Google, that allows web queries in a search engine to be part of multiple experiments, thus allowing more experiments to be carried out at a faster rate. Adams [1] present a case study
on the implementation of Adobe’s Pipeline, a process that is based on the continuous experimentation approach.
Kohavi et al. [16, 17] note that running experiments at large scale requires addressing multiple challenges in three areas: cultural/organisational, engineering, and trustworthiness. The larger organisation needs to learn the reasons for running controlled experiments and the trade-offs between controlled experiments and other methods of evaluating ideas. Even negative experiments should be run, which degrade user experience in the short term, because of their learning value and long-term benefits. When the technical infrastructure supports hundreds of concurrent experiments, each with millions of users, classical testing and debugging techniques no longer apply because there are millions of live variants of the system in production. Instead of heavy up-front testing, Kohavi et al. report having used alerts and post-deployment fixing. The system has also identified many negative features that were avoided despite being advocated by key stakeholders, saving large amounts of money.
Experimentation also has an important relationship with company culture. Kohavi et al. [15] describe a platform for experimentation built and used at Microsoft, noting the cultural challenges involved in using experiment results, rather than opinions from persons in senior positions, as the basis of decisions. They suggest, for example, that one should avoid trying to build features through extensive planning without early testing of ideas, that experiments should be carried out often, that a failed experiment is a learning opportunity rather than a mistake, and that radical and controversial ideas should be tried. All these suggestions are challenging to put into practice in organisations that are not used to experimentation-based decision-making. Kohavi et al. note the challenges they faced at Microsoft, and describe efforts to raise awareness of the experimentation approach.
The final stage of the “stairway to heaven” model is detailed and analysed by Bosch [5]. The differences between traditional development and the continuous approach are analysed, showing that in the context of the new, continuous software development model, R&D is best described as an “innovation experiment system” approach where the development organisation constantly develops new hypotheses and tests them with certain groups of customers. This approach focuses on three phases:
pre-deployment, non-commercial deployment, and commercial deployment. The au-
authors present a first systematisation of this so-called “innovation experiment system”
adapted for software development for embedded systems. It is argued that aiming for
an “innovation experiment system” is equally valid for embedded systems as it is in the
case of cloud computing and Software-as-a-Service (SaaS), and that the process could
be similar in both cases. That is, requirements should evolve in real time based on data
collected from systems in actual use with customers.
Inspired by the ideas that define the last stage of the “stairway to heaven”, we
develop and propose the RIGHT model for Continuous Experimentation. In this model,
experiments are derived from business strategies and aim to assess assumptions derived
from those strategies, potentially invalidating or supporting the strategy. Previous works
have explored the application of a framework for linking business goals and strategies
to the software development activities (e.g., [2], [20]). However, those works have
not considered the particular traits of an experiment system such as the one presented
in this paper. The model presented also describes the platform infrastructure that is
necessary to establish the whole experiment system. The Software Factory [8] can serve
as infrastructure for the model proposed, as it is a software development laboratory well
suited for continuous experimentation. In a previous article, in which we presented a
study on creating minimum viable products [19] in the context of collaboration between
industry and academia, we showed the Software Factory laboratory in relation to the
Lean Startup approach and continuous experimentation. Some of the foundational ideas
behind Software Factory with respect to continuous experimentation have been studied
in the past, analysing, for instance, the establishment of laboratories specifically targeted
for continuous development [21] and the impact of continuous integration in teaching
software engineering.
The building blocks presented in this paper, although generalizable with certain
limitations, are derived from a startup environment where the continuous experimen-
tation approach is not only well suited but possibly the only viable option for companies
to grow. Our work has similarities to the “Early Stage Startup Software Development
Model” (ESSSDM) of Bosch et al. [6] which extends existing Lean Startup approaches
offering more operational process support and better decision-making support for startup
companies. Specifically, ESSSDM provides guidance on when to move product ideas forward, when to abandon a product idea, and what techniques to use and when, while validating product ideas. Some of the many challenges faced when trying to establish a startup following the Lean Startup methodology are presented by May [18] with insights that we have considered for the present work.
3. Research approach
Our general research framework can be characterised as design science research [11], in which the purpose is to derive a technological rule which can be used in practice to achieve a desired outcome in a certain field of application [30]. The continuous experimentation model presented in this paper was first constructed based on the related work presented in the previous section as well the authors’ experience. While a framework can be derived by purely analytic means, its validation requires grounding in empirical observations. For this reason, we conducted a holistic multiple case study [32] in the Software Factory laboratory at the Department of Computer Science, University of Helsinki, in which we matched the initial model to empirical observations and made subsequent adjustments to produce the final model. The model can still be considered tentative, pending further validation in other contexts. It is important to note that this study investigates how Continuous Experimentation can be carried out in a systematic way independently of the case projects’ goals and the experiments carried out in them. Those experiments and their outcomes are treated as qualitative findings in the context of this study. In this section, we describe the case study context and the research process.
3.1. Context
The Software Factory is an educational platform for research and industry collaboration [8]. In Software Factory projects, teams of Master’s-level students use contemporary tools and processes to deliver working software prototypes in close collaboration with industry partners. The goal of Software Factory activities is to provide students with means for applying their advanced software development skills in an environment with working life relevance and to deliver meaningful results for their customers [19].
During the case projects used in this study, two of the authors were involved as participant observers. The first author coordinated the case projects: started the projects, handled contractual and other administrative issues, followed up progress through direct interaction with the customer and student teams, ended the projects, handled project debriefing and coordinated the customer interviews. The third author also participated as an observer in several meetings where the customer and student teams collaborated. The researchers were involved in directing the experimentation design activities together with the customer, and students were not directly involved in these activities. However, the customer and students worked autonomously and were responsible for project management, technical decisions, and other issues related to the daily operations of the project.
3.1.1. Case Company 1
Tellybean Ltd. is a small Finnish startup that develops a video calling solution for the home television set. During September 2012–December 2013 the company was a customer in three Software Factory projects with the aim of creating an infrastructure to support measurement and management of the architecture of their video calling service. Tellybean Ltd. aims at delivering a life-like video calling experience. Their value proposition – “the new home phone as a plug and play -experience” – is targeted at late adopter consumer customers who are separated from their families, e.g. due to migration into urban areas, global social connections, or overseas work. The company puts special emphasis on discovering and satisfying needs of the elderly, making ease of use the most important non-functional requirement of their product. The primary means for service differentiation in the marketplace are affordability, accessibility and ease of use. For the première commercial launch, and to establish the primary delivery channel of their product, the company aims at partnering with telecom operators. The company had made an initial in-house architecture and partial implementation during a pre-development phase prior to the Software Factory projects. A first project was conducted to extend the platform functionality of this implementation. A second project was conducted to
1http://www.tellybean.com/
validate concerns related to the satisfaction of operator requirements. After this project, a
technical pivot was conducted, with major portions of the implementation being changed;
the first two projects contributed to this decision. A third project was then conducted
to extend the new implementation with new features related to the ability to manage
software on already delivered products, enabling continuous delivery. The launch
strategy can be described as an MVP launch with post-development adaptation. The
three projects conducted with this company are connected to establishing a continuous
experimentation process and building capabilities to deliver software variations on
which experiments can be conducted. They also provided early evidence regarding the
feasibility of the product for specific stakeholders, such as operator partners, developers,
and release management.
3.1.2. Product
The Tellybean video calling service has the basic functionalities of a home phone: it
allows making and receiving video calls and maintaining a contact list. The product is
based on an Android OS set-top-box (STB) that can be plugged into a modern home
TV. The company maintains a backend system for mediating calls to their correct
respondents. While the server is responsible for routing the calls, the actual video
call is performed as a peer to peer connection between STBs residing in the homes of
Tellybean’s customers.
The company played the role of a product owner in three Software Factory projects
during September 2012–December 2013. The aim of the first two projects was to create
new infrastructure for measuring and analysing usage of their product in its real envi-
ronment. This information was important in order to establish the product’s feasibility
for operators and for architectural decisions regarding scalability, performance, and
robustness. For the present research, the first two projects were used to validate the steps
required to establish a continuous experimentation process. The third project at Software
Factory delivered an automated system for managing and updating the STB software
remotely. This project was used to investigate factors related to the architecture needs
for continuous experimentation. Table 1 summarises the goals and motivations of the
Table 1: Scope of each of the three Tellybean projects at Software Factory.
<table>
<thead>
<tr>
<th>Project</th>
<th>High-level goal</th>
<th>Motivation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Project 1</td>
<td>As an operator, I want to be able to see metrics for calls made by the video call product’s customers.</td>
<td>... so that I can extract and analyse business critical information. ... so that I can identify needs for maintenance of the product’s technical architecture.</td>
</tr>
<tr>
<td>Project 2</td>
<td>As a Tellybean developer, I want to be sure that our product’s system architecture is scalable and robust. As a Tellybean developer, I want to know technical weaknesses of the system. As a Tellybean developer, I want to receive suggestions for alternative technical architecture options.</td>
<td>... so that I know the limitations of the system. ... so that I can predict needs for scalability of the platform. ... so that I can consider future development options.</td>
</tr>
<tr>
<td>Project 3</td>
<td>As a technical manager, I want to be able to push an update to the Tellybean set-top-boxes with a single press of a button.</td>
<td>... so that I can deploy upgrades to the software on one or multiple set-top-boxes.</td>
</tr>
</tbody>
</table>
projects in detail. Each project had a 3–7-person student team, a company representative accessible at all times, and spent effort in the range of 600 and 700 person-hours.
3.1.3. Project 1
The aim of Tellybean’s first project at the Software Factory was to build means for measuring performance of their video calling product in its real environment. The goal was to develop a browser-based business analytics system. The team was also assigned to produce a back-end system for storing and managing data related to video calls, in order to satisfy operator monitoring requirements. The Software Factory project was carried out in seven weeks by a team of four Master’s-level computer science students. Competencies required in the project were database design, application programming, and user interface design.
The backend system for capturing and processing data was built on the Java Enterprise Edition platform, utilising the Spring Open Source framework. The browser-based reporting system was built using JavaScript frameworks D3 and NVD3 to produce vivid and interactive reporting. A cache system of historical call data was implemented to ensure the performance of the system.
After the project had been completed, both students and the customer deemed that the product had been delivered according to the customer’s requirements. Despite the fact that some of the foundational requirements changed during the project due to discoveries of new technological solutions, the customer indicated satisfaction with the end-product. During the project, communication between the customer and the team was frequent and flexible.
The first project constituted a first attempt at conducting continuous experimentation. The goal of the experiment was to gain information about the performance of the system architecture and its initial implementation. The experiment arose from operator needs to monitor call volumes and system load – a requirement that Tellybean’s product developers deemed necessary to be able to partner with operators. It was clear that there existed a set of needs arising from operator requirements, but it was not clear how the information should be presented and what functionality was needed to analyse it. From
a research perspective, however, the exact details of the experiment were less important than the overall process of starting experimentation.
3.1.4. Project 2
The second project executed at Software Factory aimed at performing a system-wide stress test for the company’s video calling service infrastructure. The Software Factory team of four Master’s-level students produced a test tool for simulating very high call volumes. The tool was used to run several tests against Tellybean’s existing call mediator server.
The test software suite included a tool for simulating video call traffic. The tool was implemented using the Python programming language. A browser-based visual reporting interface was also implemented to help analysis of test results. The reporting component was created using existing Javascript frameworks such as Highcharts.js and Underscore.js. Test data was stored in a MongoDB database to be utilised in analysis.
The purpose of the experiment was a counterpart to the experiment in the first project. Whereas the first project had focused on operator needs, the second focused on their implications for developers. The initial system architecture and many of the technical decisions had been questioned. The project aimed to provide evidence for decision-making when revisiting these initial choices.
The team found significant performance bottlenecks in Tellybean’s existing proof-of-concept system and analysed their origins. Solutions for increasing operational capacity of the current live system were proposed and some of them were also implemented. Towards the end of the project, the customer suggested that a new proof-of-concept call mediating server should be proposed by the Software Factory team. The team delivered several suggestions for a new service architecture and composed a new call mediator server. For the purposes of this study, we consider the second experiment to be another round in the continuous experimentation cycle where findings from the first cycle resulted in a new set of questions to experiment on.
3.1.5. Project 3
For their third project at Software Factory, Tellybean aimed to create a centralised infrastructure for updating their video calling product’s software components. The new remote software management system would allow the company to quickly deploy software updates to already delivered STBs. The functionality was business critical to the company and its channel partners: it allowed updating the software without having to travel on-location to each customer to update their STBs. The new instrument enabled the company to establish full control of their own software and hardware assets.
The project consisted of a team of five Master’s-level computer science students. The team delivered a working prototype for rapid deployment of software updates. In this project, the need for a support system to deliver new features or software variations was addressed. We considered the architectural requirements for a continuous delivery system that would support continuous experimentation.
3.1.6. Case Company 2
Memory Trails Ltd. (Memory Trails) is a small Finnish startup that develops a well-being service which helps users define, track, and receive assistance with life goals. During May–July 2014, the company was a customer in a Software Factory project that aimed to develop a backend recommendation engine for the service, improve the front-end user experience, and to validate central assumptions in the service strategy. Memory Trails aims at delivering the service as an HTML5-based application which is optimised for tablets but also works on other devices with an HTML5-compatible browser. The service targets adults who wish to improve their quality of life and change patterns of behaviour to reach different kinds of life goals.
Whereas the projects with the first case company focused mostly on establishing a continuous experimentation process and building capabilities to deliver software variations for experimentation, the project with the second case company focused on some of the details of deriving experiments themselves. In particular, we sought to uncover how assumptions can be identified in initial product or service ideas. These assumptions are candidates for experiments of different kinds.
3.1.7. Project 4
Memory Trails provided an initial user interface and backend system prototype which demonstrated the general characteristics of the application from a user perspective. Users interact with photos which can be placed in different spatial patterns to depict emotional aspects of their goals. Users are guided by the application to arrange the photos as a map, showing the goal, potential steps towards it, and aspects that qualify the goals. For example, a life goal may be to travel around the world. Related photos could depict places to visit, moods to be experienced, items necessary for travel such as tickets, etc. The photos could be arranged, e.g., as a radial pattern with the central goal in the middle, and the related aspects around it, or as a time-line with the end goal to the right and intermediate steps preceding it.
In the project, two high-level assumptions were identified. The customer assumed that automatic, artificial intelligence-based processing in the backend could be used to automatically guide users towards their goals, providing triggers, motivation, and rewards on the way. Also, the customer assumed that the motivation for continued use of the application would come from interacting with the photo map. Since the automatic processing depended on the motivation assumption, the latter became the focus of experimentation in the project. The customer used versions of the application in user tests during which observation and interviews were used to investigate whether the assumption held. For the purposes of this study, we used the project to validate the link in our model between product vision, business model and strategy, and experiment steps.
3.2. Research process
The case study analysis was performed in order to ground the continuous experimentation model in empirical observations, not to understand or describe the projects themselves, nor to assess the business viability of the case companies. Therefore, we collected information that would help us understand the prerequisites for performing continuous experimentation, the associated constraints and challenges, and the logic of integrating experiment results into the business strategy and the development process.
We used four different sources of data in our analysis: (i) participant observation, (ii) analysis of project artefacts, (iii) group analysis sessions, and (iv) individual interviews. We subsequently discuss the details of the data collection and analysis.
During the projects, we observed the challenges the companies faced related to achieving the continuous experimentation system. At the end of each project, an in-depth debriefing session was conducted to gain retrospective insights into the choices made during the project, and the reasoning behind them. In addition to these sources, we interviewed three company representatives from Tellybean to understand their perception of the projects and to gain data which could be matched against our model. We also conducted a joint analysis session with the project team and two representatives from Memory Trails to further match insights on the experimentation process in their project with our model.
The debriefing sessions were conducted in a workshop-like manner, with one researcher leading the sessions and the project team, customer representatives, and any other project observer present. The sessions began with a short introduction by the leader, after which the attendees were asked to list events they considered important for the project. Attendees wrote down each event on a separate sticky note and placed them on a time-line which represented the duration of the project. As event-notes were created, clarifying discussion about their meaning and location on the time-line took place. When attendees could not think of any more events, they were asked to systematically recount the progress of the project using the time-line with events as a guide.
The interviews with customer representatives were conducted either in person on the customer’s premises, online via video conferencing, or on the University of Helsinki’s premises. The interviews were semi-structured thematic interviews, having a mixture of open-ended and closed questions. This interview technique allows participants to freely discuss issues related to a focal theme. Thematic interviews have the advantage that they provide opportunities to discover information that researchers cannot anticipate and that would not be covered by more narrowly defined, closed questions. While they may result in the discussion straying away from the focal theme, this is not a problem in
practice since the interviewer can direct the participant back to the theme and irrelevant information can be ignored in the analysis.
A minimum of two researchers were present in the interviews to ensure that relevant information was correctly extracted. All participating researchers took notes during the interviews, and notes were compared after the interviews to ensure consistency. In the interviews, company representatives were first asked to recount their perception of their company, its goals, and its mode of operation before the three projects. Then, they were asked to consider what each project had accomplished in terms of software outcomes, learned information, and implications for the goals and mode of operation of the company. Finally, they were asked to reflect on how the company operated at the time of the interview and how they viewed the development process, especially in terms of incorporating market feedback into decision-making.
During analysis, the project data were examined for information relevant to the research question. We categorised the pieces of evidence according to whether they related to the Continuous Experimentation process or to the infrastructure. We sought to group the observations made and understanding gained during the projects with evidence from the retrospective sessions and interviews so that the evidence was triangulated and thus strengthened. Such groups of triangulated evidence was then matched with our initial model, which was similar to the sequence shown in Figure 1, and included the build-measure-learn cycle for the process, and a data repository, analysis tools, and continuous delivery system as infrastructure components. We adjusted the model and introduced new process steps and infrastructure components that supported the need implied by the evidence. We strived for minimal models, and when more than one need could be fulfilled with a single step or component, we did not introduce more steps or components. When all the evidence had been considered, we evaluated the result as a whole and made some adjustments and simplifications based on our understanding and judgement.
4. Results
In this section, we first describe our proposed model for continuous experimentation, and then report on the insights gained from the multiple case study and how they inform the different parts of the model.
4.1. The RIGHT model for Continuous Experimentation
By continuous experimentation, we refer to a software development approach that is based on field experiments with relevant stakeholders, typically customers or users, but potentially also with other stakeholders such as investors, third-party developers, or software ecosystem partners. The model consists of repeated Build-Measure-Learn blocks, supported by an infrastructure, as shown in Figure 1. Each Build-Measure-Learn block results in learnings which are used as input for the next block. Conceptually, the model can also be thought to apply not only to software development, but also to design and development of software-intensive products and services. In some cases, experimentation using this model may require little or no development of software.
The Build-Measure-Learn blocks structure the activity of conducting experiments, and connect product vision, business strategy, and technological product development through experimentation. In other words, the requirements, design, implementation, testing, deployment, and maintenance phases of software development are integrated and aligned by empirical information gained through experimentation. The model can be considered a vehicle for incremental innovation as defined by Henderson and Clark [10], but the model itself, as well as the transition to continuous experimentation in general, can be considered radical, architectural innovations that require significant new organisational capabilities.
4.1.1. The RIGHT process model for Continuous Experimentation
Figure 2 expands the Build-Measure-Learn blocks and describes the RIGHT process model for Continuous Experimentation. A general vision of the product or service is assumed to exist. Following the Lean Startup methodology [26], this vision is fairly stable and is based on knowledge and beliefs held by the entrepreneur. The vision is connected to the business model and strategy, which is a description of how to execute the vision. The business model and strategy are more flexible than the vision, and consist of multiple assumptions regarding the actions required to bring a product or service to market that fulfils the vision and is sustainably profitable. However, each assumption has inherent uncertainties. In order to reduce the uncertainties, we propose to conduct experiments. An experiment operationalises the assumption and states a hypothesis that can be subjected to experimental testing in order to gain knowledge regarding the assumption. The highest-priority hypotheses are selected first. Once a hypothesis is formulated, two parallel activities can occur. The hypothesis can optionally be used to implement and deploy a Minimum Viable Product (MVP) or Minimum Viable Feature (MVF), which is used in the experiment and has the necessary instrumentation. Simultaneously, an experiment is designed to test the hypothesis. The experiment is then executed and data from the MVP/MVF are collected in accordance with the experimental design. The resulting data are analysed, concluding the experimental activities.
Once the experiment has been conducted and analysis performed, the analysis results are used on the strategy level to support decision-making. Again following Lean Startup terminology, the decision can be to either “pivot” or “persevere” [26], but a third alternative is also possible: to change assumptions in the light of new information. If the experiment has given support to the hypothesis, and thus the assumption on the strategy level, a full product or feature is developed or optimised, and deployed. The strategic decision in this case is to persevere with the chosen strategy. If, on the other hand, the hypothesis was falsified, invalidating the assumption on the strategy level, the decision is to pivot and alter the strategy by considering the implications of the assumption being false. Alternatively, the tested assumption could be changed, but not
Figure 2: The RIGHT process model for Continuous Experimentation.
4.1.2. The RIGHT infrastructure architecture for Continuous Experimentation
To support conducting such experiments, an infrastructure for continuous experimentation is needed. Figure 3 sketches the RIGHT infrastructure architecture for Continuous Experimentation, with roles and associated tasks, the technical infrastructure, and information artefacts. The roles indicated here will be instantiated in different ways depending on the type of company in question. In a small company, such as a startup, a small number of persons will handle the different roles and one person may have more than one role. In a large company, the roles are handled by multiple teams. Seven roles are defined to handle four classes of tasks. A business analyst and a product owner, or a product management team, together handle the creation and iterative updating of the strategic roadmap. In order to do so, they consult existing experimental plans, results, and learnings, which reside in a back-end system. As plans and results accumulate and are stored, they may be reused in further development of the roadmap. The business
analyst and product owner work with a data scientist role, which is usually a team with diverse skills, to communicate the assumptions of the roadmap and map the areas of uncertainty which need to be tested.
The data scientist designs, executes, and analyses experiments. A variety of tools are used for this purpose, which access raw data in the back-end system. Conceptually, raw data and experiment plans are retrieved, analysis performed, and results produced in the form of learnings, which are stored back into the back-end system.
The data analyst also communicates with a developer and quality assurance role. These roles handle the development of MVPs, MVFs, and the final product. They first work with the data analyst to produce proper instrumentation into the front-end system, which is the part of the software which is delivered or visible to the user. In the case of a persevere-decision, they work to fully develop or optimise the feature and submit it for deployment into production. MVPs, MVFs, and final products are deployed to users after first going through the continuous integration and continuous delivery systems. A DevOps engineer acts as the mediator between the development team and operations, and a release engineer may oversee and manage the releases currently in production. Importantly, the continuous delivery system provides information on software roll-out status, allowing other roles to monitor the experiment execution and, e.g., gain an understanding of the conditions under which the software was deployed to users and of the sample characteristics and response rate of the experiment. Cross-cutting concerns.
such as User Experience may require additional roles working with several of the roles mentioned here. To simplify the figure, we have omitted the various roles that relate to operations, such as site reliability engineer, etc. Also, we have omitted a full elaboration of which information artefacts should be visible to which roles. In general, we assume that is is beneficial to visualise the state of the continuous experimentation system for all roles.
The back-end system consists of an experiment database which, conceptually, stores raw data collected from the software instrumentation, experiment plans – which include programmatic features of sample selection and other logic needed to conduct the experiment – and experiment results. The back-end system and the database are accessible through an API. Here, these parts should be understood as conceptual; an actual system likely consists of multiple APIs, databases, servers, etc. The experiment database enables a product architecture where deployed software is configured for experiments at run-time. Thus it is not always required that a new version of the software or the accompanying instrumentation is shipped to users prior to an experiment; the experimental capability can be built into the shipped software as a configurable variation scheme. The shipped software fetches configuration parameters for new experiments, reconfigures itself, and sends back the resulting measurement data, eliminating the need to perform the Develop Product and Deploy Product tasks. For larger changes, a new software version may be required, and the full set of tasks performed.
4.2. Model instantiations and lessons learned
In this subsection, we describe how the RIGHT models were instantiated in the four projects, and we describe the lessons learned. We include illustrative examples from our interview data. We note that the model was initially quite simple, similar to the sequence described in Figure 1 with a build-measure-learn cycle, a data repository, analysis tools, and continuous delivery system. We also note that not all parts of the models were instantiated in all projects. We assume that this will be the case in other projects as well. In the first two projects, we focused on problem validation: developing an understanding of the needs in real situations that a model for continuous experimentation should address. In the two latter projects, we already had most of the model in place and
focused more on validating our solution, using detailed findings from the projects in order to adjust the model.
Each of the four case projects relate to different aspects of continuous experimentation. The case findings support the need for systematic integration of all levels of software product and service development, especially when the context is rapid new product and service development. The key issue is to develop a product that customers will buy, given tight financial constraints. Startup companies operate in volatile markets and under high uncertainty. They may have to do several quick changes as they get feedback from the market. The challenge is to reach product-market fit before running out of money.
“You have to be flexible because of money, time and technology constraints. The biggest question for us has been how to best use resources we have to achieve our vision. In a startup, you are time-constrained because you have a very limited amount of money. So you need to use that time and money very carefully.” (Tellybean founder)
When making changes in the direction of the company, it is necessary to base decisions on sound evidence rather than guesswork. However, we found that it is typically not the product or service vision that needs to change. The change should rather concern the strategy by which the vision is implemented, including the features that should be implemented, their design, and the technological platform on which the implementation is based. For example, although Tellybean has had to adapt several times, the main vision of the company has not changed.
“The vision has stayed the same: lifelike video calling on your TV. It is very simple; everyone in the company knows it. The TV part doesn’t change, but the business environment is changing. The technology – the hardware and software – is changing all the time.” (Tellybean founder)
“We had to pivot when it comes to technology and prioritising features. But the main offering is still the same: it’s the new home phone and it connects to your TV. That hasn’t changed. I see the pivots more like springboards to
the next level. For example, we made a tablet version to [gain a distributor partner].” (Tellybean CTO)
Also, although an experiment design is, at best, self-evident when viewed in hindsight, developing one based on the information available in actual software projects, especially new product or service development, is not an easy task. There are multiple possibilities for what to experiment on, and it is not obvious how to choose the first experiment or each next experiment after that. Our case projects showed that initiating the continuous experimentation process is a significant task in its own right and involves much learning. This strengthens the notion that a basic and uncomplicated model to guide the process in the right direction is needed.
4.2.1. Project 1
In the first project, the new business analytics instrument allowed Tellybean to yield insights on their system’s statistics, providing the company a means for feedback. They could gain a near-real-time view on call related activities, yielding business critical information for deeper analysis. The presence of the call data could be used as input for informed decisions. It also allowed learning about service quality and identifying customer call behaviour patterns. Based on the customer’s comments, such information would be crucial for decision-making regarding the scaling of the platform. Excess capacity could thus be avoided and the system would be more profitable to operate while still maintaining a good service level for end users. The primary reason for wanting to demonstrate such capabilities was the need to satisfy operator needs. To convince operators to become channel partners, the ability to respond to fluctuations in call volumes was identified as critical. Potential investors would be more inclined to invest in a company that could convince channel operators of the technical viability of the service.
“There were benefits in terms of learning. We were able to show things to investors and other stakeholders. We could show them examples of metric data even if it was just screenshots.” (Tellybean CTO)
The high-level goal of the first project could be considered as defining a business hypothesis to test the business model from the viewpoint of the operators. The project delivered the needed metrics as well as a tool-supported infrastructure to gather the necessary data. These results could be used to set up an experiment to test the business hypotheses.
Table 2 shows the parts of our model that were instantiated in Project 1. The project instantiated a few basic elements of the RIGHT process model. The chosen business model and strategy was to offer the video calling service through operator partnerships. In order for the strategy to be successful, the company needed to demonstrate the feasibility of the service in terms of operator needs and requirements. This demonstration was to operators themselves but also to other stakeholders, such as investors, who assessed the business model and strategy. The hypothesis to test was not very precisely defined in the project, but could be summarised as “operators will require system performance management analysis tools in order to enter a partnership”. The experiment, which was obviously not a controlled one but rather conducted as part of investor and operator negotiations, used the analytics instrument developed in the project to assess whether the assumption was correct, thus instantiating an MVF, and making a rudimentary experiment execution and analysis. Based on this information, some decisions were made: to start investigating alternative architectures and product implementation strategies.
4.2.2. Project 2
In the second project, Tellybean was able to learn the limitations of the current proof-of-concept system and its architecture. An alternative call mediator server and an alternative architecture for the system were very important for the future development of the service. The lessons learned in the second project, combined with the results of the first, prompted them to pivot heavily regarding the technology, architectural solutions, and development methodology.
“The Software Factory project […] put us on the path of ‘Lego software development’, building software out of off-the-shelf, pluggable components. It got us thinking about what else we should be doing differently. […] We
Table 2: Model instantiations in Project 1.
<table>
<thead>
<tr>
<th>Process model instantiation</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Vision</strong></td>
</tr>
<tr>
<td>Video calling in the home</td>
</tr>
<tr>
<td><strong>Business model and strategy</strong></td>
</tr>
<tr>
<td>Offer video calling through operator partnerships</td>
</tr>
<tr>
<td>(+ assumptions about architecture and product implementation strategies)</td>
</tr>
<tr>
<td><strong>Hypotheses</strong></td>
</tr>
<tr>
<td>“Operators will require performance management analysis tools in order to enter a partnership”</td>
</tr>
<tr>
<td><strong>Design, execute, analyse</strong></td>
</tr>
<tr>
<td>Rudimentary</td>
</tr>
<tr>
<td><strong>MVF</strong></td>
</tr>
<tr>
<td>Analytics instrument</td>
</tr>
<tr>
<td><strong>Decision making</strong></td>
</tr>
<tr>
<td>Start architectural pivot (continued in Project 2)</td>
</tr>
<tr>
<td>Start product implementation strategy pivot (continued in Project 2)</td>
</tr>
<tr>
<td>Validate further assumptions (regarding architecture and product implementation)</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Infrastructure model instantiation (only applicable parts)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Roles</strong></td>
</tr>
<tr>
<td>Business analyst, product owner (played by company leadership), software developer (played by Software Factory students)</td>
</tr>
<tr>
<td><strong>Technical Infrastructure</strong></td>
</tr>
<tr>
<td>Analytics Tools (MVF developed in project)</td>
</tr>
<tr>
<td><strong>Information Artefacts</strong></td>
</tr>
<tr>
<td>Learnings (not formally documented in project)</td>
</tr>
</tbody>
</table>
were thinking about making our own hardware. We had a lot of risk and high expenses. Now we have moved to existing available hardware. Instead of a client application approach, we are using a web-based platform. This expands the possible reach of our offering. We are also looking at other platforms. For example, Samsung just released a new SDK for Smart TVs.” (Tellybean founder)
“Choosing the right Android-based technology platform has really sped things up a lot. We initially tried to do the whole technology stack from hardware to application. The trick is to find your segment in the technology stack, work there, and source the rest from outside. We have explored several Android-based options, some of which were way too expensive. Now we have started to find ways of doing things that give us the least amount of problems. But one really important thing is that a year ago, there were no Android devices like this. Now there are devices that can do everything we need. So the situation has changed a lot.” (Tellybean CTO)
The high-level goals of the second project could be considered as defining and testing a solution hypothesis that addresses the feasibility of the proposed hardware-software solution. The project delivered an evaluation of the technical solution as well as improvement proposals. The analysis showed that the initial architecture and product implementation strategy were too resource-consuming to carry out fully. The results were used by the company to modify their strategy. Instead of implementing the hardware themselves, they opted for a strategy where they would build on top of generic hardware platforms and thus shorten time-to-market and development costs. Table 3 shows the model instantiations in Project 2.
4.2.3. Project 3
In the third project, the capability for continuous deployment was developed. The STBs could be updated remotely, allowing new features to be pushed to customers at very low cost and with little effort. The implications of this capability are that the company is able to react to changes in their technological solution space by updating operating
Table 3: Model instantiations in Project 2.
<table>
<thead>
<tr>
<th>Process model instantiation</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Vision</strong></td>
</tr>
<tr>
<td>Video calling in the home</td>
</tr>
<tr>
<td><strong>Business model and strategy</strong></td>
</tr>
<tr>
<td>Offer video calling through operator partnerships (+ assumptions about architecture and product implementation strategies)</td>
</tr>
<tr>
<td><strong>Hypotheses</strong></td>
</tr>
<tr>
<td>“Product should be developed as custom hardware-software codesign” and “Architecture should be based on Enterprise Java technology and be independent of TV set (which acts only as display)”</td>
</tr>
<tr>
<td><strong>Design, execute, analyse</strong></td>
</tr>
<tr>
<td>Prototype implementation; evaluate current solution proposal</td>
</tr>
<tr>
<td><strong>MVF</strong></td>
</tr>
<tr>
<td>Alternative call mediator server; alternative system architecture</td>
</tr>
<tr>
<td><strong>Decision making</strong></td>
</tr>
<tr>
<td>Architectural pivot (Android-based COTS hardware and OS)</td>
</tr>
<tr>
<td>Product implementation strategy pivot (do not develop custom hardware)</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Infrastructure model instantiation (only applicable parts)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Roles</strong></td>
</tr>
<tr>
<td>Business analyst, product owner (played by company leadership), software developer (played by Software Factory students)</td>
</tr>
<tr>
<td><strong>Technical Infrastructure</strong></td>
</tr>
<tr>
<td>Analytics Tools (from previous project)</td>
</tr>
<tr>
<td><strong>Information Artefacts</strong></td>
</tr>
<tr>
<td>Learnings (not formally documented in project)</td>
</tr>
</tbody>
</table>
system and application software, and to emerging customer needs by deploying new features and testing feature variants continuously.
The high-level goals of the third project could be considered as developing a capability that allows for automating the continuous deployment process. The prerequisite for this is a steady and controlled pace of development where the focus is on managing the amount of work items that are open concurrently in order to limit complexity. At Tellybean, this is known as the concept of one-piece flow.
“The one-piece flow means productisation. In development, it means you finish one thing before moving on to the next. It’s a bit of a luxury in development, but since we have a small team, it’s possible. On the business side, the most important thing has been to use visual aids for business development and for prioritising. In the future we might try to manage multiple-piece flows.” (Tellybean founder)
The third project instantiated parts of our infrastructure architecture model, shown in Table 4. In particular, it focused on the role of a continuous delivery system in relation to the tasks that need to be carried out for continuous experimentation, meaning that top and rightmost parts of Figure 3 were instantiated, as detailed in the table.
4.2.4. Project 4
In the fourth project, it was initially difficult to identify what the customers considered to be the main assumptions. However, once the main assumptions became clear, it was possible to focus on validating them. This highlights the finding that although it is straightforward in theory to assume that hypotheses should be derived from the business model and strategy, it may not be straightforward in practice. In new product and service development, the business model and strategy is not finished, and, especially in the early cycles of experimentation, it may be necessary to try several alternatives and spend effort on modelling assumptions until a good set of hypotheses is obtained. We therefore found it useful to separate the identification and prioritisation of hypotheses on the strategy level from the detailed formulation of hypotheses and experiment design on the experiment level. Table 5 shows the instantiated model parts in Project 4. We
<table>
<thead>
<tr>
<th>Table 4: Model instantiations in Project 3.</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Process model instantiation</strong></td>
</tr>
<tr>
<td>Vision</td>
</tr>
<tr>
<td>Business model and strategy</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>Hypotheses</td>
</tr>
<tr>
<td>Design, execute, analyse</td>
</tr>
<tr>
<td>MVF</td>
</tr>
<tr>
<td>Decision making</td>
</tr>
<tr>
<td><strong>Infrastructure model instantiation (only applicable parts)</strong></td>
</tr>
<tr>
<td>Roles</td>
</tr>
<tr>
<td>Technical infrastructure</td>
</tr>
<tr>
<td>Information artefacts</td>
</tr>
</tbody>
</table>
note that some of these parts were introduced into the model because of our findings from Project 4.
In this project, there were two assumptions: that interaction with the photo map would retain users, and that an automated process of guiding users towards goals was feasible. The assumption that continued use of the application would come from interacting with the photo map was shown to be incorrect. Users would initially create the map, but would not spend much time interacting with it – by, e.g., adding or changing photos, rearranging the map, adding photo annotations, etc. Instead, users reported a desire for connecting with other users to share maps and discuss life goals. Also, they expressed a willingness to connect with professional or semi-professional coaches to get help with implementing their life goals. The social aspect of the service had been overlooked. Whether this was due to familiarity with existing social media applications was left uninvestigated. In any case, the assumption was invalidated and as a result, the assumptions regarding automated features for guiding users towards goals were also invalidated. The investigation indicated that users were motivated by the potential for interaction with other users, and that these interactions should include the process of motivating them to reach goals. It is important to note that the two hypotheses could be invalidated because they were dependent. The process of identifying and prioritising hypotheses separately from detailed formulation of hypotheses and experiment design makes it possible to choose the order of experiments in a way that gains the maximum amount of information with the minimum number of experiments. Testing the most fundamental assumptions – the ones on which most other assumptions rely – first, allows the possibility of eliminating other assumptions with no additional effort.
The fourth project also revealed challenges involved with instrumenting the application for data collection. It was difficult to separate the process of continuous experimentation from the technical prerequisites for instrumentation. In many cases, substantial investments into technical infrastructure may be needed before experiments can be carried out. These findings led to the roles, the high-level description of the technical infrastructure, and the information artefacts in the infrastructure architecture (see Figure 3).
Table 5: Model instantiations in Project 4.
<table>
<thead>
<tr>
<th>Process model instantiation</th>
<th>Vision</th>
<th>Business model and strategy</th>
<th>Hypotheses</th>
</tr>
</thead>
<tbody>
<tr>
<td>Vision</td>
<td>Well-being service for defining, tracking, and receiving assistance with life goals</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Business model and strategy</td>
<td>Product and service recommendations, automated recommendation engine for motivating progress towards goals</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Hypotheses</td>
<td>“Motivation for continued use comes from interacting with photo map” and “Automatic recommendation engine will automatically guide users to reach goals” (depends on first hypothesis)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Design, execute, analyse</td>
<td>User tests with observation and interviews</td>
<td></td>
<td></td>
</tr>
<tr>
<td>MVF</td>
<td>HTML5-based, tablet-optimised application</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Decision making</td>
<td>Product implementation strategy pivot (focus on social interaction rather than automated recommendations)</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Infrastructure model instantiation (only applicable parts)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Roles</td>
</tr>
<tr>
<td>Technical infrastructure</td>
</tr>
<tr>
<td>Information artefacts</td>
</tr>
</tbody>
</table>
However, many experiments are also possible without advanced instrumentation. The fourth project indicates that experiments may typically be large, or target high-level questions, in the beginning of the product or service development cycle. They may address questions and assumptions which are central to the whole product or service concept. Later stages of experimentation may address more detailed aspects, and may be considered optimisation of an existing product or service.
5. Discussion
The continuous experimentation model developed in the previous section can be seen as a general description. Many variations are possible. For instance, experiments may be deployed to selected customers in a special test environment, and several experiments may be run in parallel. A special test environment may be needed particularly in business-to-business markets, where the implications of feature changes are broad and there may be reluctance towards having new features at all. The length of the test cycle may thus have to be longer in business-to-business markets. Direct deployment could be more suitable for consumer markets, but we note that the attitude towards continuous experimentation is likely to change as both business and consumer customers become accustomed to it.
Each project could have instantiated the RIGHT models in different ways. In the first project, the experiment could have been carried out using mockup screens to validate what metric data, visualisation, and analysis tools would have been sufficient to convince the stakeholders. However, this would have been detrimental since it would not have revealed the shortcomings in the initial architecture and implementation strategy. Although the design of the experiment left much to be desired, carrying it out using a real, programmed prototype system made it possible to discover the need to reconsider some of the previous strategy choices.
In the second project, the learnings could have been better used to define a more precise set of hypotheses after a careful analysis of the shortcomings of the previous system architecture. However, this was not necessary since the purpose was not a point-by-point comparison but rather an either-or comparison between one general approach
and another. This highlights an important notion regarding continuous experimentation:
it only seeks to produce enough information for a decision to be made correctly.
In the third project, only the capability for continuous delivery was instantiated. The
project could also have addressed the components that are necessary to carry out actual
experiments. Due to project time constraints, this was left uninvestigated in the third
project, but was considered in the fourth project instead. In that project, one cycle of
the full RIGHT process model was carried out, and the software was instrumented for
experimentation although using ready-made services such as Google Analytics.
While our ultimate aim is for our models to cover the entire breadth of continuous
experimentation, we assume that not all real-life projects will need to instantiate all parts.
For instance, experiments can be conducted without an MVP, especially in an early
stage of product development. It may also not be necessary in all cases to have a heavy
infrastructure for the experimentation – this becomes relevant if experimentation is
conducted in very large volumes or when the purpose is to maintain a set of experiments
that are run continuously to collect trend information while the product is incrementally
changed.
In addition to the project-specific observations, we consider some more general
concerns. Having several experiments run in parallel presents a particular challenge.
The difficulty of interpreting online experiments has been convincingly demonstrated by
Kohavi et al. [16]. Statistical interactions between experiments should be considered in
order to assess the trustworthiness of the experiments. For this reason, it is important to
coordinate the design and execution of experiments so that correct inferences are drawn.
More generally, the issue of validity becomes important when the entire R&D organisa-
tion is experiment-driven. Incorrectly designed or implemented experiments may lead
to critical errors in decision-making. Threats to validity can also stem from a failure to
consider ethical aspects of experiments. Not only may unethical experiments damage
company reputation, but they may cause respondents to knowingly or unconsciously
bias the experimental results, leading to errors in decision-making.
Other challenges include the difficulty of prioritising where to start: which assump-
tion should be tested first. In Project 4, we identified a dependency between assumptions
regarding the backend recommendation logic and the assumption of what motivates users
to keep using the application. By invalidating the latter, we automatically invalidated the first assumption. This highlights the importance of identifying critical assumptions, as testing them first may save several unneeded experiments. We see a need for further research into this area. Also, in hardware-software co-design, illustrated by the first three projects, setting up the experimental cycle quickly is a major challenge due to both the longer release cycle of hardware and the potential synchronisation problems between hardware and software development schedules. Based on the findings presented in this paper, it may be beneficial to test a few strategic technical assumptions first, such as the viability of a certain hardware-software platform. As our case demonstrates, choosing the correct platform early can have a significant impact on the ability to proceed to actual service development.
A further set of challenges have to do with the model of sales and supplier networks. Essentially all companies are dependent on a network of suppliers and sales channels. It may be necessary to extend the model presented here to take into account the capabilities particularly of hardware suppliers to supply the needed components in a timely fashion and with the needed flexibility to programmatically vary behavioural parameters in these components. Also, when the company is not selling its products directly to end users, several levels of intermediaries may interfere with the possibilities to collect data directly from field use. If a sales partner cannot grant access to end users, other means of reaching the audience are needed. We envision using early-access and beta-test programs for this purpose, a practice that is commonly used in the computer gaming industry. Other models are possible, and there is an opening for further research in this area.
In some cases, an experimental approach may not be suitable at all. For example, certain kinds of life-critical software or software that is used in environments where experimentation is prohibitively expensive, may preclude the use of experiments as a method of validation. However, it is not clear how to determine the suitability of an experimental approach in specific situations, and research on this topic could yield valuable guidelines on when to apply the model presented here.
Another question is whether continuous delivery is a strictly necessary precondition for continuous experimentation. In the beginning of the product development cycle,
experimentation must occur before much software is written at all. At that stage, continuous delivery may not be necessary. Also, not all experiments require new software to be delivered to users. While a continuous delivery system may exist, the software itself may be architected for variability so that it can reconfigure itself at run-time. In such cases, no new version of the software needs to be delivered for new experiments to run. However, not all experiments are possible even with a very flexible architecture that allows for run-time reconfiguration. Continuous delivery is a good vehicle for delivering experiments to users and to ensure quality in the development process. The model presented here is based on iterative, evolutive optimisation of product features and an incremental model of innovation. To carry out revolutionary innovation, the process needs to be extended with other means of discovering customer value. These may profoundly invalidate the business model or strategy, and may even have an impact on the overall vision.
Finally, experimentation may be conducted with several kinds of stakeholders. Apart from customers and end users, experiments could be directed towards investors, suppliers, sales channels, or distributors. Companies whose product is itself a development platform may want to conduct experiments with developers in their platform ecosystem to optimise the developer experience [9] of their tools, methods, and processes. These experiments may require other kinds of experimental artefacts than the MVP/MVF, including, e.g., processes, APIs, and documentation. Research on the types of experimental artefacts and associated experimental designs could lead to fruitful results for such application areas. Also, an open question is who should primarily lead or conduct the experimentation, especially when the development organisation is separate from the customer organisation. Some training may be needed for customers in order to ensure that they can interact with the continuous experimentation process running in the development organisation. Similarly, the development team may need additional training to be able to interact with the customer to derive assumptions, plan experiments, and report results for subsequent decision-making. Another possibility is to introduce a mediating role which connects the customer and development organisations. More generally, increasing the capability to perform experimentation and continuous software engineering requires consideration of human factors in software development teams [23].
Further research is needed to determine how the experimental process works across organisational borders, whether within or outside a single company.
A particular limitation of this study is the use of relatively short projects with student participants. Students carried out the technical software development and analysis tasks in the projects, while the researchers handled tasks related to identification of assumptions, generation of hypotheses, and higher-level planning tasks together with customer representatives. While it is reasonable to expect that professional software developers would have reached a different level of quality and rigour in the technical tasks, we consider it likely that the findings are applicable beyond student projects since the focus of this paper is not on the technical implementation but on the integration of experiment results in the product development cycle and the software development process. The length of the projects means that at most one experimental cycle could be carried out in a single project. Thus the first case company completed three, and the second case company one experimental cycle. In a real setting, multiple experimentation rounds would be carried out over an extended period of time, proceeding from experiments addressing the most important assumptions with the highest impact towards increasing detail and optimisation. The findings of this study should be considered to apply mostly in the early stages of experimentation.
6. Conclusions
Companies are increasingly transitioning their traditional research and product development functions towards continuous experiment systems [12]. Integrating field experiments with product development on business and technical levels is an emerging challenge. There are reports of many companies successfully conducting online experiments, but there is a lack of a systematic framework model for describing how such experiments should be carried out and used systematically in product development. Empirical studies on the topic of continuous experimentation in software product development is a fruitful ground for further research. Software companies would benefit from clear guidelines on when and how to apply continuous experimentation in the design and development of software-intensive products and services.
In this paper, we match a model for Continuous Experimentation based on analysis of previous research against a multiple case study in the Software Factory laboratory at the University of Helsinki. The model describes the experimentation process, in which assumptions for product and business development are derived from the business strategy, systematically tested, and the results used to inform further development of the strategy and product. The infrastructure architecture for supporting the model takes into account the roles, tasks, technical infrastructure, and information artefacts needed to run large-scale continuous experiments.
A system for continuous experimentation requires the ability to release minimum viable products or features with suitable instrumentation, design and manage experiment plans, link experiment results with a product roadmap, and manage a flexible business strategy. There are several critical success factors for such a system. The organisation must be able to properly and rapidly design experiments, perform advanced instrumentation of software to collect, analyse, and store relevant data, and integrate experiment results in both the product development cycle and the software development process. Feedback loops must exist through which relevant information is fed back from experiments into several parts of the organisation. A proper understanding of what to test and why must exist, and the organisation needs a workforce with the ability to collect and analyse qualitative and quantitative data. Also, it is crucial that the organisation has the ability to properly define decision criteria and act on data-driven decisions.
In future work, we expect the model to be expanded as more use cases arise in the field. Domain-specific variants of the model may also be needed. Furthermore, there are many particular questions with regard to the individual parts of the model. Some specific areas include (i) how to prioritise assumptions and select which assumptions to test first; (ii) how to assess validity and determine how far experimental results can be trusted – especially how to ensure that experiments are trustworthy when running potentially thousands of them in parallel; (iii) how to select proper experimental methods for different levels of product or service maturity; and (iv) how to build a back-end system for continuous experimentation that can scale to the needs of very large deployments, and can facilitate and even partially automate the creation of experimental plans. Particular questions regarding automation include which parts of the model could be automated or
supported through automation. Another question is how quickly a Build-Measure-Learn block can be executed, and what the performance impact of the model is on the software development process.
Acknowledgements
This work was supported by Tekes – the Finnish Funding Agency for Technology and Innovation, as part of the N4S Program of DIGILE (Finnish Strategic Centre for Science, Technology and Innovation in the field of ICT and digital business).
References
|
{"Source-Url": "https://helda.helsinki.fi//bitstream/handle/10138/175085/rightmodel.pdf?sequence=1", "len_cl100k_base": 16189, "olmocr-version": "0.1.53", "pdf-total-pages": 44, "total-fallback-pages": 0, "total-input-tokens": 96649, "total-output-tokens": 19393, "length": "2e13", "weborganizer": {"__label__adult": 0.00042366981506347656, "__label__art_design": 0.0007109642028808594, "__label__crime_law": 0.0002651214599609375, "__label__education_jobs": 0.005924224853515625, "__label__entertainment": 9.995698928833008e-05, "__label__fashion_beauty": 0.0002161264419555664, "__label__finance_business": 0.000690460205078125, "__label__food_dining": 0.0003676414489746094, "__label__games": 0.0008702278137207031, "__label__hardware": 0.0009431838989257812, "__label__health": 0.0004742145538330078, "__label__history": 0.000469207763671875, "__label__home_hobbies": 0.00014293193817138672, "__label__industrial": 0.0004360675811767578, "__label__literature": 0.0005102157592773438, "__label__politics": 0.000247955322265625, "__label__religion": 0.0004949569702148438, "__label__science_tech": 0.017791748046875, "__label__social_life": 0.0001418590545654297, "__label__software": 0.00595855712890625, "__label__software_dev": 0.96142578125, "__label__sports_fitness": 0.0003108978271484375, "__label__transportation": 0.0006313323974609375, "__label__travel": 0.00023281574249267575}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 93749, 0.02199]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 93749, 0.19601]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 93749, 0.94462]], "google_gemma-3-12b-it_contains_pii": [[0, 615, false], [615, 2940, null], [2940, 4805, null], [4805, 6748, null], [6748, 8962, null], [8962, 11565, null], [11565, 14058, null], [14058, 16389, null], [16389, 18873, null], [18873, 21443, null], [21443, 23681, null], [23681, 25990, null], [25990, 28287, null], [28287, 29432, null], [29432, 31675, null], [31675, 33742, null], [33742, 35986, null], [35986, 38225, null], [38225, 40640, null], [40640, 42799, null], [42799, 44543, null], [44543, 47001, null], [47001, 48179, null], [48179, 49833, null], [49833, 52299, null], [52299, 54425, null], [54425, 56536, null], [56536, 58813, null], [58813, 60396, null], [60396, 62518, null], [62518, 64343, null], [64343, 66607, null], [66607, 68095, null], [68095, 70519, null], [70519, 72070, null], [72070, 74337, null], [74337, 76923, null], [76923, 79455, null], [79455, 82042, null], [82042, 84372, null], [84372, 87011, null], [87011, 89349, null], [89349, 92079, null], [92079, 93749, null]], "google_gemma-3-12b-it_is_public_document": [[0, 615, true], [615, 2940, null], [2940, 4805, null], [4805, 6748, null], [6748, 8962, null], [8962, 11565, null], [11565, 14058, null], [14058, 16389, null], [16389, 18873, null], [18873, 21443, null], [21443, 23681, null], [23681, 25990, null], [25990, 28287, null], [28287, 29432, null], [29432, 31675, null], [31675, 33742, null], [33742, 35986, null], [35986, 38225, null], [38225, 40640, null], [40640, 42799, null], [42799, 44543, null], [44543, 47001, null], [47001, 48179, null], [48179, 49833, null], [49833, 52299, null], [52299, 54425, null], [54425, 56536, null], [56536, 58813, null], [58813, 60396, null], [60396, 62518, null], [62518, 64343, null], [64343, 66607, null], [66607, 68095, null], [68095, 70519, null], [70519, 72070, null], [72070, 74337, null], [74337, 76923, null], [76923, 79455, null], [79455, 82042, null], [82042, 84372, null], [84372, 87011, null], [87011, 89349, null], [89349, 92079, null], [92079, 93749, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 93749, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 93749, null]], "pdf_page_numbers": [[0, 615, 1], [615, 2940, 2], [2940, 4805, 3], [4805, 6748, 4], [6748, 8962, 5], [8962, 11565, 6], [11565, 14058, 7], [14058, 16389, 8], [16389, 18873, 9], [18873, 21443, 10], [21443, 23681, 11], [23681, 25990, 12], [25990, 28287, 13], [28287, 29432, 14], [29432, 31675, 15], [31675, 33742, 16], [33742, 35986, 17], [35986, 38225, 18], [38225, 40640, 19], [40640, 42799, 20], [42799, 44543, 21], [44543, 47001, 22], [47001, 48179, 23], [48179, 49833, 24], [49833, 52299, 25], [52299, 54425, 26], [54425, 56536, 27], [56536, 58813, 28], [58813, 60396, 29], [60396, 62518, 30], [62518, 64343, 31], [64343, 66607, 32], [66607, 68095, 33], [68095, 70519, 34], [70519, 72070, 35], [72070, 74337, 36], [74337, 76923, 37], [76923, 79455, 38], [79455, 82042, 39], [82042, 84372, 40], [84372, 87011, 41], [87011, 89349, 42], [89349, 92079, 43], [92079, 93749, 44]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 93749, 0.21739]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
81a0f6613ffb61d49c635234b02746997d446c74
|
7-2013
**SROIQ Syntax Approximation by Using Nominal Schemas**
Cong Wang
David Carral
Pascal Hitzler
pascal.hitzler@wright.edu
Follow this and additional works at: [https://corescholar.libraries.wright.edu/cse](https://corescholar.libraries.wright.edu/cse)
Part of the Computer Sciences Commons, and the Engineering Commons
**Repository Citation**
[https://corescholar.libraries.wright.edu/cse/216](https://corescholar.libraries.wright.edu/cse/216)
This Conference Proceeding is brought to you for free and open access by Wright State University's CORE Scholar. It has been accepted for inclusion in Computer Science and Engineering Faculty Publications by an authorized administrator of CORE Scholar. For more information, please contact corescholar@www.libraries.wright.edu, library-corescholar@wright.edu.
Syntax Approximation by Using Nominal Schemas
Cong Wang, David Carral, and Pascal Hitzler
Kno.e.sis Center, Wright State University, Dayton, OH, U.S.A.
Abstract. Nominal schemas is a recently introduced extension of description logics which makes it possible to express rules which generalize DL-safe ones. A tractable description logic, $\mathcal{ELROV}_n$, has been identified. This leads us to the question: can we improve approximate reasoning results by employing nominal schemas? In this paper, we investigate how to approximately cast $\mathcal{SROIQ}$ into $\mathcal{ELROV}_n$. Using a datalog-based tractable algorithm, a preliminary evaluation shows that our approach can indeed do approximate $\mathcal{SROIQ}$-reasoning with a high recall.
1 Introduction
Reasoning with large or complex terminology is computationally difficult and is one of the bottlenecks for Semantic Web applications. Most reasoning tasks for ontologies underlying OWL [11] are intractable. Even with small ontologies, sound and complete reasoning is practically infeasible, in particular for applications where quick responses are critical.
This fundamental insight that expressive ontology reasoning is often necessarily of high computational complexity has triggered a line of research which aims at utilizing approximate algorithms, i.e. algorithms which are (provably) not sound and complete, but which nevertheless provide answers which are good enough for practical purposes [6,9,10,24]. This general idea of approximate reasoning is not new and to a certain extent had been studied already before the advent of the Semantic Web [4,25,26]. But the Semantic Web effort with its increased requirements for scalability has recently put this into a focus which this branch of reasoning research has never had before [7,8,12,20,21,22,23,27].
One of the prominent general approaches to approximate reasoning is known as language weakening. Language weakening refers to the idea of rewriting a knowledge base into a language which can be handled more efficiently. Obviously, if the target language has a lower complexity class, this rewriting in general cannot be done without a loss, resulting in an approximate reasoning procedure. In order to limit loss in the translation, it is of advantage if the target language be as expressive as possible while still being of low computational complexity, and hence languages which push expressivity while retaining tractability are natural choices for a language weakening approach.
In this paper, we use $\mathcal{ELROV}_n$ for approximate reasoning over $\mathcal{SROIQ}$ using language weakening. $\mathcal{ELROV}_n$ is essentially a tractable extension of $\mathcal{EL}^{++}$ [2],
$\mathcal{SROIQ}$ Syntax Approximation by Using Nominal Schemas
Cong Wang, David Carral, and Pascal Hitzler
Kno.e.sis Center, Wright State University, Dayton, OH, U.S.A.
Abstract. Nominal schemas is a recently introduced extension of description logics which makes it possible to express rules which generalize DL-safe ones. A tractable description logic, $\mathcal{ELROV}_n$, has been identified. This leads us to the question: can we improve approximate reasoning results by employing nominal schemas? In this paper, we investigate how to approximately cast $\mathcal{SROIQ}$ into $\mathcal{ELROV}_n$. Using a datalog-based tractable algorithm, a preliminary evaluation shows that our approach can indeed do approximate $\mathcal{SROIQ}$-reasoning with a high recall.
1 Introduction
Reasoning with large or complex terminology is computationally difficult and is one of the bottlenecks for Semantic Web applications. Most reasoning tasks for ontologies underlying OWL [11] are intractable. Even with small ontologies, sound and complete reasoning is practically infeasible, in particular for applications where quick responses are critical.
This fundamental insight that expressive ontology reasoning is often necessarily of high computational complexity has triggered a line of research which aims at utilizing approximate algorithms, i.e. algorithms which are (provably) not sound and complete, but which nevertheless provide answers which are good enough for practical purposes [6,9,10,24]. This general idea of approximate reasoning is not new and to a certain extent had been studied already before the advent of the Semantic Web [4,25,26]. But the Semantic Web effort with its increased requirements for scalability has recently put this into a focus which this branch of reasoning research has never had before [7,8,12,20,21,22,23,27].
One of the prominent general approaches to approximate reasoning is known as language weakening. Language weakening refers to the idea of rewriting a knowledge base into a language which can be handled more efficiently. Obviously, if the target language has a lower complexity class, this rewriting in general cannot be done without a loss, resulting in an approximate reasoning procedure. In order to limit loss in the translation, it is of advantage if the target language be as expressive as possible while still being of low computational complexity, and hence languages which push expressivity while retaining tractability are natural choices for a language weakening approach.
In this paper, we use $\mathcal{ELROV}_n$ for approximate reasoning over $\mathcal{SROIQ}$ using language weakening. $\mathcal{ELROV}_n$ is essentially a tractable extension of $\mathcal{EL}^{++}$ [2],
Table 1. Normal forms of $\mathcal{SROIQ}$ TBox axioms. $A$, $B$ and $C$ are atomic concept or negations of atomic concepts.
<table>
<thead>
<tr>
<th>Normal Form</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>$A \sqsubseteq \bot$</td>
<td>$C \sqsubseteq A$</td>
</tr>
<tr>
<td>$A \sqsubseteq C$</td>
<td>$A \sqcap B \sqsubseteq C$</td>
</tr>
<tr>
<td>$A \sqsubseteq B \cup C$</td>
<td>$\exists R.A \sqsubseteq C$</td>
</tr>
<tr>
<td>$A \sqsubseteq \exists R.C$</td>
<td>$\forall R.A \sqsubseteq C$</td>
</tr>
<tr>
<td>$A \sqsubseteq {a}$</td>
<td>${a} \sqsubseteq A$</td>
</tr>
<tr>
<td>$\geq n R.A \sqsubseteq C$</td>
<td>$\leq n R.A \sqsubseteq C$</td>
</tr>
<tr>
<td>$A \sqsubseteq n R.C$</td>
<td>$A \sqsubseteq \geq n R.C$</td>
</tr>
</tbody>
</table>
a.k.a. OWL 2 EL [18], by nominal schemas [17]. As such, $\mathcal{ELROV}_n$ incorporates DL-safe Datalog under Herbrand semantics [14]. We have recently described an efficient procedure to reasoning with $\mathcal{ELROV}_n$ [5] on which we base the evaluations in this paper.
The plan of this paper is as follows. In Section 2 we recall the languages $\mathcal{SROIQ}$ and $\mathcal{ELROV}_n$. In Section 3 we describe our approximate compilation of $\mathcal{SROIQ}$ into $\mathcal{ELROV}_n$. In Section 4 we recall our $\mathcal{ELROV}_n$ reasoning approach from [5]. In Section 5 we describe our implementation and evaluation results. In Section 6 we conclude.
2 Preliminaries
In this section, we introduce the description logics (DLs) $\mathcal{SROIQ}$ and $\mathcal{ELROV}_n$. The latter includes the new constructor from [17], nominal schemas, which we use to approximate some features of $\mathcal{SROIQ}$.
A signature $\Sigma = \langle \Sigma_I, \Sigma_C, \Sigma_R, \Sigma_S \rangle$ consists of mutually disjoint finite sets of atomic roles role names $\Sigma_R$, atomic concepts $\Sigma_C$, and individuals individual $\Sigma_I$, together with a distinguished subset $\Sigma_S \subseteq \Sigma_R$ of simple atomic roles. The set of roles (over $\Sigma$) is $R := \Sigma_R \cup \{R^{-} | R \in \Sigma_R\}$; the set of simple roles is $S := \Sigma_S \cup \{S^{-} | S \in \Sigma_S\}$. A role chain is an expression of the form $R_1 \cdot \ldots \cdot R_n$ with $n \geq 1$ and each $R_i \in R$. The function $\text{inv}(\cdot)$ is defined on roles by $\text{inv}(R) := R^{-}$ and $\text{inv}(R^{-}) := R$ where $R \in R$, and extended to role chains by $\text{inv}(R_1 \cdot \ldots \cdot R_n) := \text{inv}(R_n) \cdot \ldots \cdot \text{inv}(R_1)$.
The set $C$ of $\mathcal{SROIQ}$ concepts (over $\Sigma$) is defined recursively as follows:
$$C := \Sigma_C[\{\Sigma_I\}]C \sqcap C | C \sqcup C | \neg C | \exists R.C | \forall R.C | \geq n S.C | \leq n S.C | \exists S.Self$$
A TBox is a finite set of general concept inclusions (GCIs) of the form $C \sqsubseteq D$ where $C, D \in C$. A $\mathcal{SROIQ}$ TBox can be normalized such that it only contains the normal forms in Table 1 [1].
Satisfiability checking of $\mathcal{SROIQ}$ ontologies is in $\text{N2ExpTime}$ [13]. Given a disjunctive assertion $(C \sqcup D)(s)$, the tableau algorithm [13] nondeterministically guesses that either $C(s)$ or $D(s)$ holds, which can give rise to exponential behavior. Although the absorption technique and the hypertableaux approach [19] reduce the cost of this nondeterminism, it is still a considerable performance bottleneck.
\footnote{It was called $\mathcal{SROELV}_n$ in [17].}
**SROIQ** defines simple roles and role regularity to ensure decidability [13]. However, since we will later approximately cast **SROIQ** into **ELROV** \(_n\), which is free of these restrictions, we do not have to concern ourselves with them for the purposes of this paper. **ELROV** \(_n\) extends **EL**++ with nominal schemas (see [5,17] for details). To deal with the new constructor, we extend the signature to \(\Sigma = (\Sigma_I, \Sigma_C, \Sigma_R, \Sigma_V)\), where \(\Sigma_V\) is a set of variables. A nominal schema is a concept of the form \(\{x\}\) where \(x \in \Sigma_V\). Semantically, these variables can only bind to known individuals. The \(n\) in **ELROV**\(_n\) is a global bound on the number of different nominal schemas which can occur in any axiom in a knowledge base—this restriction guarantees tractability. The set of \(C\) of **ELROV**\(_n\) concepts is defined as follows:
\[
C := \Sigma_C | \{\Sigma_I\} | \{\Sigma_V\} | C \sqcap C | \exists R. C | \exists S. \text{Self}
\]
To give an example, consider the first-order rule
\[
R_1(x, y) \land R_2(y, z) \land R_3(x, z) \rightarrow R(x, z)
\]
which cannot be translated faithfully into **SROIQ**. By limiting the variable \(z\) in the sense that it can bind only to known individuals (such variables are called DL-safe [16]), we can express this rule in **ELROV**\(_n\) as
\[
\exists R_1. \exists R_2. \{z\} \sqcap \exists R_3. \{z\} \subseteq \exists R. \{z\}.
\]
If \(a_1, \ldots, a_k\) are all the known individuals in the knowledge base, then this axiom can also be expressed using the \(k\) **SROIQ**-axioms
\[
\exists R_1. \exists R_2. \{a_i\} \sqcap \exists R_3. \{a_i\} \subseteq \exists R. \{a_i\}
\]
where \(i\) ranges from 1 to \(k\). This kind of conversion, called full or naive grounding, of nominal schemas into classical description logics is, however, computationally infeasible [5] even for **ELROV**\(_n\), which is of \(\text{PTime}\) complexity [17]. In [5], we thus presented a datalog-based algorithm for **ELROV**\(_n\) which avoids full grounding, and have also shown experimentally that the algorithm is efficient.
3 Approximation
For our approximation of **SROIQ** by **ELROV**\(_n\), we use a number of different techniques, some of which are borrowed from existing literature. The key ideas are as follows.
- We rewrite mincardinality restrictions into maxcardinality restrictions or approximate using an existential.
- We rewrite universal quantification into existential quantification.
- We approximate maxcardinality restrictions using functionality.
- We approximate inverse roles and functionality using nominal schemas.
- We approximate negation using class disjointness.
We approximate disjunction using conjunction.
A pseudocode description is given in Algorithm 1, we explain the relevant parts in more detail below. Role chain axioms are left untouched, as are axioms which can already directly be expressed in $\mathcal{ELROV}_n$. We drop the soundness proof, since one can easily find out that our approach is sound but incomplete.
\section{Approximation of Inverse Role and Functionality}
Since $\mathcal{ELROV}_n$ can express DL-safe Datalog rules, all rule-like axioms in SROIQ can be approximated easily in $\mathcal{ELROV}_n$.
For role inclusion axioms of the form $R \sqsubseteq S^-$, the first-order logic rule is $R(x,y) \rightarrow S(y,x)$. By restricting the variables to nominals, we obtain $\text{nom}(x) \land \text{nom}(y) \land R(x,y) \rightarrow S(y,x)$, where $\text{nom}(x)$ is defined by the collection of facts
nom\( (a_i) \) for each individual \( a_i \). The latter rule can be expressed by means of the nominal schema axiom,
\[
\{x\} \cap \exists R. \{y\} \sqsubseteq \{y\} \cap \exists S. \{x\}
\]
where \( x \) and \( y \) are nominal schemas. This axiom will be later translated into datalog rule,
\[
nom(x), nom(y), triple(x, R, y) \rightarrow triple(y, S, x)
\]
where we can clearly see that the rule expresses the inverse role with restricting variable bounded to known individuals.
Similarly, for a functionality axiom \( C \sqsubseteq \leq 1 R. D \), we can cast it into
\[
C \cap \exists R. (\{z1\} \cap D) \sqsubseteq \exists U. (\{z1\} \cap \{z2\})
\]
where \( U \) is the universal role. This axiom will be translated into two datalog rules:
\[
\begin{align*}
nom(z1), nom(z2), inst(x, C), inst(x, D), triple(x, R, z1), triple(x, R, z2) & \rightarrow inst(z1, z2) \\
nom(z1), nom(z2), inst(x, C), inst(x, D), triple(x, R, z1), triple(x, R, z2) & \rightarrow inst(z2, z1)
\end{align*}
\]
Briefly, it means if there are two triples \( triple(x, R, z1) \) and \( triple(x, R, z2) \), then \( z1 \) and \( z2 \) must be same. (See details of translation in [5].)
Since \( A \sqsubseteq \forall R. C \) is the same as \( \exists R^{-}. A \sqsubseteq C \), we can approximate \( A \sqsubseteq \forall R. C \) by adding
\[
\exists inv(R). A \sqsubseteq C
\]
and
\[
\{x\} \cap \exists R. \{y\} \sqsubseteq \{y\} \cap \exists inv(R). \{x\}.
\]
Furthermore, for each axiom \( A \sqsubseteq \leq n R. C \), we reduce it to \( A \sqsubseteq 1 R. C \), such that it can be approximated through the nominal schema axiom
\[
A \cap \exists R. (\{x\} \cap C) \sqsubseteq \exists U. (\{x\} \cap \{y\}).
\]
3.2 Approximation of Negation and Disjunction
Our approach for approximating negation is derived from [23]. In brief, we add a fresh concept \( neg(C) \) for each concept \( C \) in KB, and add the axiom \( neg(C) \cap C \sqsubseteq \bot \) to express that the negation of \( C \) and \( C \) are disjoint. Furthermore, we rewrite the following axioms by using their De Morgan equivalent axioms and replace \( \neg C \) by the fresh concept \( neg(C) \).
\[
\begin{align*}
(1) & \quad A \sqsubseteq B \sqcup C \Rightarrow \neg B \sqcap \neg C \sqsubseteq \neg A \Rightarrow neg(C) \sqsubseteq neg(A) \\
(2) & \quad A \sqsubseteq \forall R. C \Rightarrow \exists R. \neg C \sqsubseteq \neg A \Rightarrow \exists R. neg(C) \sqsubseteq neg(A) \\
(3) & \quad \forall R. A \sqsubseteq C \Rightarrow \neg C \sqsubseteq \exists R. \neg A \Rightarrow neg(C) \sqsubseteq \exists R. neg(A) \\
(4) & \quad \leq n R. A \sqsubseteq C \Rightarrow \neg C \sqsubseteq n R. A \Rightarrow neg(C) \sqsubseteq n R. A \\
(5) & \quad \geq n R. A \sqsubseteq C \Rightarrow \neg C \sqsubseteq < n R. A \Rightarrow neg(C) \sqsubseteq < n R. A
\end{align*}
\]
Table 2. Evaluation ontologies for our algorithm
<table>
<thead>
<tr>
<th>Ontology</th>
<th>Classes</th>
<th>Annotation P.</th>
<th>Data P.</th>
<th>Object P.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rex(^3)</td>
<td>552</td>
<td>10</td>
<td>0</td>
<td>6</td>
</tr>
<tr>
<td>Spatial(^4)</td>
<td>106</td>
<td>13</td>
<td>0</td>
<td>13</td>
</tr>
<tr>
<td>Xenopus(^5)</td>
<td>710</td>
<td>19</td>
<td>0</td>
<td>5</td>
</tr>
</tbody>
</table>
Note that we can always reduce $C \sqsubseteq nR.A$ to $C \subseteq \exists R.A$. Then, for the last two axioms (4) and (5), we reduce them to $neg(C) \subseteq \exists R.A$ and $neg(C) \sqsubseteq 1R.A$. Following the ideas in \([12,27]\), for $A \subseteq B \cap C$, i.e., $A \subseteq B$ and $A \subseteq C$, falling into unsound but complete results. We will attempt to combine this idea with the approach in the paper. Briefly, combining unsound results and incomplete results to achieve higher precise and recall.
4 Reasoning over $\mathcal{ELROV}_n$
We briefly recall the algorithm for reasoning over $\mathcal{ELROV}_n$ presented in [5], and the evaluation results presented therein. The algorithm actually imposes some restrictions on $\mathcal{ELROV}_n$ which are described in detail in [5] and which cause no problem for our approximation approach.
The algorithm itself is based on results presented in [15]. Following this approach, for every $\mathcal{ELROV}_n$ knowledge base $KB$ we can construct a Datalog program $P_{KB}$ that can be used for reasoning over $KB$. The Datalog program $P_{KB}$ contains facts which are translated from all the DL normal forms (Figure 1) and rules (Figure 2). [5] contains a correctness proof.
The evaluation reported in [5] was performed using the Java-based Datalog reasoner IRIS\(^2\) [3], and we compared it to a full grounding approach for which we also used IRIS. We used suitable ontologies from the TONES repository, see Table 2 for some basic metrics, and artificially added named individuals and axioms using nominal schemas. Results are listed in Table 3. In our approach, the number of nominal schemas per axioms had almost no effect on the runtime, thus indicating that the approach performs very well indeed.
---
\(^{2}\) http://iris-reasoner.org/
\(^{3}\) http://obo.cvs.sourceforge.net/checkout/obo/obo/ontology/physicochemical/rex.obo
\(^{4}\) http://obo.cvs.sourceforge.net/checkout/obo/obo/ontology/anatomy/caro/spatial.obo
Table 3. Evaluation, IRIS reasoning time listed only (no pre-processing, no load time), in ms. The "No ns" column refers to the running with no nominal schemas, while k ns refers to the use of k nominal schemas in an axiom. Times in brackets are for full grounding, for comparison. If not listed, full grounding was OOM (Out of Memory)
<table>
<thead>
<tr>
<th>Ontology</th>
<th>number of individuals</th>
<th>no ns</th>
<th>1 ns</th>
<th>2 ns</th>
<th>3 ns</th>
<th>4 ns</th>
<th>5 ns</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rex</td>
<td>100</td>
<td>263</td>
<td>263 (321)</td>
<td>267 (972)</td>
<td>273</td>
<td>275</td>
<td>259</td>
</tr>
<tr>
<td></td>
<td>1000</td>
<td>480</td>
<td>518 (1753)</td>
<td>537 (OOM)</td>
<td>538</td>
<td>545</td>
<td>552</td>
</tr>
<tr>
<td></td>
<td>10000</td>
<td>2904</td>
<td>2901 (133179)</td>
<td>3120 (OOM)</td>
<td>3165</td>
<td>3192</td>
<td>3296</td>
</tr>
<tr>
<td>Spatial</td>
<td>100</td>
<td>22</td>
<td>191 (222)</td>
<td>201 (1163)</td>
<td>198</td>
<td>202</td>
<td>207</td>
</tr>
<tr>
<td></td>
<td>1000</td>
<td>134</td>
<td>417 (1392)</td>
<td>415 (OOM)</td>
<td>421</td>
<td>431</td>
<td>432</td>
</tr>
<tr>
<td></td>
<td>10000</td>
<td>1322</td>
<td>1792 (96437)</td>
<td>1817 (OOM)</td>
<td>1915</td>
<td>1888</td>
<td>1997</td>
</tr>
<tr>
<td>Xenopus</td>
<td>100</td>
<td>62</td>
<td>332 (383)</td>
<td>284 (1629)</td>
<td>311</td>
<td>288</td>
<td>280</td>
</tr>
<tr>
<td></td>
<td>1000</td>
<td>193</td>
<td>538 (4751)</td>
<td>440 (OOM)</td>
<td>430</td>
<td>456</td>
<td>475</td>
</tr>
<tr>
<td></td>
<td>10000</td>
<td>1771</td>
<td>2119 (319013)</td>
<td>1843 (OOM)</td>
<td>1886</td>
<td>2038</td>
<td>2102</td>
</tr>
</tbody>
</table>
5 Implementation and Evaluation
We realized the implementation based on the ELROVₙ, datalog-based reasoner [5]. All experiments were conducted on a laptop with a 2.4GHz Intel CoreTM i7-3630QM processor and 8GB RAM operated by Windows 7 64-bit system with Java VM v.1.7.0. We set time out of 1 hour and Java heap space of 1GB. The ontologies were chose from Oxford Ontologies Repository ⁶, in Table Table 4. To evaluate the performance in practice, we also compared with mainstream reasoners Pellet 2.3.0⁷, FaCT++ 1.6.2⁸ and HermiT 1.3.7⁹. The reasoning task is classification, therefore recall equals the number of subsumption relations between concepts divides its correct number. Since our approach needs some individual to fire the datalog rules, we add one unique dummy individual for each concepts if the testing ontology does not contain individuals. Therefore, we can check subsumption relations by tracking those dummy individuals.
The experiment, Table 5 , shows our approach has good recalls but fails when conducting very large ontologies. The reason is that IRIS reasoner has a difficulty to run with large number of rules or facts. However, with a quicker datalog reasoner or a more efficient reasoner that supports nominal schemas, we believe it will achieve a better result. Also, since the number of rules (Figure 2) are fixed, we do not need a full powerful Datalog reasoner. We can specifically program the rules to improve the efficiency.
To be noticed, the approximation in this paper can be done by HermiT reasoner since HermiT can handle DL-safe rules and the rules can directly be
⁶ http://www.cs.ox.ac.uk/isg/ontologies/
⁷ http://clarkparsia.com/pellet/
⁸ http://owl.man.ac.uk/factplusplus/
⁹ http://www.hermit-reasoner.com/
\begin{align*}
C(a) & \mapsto \{\text{subClass}(a, D)\} & R(a, b) & \mapsto \{\text{subEx}(a, R, b, b)\} \\
\top \sqsubseteq C & \mapsto \{\text{top}(C)\} & A \sqsubseteq \bot & \mapsto \{\text{bot}(A)\} \\
\{a\} \sqsubseteq C & \mapsto \{\text{subClass}(a, C)\} & A \sqsubseteq \{c\} & \mapsto \{\text{subClass}(A, c)\} \\
A \sqsubseteq C & \mapsto \{\text{subclass}(A, C)\} & A \cap B \sqsubseteq C & \mapsto \{\text{subConj}(A, B, C)\} \\
\exists R. \text{Self} \sqsubseteq C & \mapsto \{\text{subSelf}(R, C)\} & A \sqsubseteq \exists R. \text{Self} & \mapsto \{\text{supSelf}(A, R)\} \\
\exists R.A \sqsubseteq C & \mapsto \{\text{subEx}(R, A, C)\} & A \sqsubseteq \exists R.C & \mapsto \{\text{supEx}(A, R, B, \text{aux}, A \sqsubseteq \exists R.C)\} \\
R \sqsubseteq C \times D & \mapsto \{\text{supProd}(R, C, D)\}
\end{align*}
Fig. 1. Input Translation \(I_V\)
\begin{table}[h]
\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|}
\hline
No. & Ontology & expressivity & Classes & Object Properties & Individuals & TBox & RBox & ABox \\
\hline
00004 & BAMS & SHIF & 1110 & 12 & 0 & 1813 & 9 & 0 \\
00015 & DOLCE & SHI & 37 & 70 & 0 & 279 & 76 & 0 \\
00039 & GALEN & ALEHIF\(^+\) & 3097 & 403 & 0 & 14664 & 111 & 0 \\
00040 & GO & SRIQ & 58882 & 220 & 0 & 130376 & 104 & 0 \\
00103 & Gardiner & ALEO & 176 & 10 & 187 & 263 & 0 & 187 \\
00387 & OBO & SRLF & 27412 & 215 & 34 & 55998 & 87 & 157897 \\
\hline
\end{tabular}
\caption{Evaluation ontologies for our algorithm, the No. denotes the number order of Oxford Repository. Since the implementation does not support datatype property, any ontologies containing datatype properties are not chosen here.}
\end{table}
added to the input ontology in functional style. But, HermiT doesn’t have specific reasoning procedure for \(\mathcal{EL}\)-families, such that reasoning for \(\mathcal{EL}\) is not its advantage. Moreover, there are \(\mathcal{ELROV}_n\)axioms which cannot be expressed as \(DL\)-\textit{safe} rules, e.g., \(\exists R.\{z\} \sqsubseteq \exists T.\exists S.\{z\}\). Moreover,
\section{Conclusions and Future Work}
We have described an approximate reasoning procedure for \(SROIQ\) which utilizes the tractable nominal-schemas-based \(\mathcal{ELROV}_n\) using a language weakening approach. We have also provided an experimental evaluation which shows the feasibility of this setting.
Going forward, there are several directions which we intend to explore. On the one hand, we will be looking into variants on how to obtain the weakened language, in the spirit of [27], and will attempt to further tweak and optimize our approach. On the one hand, we will be looking into incremental methods
\[
\begin{align*}
\text{nom}(x) & \mapsto \text{inst}(x, x) \\
\text{nom}(x) \land \text{triple}(x, v, x) & \mapsto \text{self}(x, v) \\
\text{top}(z) \land \text{inst}(x, z') & \mapsto \text{inst}(x, z) \\
\text{bot}(z) \land \text{inst}(u, z) \land \text{inst}(x, z') \land \text{cls}(y) & \mapsto \text{inst}(x, y) \\
\text{subClass}(y, z) \land \text{inst}(x, y) & \mapsto \text{inst}(x, z) \\
\text{subConj}(y_1, y_2, z) \land \text{inst}(x, y_1) \land \text{inst}(x, y_2) & \mapsto \text{inst}(x, z) \\
\text{subEx}(v, y, z) \land \text{triple}(x, v, x') \land \text{inst}(x', y) & \mapsto \text{inst}(x, z) \\
\text{subEx}(v, y, z) \land \text{self}(x, v) \land \text{inst}(x, y) & \mapsto \text{inst}(x, z) \\
\text{supEx}(y, v, z) \land \text{inst}(x, y) & \mapsto \text{triple}(x, v, x') \\
\text{supEx}(y, v, z) \land \text{inst}(x, y) & \mapsto \text{inst}(x', z) \\
\text{subSelf}(v, z) \land \text{self}(x, v) & \mapsto \text{inst}(x, z) \\
\text{supSelf}(y, v) \land \text{inst}(x, y) & \mapsto \text{self}(x, v) \\
\text{subRole}(v, w) \land \text{triple}(x, v, x') & \mapsto \text{triple}(x, w, x') \\
\text{subRole}(v, w) \land \text{self}(x, v) & \mapsto \text{self}(x, w) \\
\text{supProd}(v, z_1, z_2) \land \text{triple}(x, v, x') & \mapsto \text{inst}(x, z_1) \\
\text{supProd}(v, z_1, z_2) \land \text{self}(x, v) & \mapsto \text{inst}(x, z_1) \\
\text{supProd}(v, z_1, z_2) \land \text{triple}(x, v, x') & \mapsto \text{inst}(x', z_2) \\
\text{supProd}(v, z_1, z_2) \land \text{self}(x, v) & \mapsto \text{inst}(x, z_2) \\
\text{inst}(x, y) \land \text{nom}(y) \land \text{inst}(x, z) & \mapsto \text{inst}(y, z) \\
\text{inst}(x, y) \land \text{nom}(y) \land \text{inst}(y, z) & \mapsto \text{inst}(x, z) \\
\text{inst}(x, y) \land \text{nom}(y) \land \text{triple}(z, u, x) & \mapsto \text{triple}(z, u, y) \\
\text{inst}(x, y) & \mapsto \text{triple}(x, y, x)
\end{align*}
\]
Fig. 2. Deduction Rules $P_V$
Table 5. Evaluation, reasoning time of each reasoner, in ms. N/A denotes that the datalog-based reasoner corrupts with too many loading rules.
<table>
<thead>
<tr>
<th>Ontology</th>
<th>HermiT</th>
<th>Fact++</th>
<th>Pellet</th>
<th>Ours</th>
<th>Recall</th>
</tr>
</thead>
<tbody>
<tr>
<td>BAMS</td>
<td>3</td>
<td>2</td>
<td>10</td>
<td>107</td>
<td>100%</td>
</tr>
<tr>
<td>DOLCE</td>
<td>1</td>
<td>1</td>
<td>4</td>
<td>53</td>
<td>100%</td>
</tr>
<tr>
<td>GALEN</td>
<td>4</td>
<td>2</td>
<td>17</td>
<td>7840</td>
<td>90.8%</td>
</tr>
<tr>
<td>GO</td>
<td>36</td>
<td>75</td>
<td>59</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<td>GardinerCorpus</td>
<td>14</td>
<td>6</td>
<td>17</td>
<td>89</td>
<td>92.3%</td>
</tr>
<tr>
<td>OBO</td>
<td>34</td>
<td>61</td>
<td>139</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</tbody>
</table>
which use the approximate reasoning results as starting point and subsequently compute correct results in all or at least most cases.
Acknowledgements This work was supported by the National Science Foundation under award 1017225 III: Small: TROn – Tractable Reasoning with Ontologies.
References
|
{"Source-Url": "https://corescholar.libraries.wright.edu/cgi/viewcontent.cgi?article=1215&context=cse", "len_cl100k_base": 8424, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 45775, "total-output-tokens": 11467, "length": "2e13", "weborganizer": {"__label__adult": 0.0004949569702148438, "__label__art_design": 0.0007405281066894531, "__label__crime_law": 0.00077056884765625, "__label__education_jobs": 0.00229644775390625, "__label__entertainment": 0.0002455711364746094, "__label__fashion_beauty": 0.0003261566162109375, "__label__finance_business": 0.0006403923034667969, "__label__food_dining": 0.0007014274597167969, "__label__games": 0.0010738372802734375, "__label__hardware": 0.0008745193481445312, "__label__health": 0.0014925003051757812, "__label__history": 0.0005359649658203125, "__label__home_hobbies": 0.00021541118621826172, "__label__industrial": 0.0008535385131835938, "__label__literature": 0.0020236968994140625, "__label__politics": 0.0006256103515625, "__label__religion": 0.0009250640869140624, "__label__science_tech": 0.3955078125, "__label__social_life": 0.0002644062042236328, "__label__software": 0.01471710205078125, "__label__software_dev": 0.5732421875, "__label__sports_fitness": 0.00037169456481933594, "__label__transportation": 0.0008549690246582031, "__label__travel": 0.0002409219741821289}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33766, 0.04156]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33766, 0.27455]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33766, 0.7396]], "google_gemma-3-12b-it_contains_pii": [[0, 961, false], [961, 6418, null], [6418, 9681, null], [9681, 12386, null], [12386, 13255, null], [13255, 16086, null], [16086, 18592, null], [18592, 21824, null], [21824, 24490, null], [24490, 26425, null], [26425, 29037, null], [29037, 32205, null], [32205, 33766, null]], "google_gemma-3-12b-it_is_public_document": [[0, 961, true], [961, 6418, null], [6418, 9681, null], [9681, 12386, null], [12386, 13255, null], [13255, 16086, null], [16086, 18592, null], [18592, 21824, null], [21824, 24490, null], [24490, 26425, null], [26425, 29037, null], [29037, 32205, null], [32205, 33766, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33766, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33766, null]], "pdf_page_numbers": [[0, 961, 1], [961, 6418, 2], [6418, 9681, 3], [9681, 12386, 4], [12386, 13255, 5], [13255, 16086, 6], [16086, 18592, 7], [18592, 21824, 8], [21824, 24490, 9], [24490, 26425, 10], [26425, 29037, 11], [29037, 32205, 12], [32205, 33766, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33766, 0.12941]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
8b618ee1116f7bcda925dc89d2cc8d01ab75ae05
|
Mutational Fuzzing to Discover Software Bugs and Vulnerabilities
Dylan Wolff
Advised by Robert Signorile
2015 Senior Honors Thesis
Boston College Computer Science Department
Abstract:
Recent major vulnerabilities such as the Heartbleed bug have emphasized the importance of properly testing software. For both product testers and hackers, fuzzing has emerged as an important tool used to find these issues. This thesis investigates one branch of the field, mutational fuzzing, in which valid inputs are randomly altered to produce sample files. While the samples produced by this approach are not as efficient as the hand-crafted inputs used in generational fuzzing, a mutational fuzzer can easily be used on multiple applications with no prior knowledge of the input formats and only a small amount of setup. The fuzzer created for this thesis, written in Python, is a multiprocessing, distributed generic file fuzzer, and was used to test the popular media player VLC for bugs.
## Contents:
1. **Introduction**
2. **Fuzzer Structure**
3. **Fuzzing VLC**
### 1. Introduction
1.1 What is Fuzzing?
1.2 Why Fuzzing?
### 2. Fuzzer Structure
2.1 Virtual Machine and Environment
2.2 FuzzServer.py and FuzzClient.py
2.4 Fuzzer.py
2.5 Mutator.py
2.6 Executor.py
2.7 reMutate.py
### 3. Fuzzing VLC
3.1 Why VLC?
3.2 Crash Results
3.3 Optimizing Fuzzing Parameters for Future Fuzzing Runs
3.3.1 Mutation Percentage
3.3.2 Number of Iterations and Seed Selection
3.3.3 Timeout
3.3.4 Number of Executor Processes
4 Conclusions and Future Work
5 References
Appendix A: Comparison of Mutator function Performance
Appendix B: Source Code
1 Introduction
As technology becomes increasingly involved with our daily lives, breaches in the security of devices and applications that we rely on can have devastating implications. In recent months, serious vulnerabilities with seriously catchy names like “Shellshock” and “Heartbleed” have made headlines. These were important discoveries to be sure, but they are just two of countless important vulnerabilities in software that have been uncovered (and countless more that haven’t yet been found). The purpose of this thesis is to examine one branch of computer security, fuzzing, and how it is used by both security experts and attackers to test real world programs for these issues.
1.1 What is Fuzzing?
Fuzz testing is the process of feeding random, unexpected, or invalid data to a program’s inputs. This process is usually automated, with a debugger attached to the target program. If the program does crash, information about the state of the machine is logged by the debugger so that a programmer can later identify the faulty code that led to the crash. Fuzzing automates the process of vulnerability and crash discovery. This allows for a massive increase in the volume of tests that can be run compared to what a human could do, while also potentially catching subtle bugs that a human code auditor might miss when looking at lengthy and complex source code [15].
Unfortunately, fuzzing an entire input space is generally intractable.
Consider an image that is 47.4KB large. For each byte, there are 256 possible values so the input space for an image viewer accepting only images of this exact size is: $256^{47400}$. This would take a computer running at 4GHz doing one possible iteration of this input space every cycle $10^{737}$ times the current age of the universe to finish. Thus the differences in types of fuzzers arise in how test cases are chosen from the vast input space of a program.
<table>
<thead>
<tr>
<th>Advantages</th>
<th>Random</th>
<th>Mutational</th>
<th>Model Based</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>-Simple</td>
<td>-Relatively simple</td>
<td>-Potentially efficient</td>
</tr>
<tr>
<td></td>
<td>-Quick</td>
<td>-Reusable across different software</td>
<td>(if the target is well modeled)</td>
</tr>
<tr>
<td></td>
<td>-Low Cost</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Disadvantages</th>
<th>Random</th>
<th>Mutational</th>
<th>Model Based</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>-Pretty much useless if inputs are checked</td>
<td>-Needs numerous valid inputs to get good coverage</td>
<td>-Time-consuming to set up</td>
</tr>
<tr>
<td></td>
<td>-Poor coverage</td>
<td></td>
<td>-Requires knowledge of the input format and protocol</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>-Reusable only with the same format</td>
</tr>
</tbody>
</table>
Overview of different fuzzing strategies [7]
The two primary categories of fuzzers are mutational and generational. Random fuzzers can also be useful in a narrow set of applications, but most real-world software has some kind of input checking mechanism that makes productive random fuzzing impossible. Mutational fuzzing takes seed files that are valid inputs to a program and “mutates” random bits of data in these files to other values. These mutated files are then executed under the target program. Generational fuzzing relies on a deeper understanding of the application to create input files designed to test specific aspects of a program. Instead of
randomly testing mutant files in the input space, using knowledge of the program and the structure of it’s inputs, generational fuzzing aims to only tests minimum and maximum values within test cases (e.g. for a piece of code like: “if 3 <= x <=10:”, the edge cases 3 and 10 are worth testing, as well as 2 and 11, but other values for x won’t change the control flow of the program and are thus unlikely to produce any errors that these four values do not). Unfortunately, code branching is still generally exponential with code length, so it is still unlikely that a significant portion of edge cases could be tested for all branches within a given program [9].
1.2 Why fuzzing?
Most of us know enough not to download or open anything with weird file extensions, but vulnerabilities in applications can be exploited even by seemingly innocuous files like .wav, .doc, etc., the worst of which can even be used by an attacker to achieve arbitrary code execution on a machine. Fuzzing has uncovered such vulnerabilities in a wide variety of applications. Charlie Miller, one of the premier experts in fuzzing, was the first one to hack the iPhone [10]. He did so by exploiting a vulnerability he found while fuzzing. Other fuzzers have uncovered vulnerabilities in targets ranging from the Debian operating system to the image viewer ImageMagick [9]. Fuzzing has become so prominent that even “Verizon now requires that its vendors do their own fuzz testing before submitting equipment into the Verizon testing lab” [2].
Initially, for this project, I looked at two separate fuzzers that were free online. The first was the Basic Fuzzing Framework (BFF), the second Peach Fuzzer. In both cases I found the fuzzers to be incredibly complex and poorly documented. While they are both quality products, the sheer number of features in each is totally overwhelming. After far too much time spent wading through other people’s code (ironically the exact kind of brutal legwork fuzzing itself aims to avoid) and the few tutorials I could find online, it became apparent that learning one of these prebuilt frameworks was a project in of itself, and certainly not one worth dedicating a serious amount of my thesis to. Instead, I have written my own fuzzer, with the intention of it being both effective and user friendly.
2 Fuzzer Structure
2.1 Environment and Structural Overview
The entire fuzzer is built in a virtual machine for Virtual Box running a 64 bit copy of Windows 7 Enterprise. This ensures that the host machine is unaffected by any adverse consequences of executing so many potentially damaging files during the fuzzing run. It also has the added benefit of making installing the fuzzer on multiple computers for a distributed run extremely simple. After installing Virtual Box and importing the WolffFuzz appliance on the new computer, the fuzzer is already fully operational. In order to maximize
the amount of a program’s input space that can be fuzzed in a given amount of time, the fuzzer is both distributed and multiprocessing, but for distributed fuzzing runs to work, port forwarding must be activated in the network settings of the server virtual machine (using the guest and host ip’s respectively and the appropriate port number).
*Overview of fuzzer structure. Depicted with two clients and four Executor processes per client.*
2.2 FuzzServer.py and FuzzClient.py
When run on the server machine, FuzzServer.py first reads in the parameters for the fuzzing run from the config file, FuzzerConfig.txt, on the desktop. It then waits for client connections on a pre-selected port (12000 is the default). Upon connection to a client, it sends across the fuzzing parameters, followed by a portion of the sample files that are located in the servSamples folder on the desktop. Once all of the sample files have been distributed equally to each of the clients, the server waits once again on the selected port for client connections that signal that each client fuzzer has completed the run. From these connections, the server collects and consolidates the crashes of all clients into the ServCrashers folder on the desktop, and performs some cursory automated analysis to give the user the number of crashes considered exploitable, the number of unique crashes, and the total number of crashes.
When run, FuzzClient.py immediately attempts to connect with the server at a port number and IP address specified in FuzzerConfig.txt on the desktop of its virtual machine. Upon connection, it parses the fuzzing parameters from the server, and writes the sample files it receives to the Samples folder on the desktop. Finally, it begins a new Fuzzer process before terminating.
2.3 Fuzzer.py
Fuzzer.py can be run manually by a user to proceed with a non-distributed fuzzing run. If this is the case, the fuzzing parameters are read in from the local
FuzzerConfig.txt file. Otherwise, the parameters are passed in as arguments when the Fuzzer process is created by a FuzzClient process as part of a distributed run. The Fuzzer process creates one Mutator process and the number of Executor processes specified by the fuzzing parameters. It passes to each child process a process/thread safe Queue to convey mutated file names from the Mutator to the Executor processes as well as a similarly synchronized Queue for the names of old mutated files that need to be removed. The Fuzzer process then sits in a loop checking if any of the Executors have died. If this is the case, the Fuzzer launches a new Executor process. The Fuzzer also checks the Queue for the string “STOP”. If “STOP”, the poison pill, is found, the Fuzzer waits until all Executors are finished with their current files before sending the contents of the Crashers folder to the server. If the fuzzing run is not distributed, the Fuzzer process calculates and prints the number of exploitable crashes, unique crashes, and total crashes before terminating.
2.4 Mutator.py
The Mutator process takes each seed file and mutates it the amount given by the mutation percentage parameter a certain number of times. This number is dictated by the iterations parameter in the FuzzerConfig.txt file. The Mutator first sorts the seed files by size, so that smaller files that are mutated faster can be made available more quickly for the initial executions of the target program. Each file is read into a string, which is then converted to a list. For each iteration of each file, the Mutator gets a random seed value. It then calculates a
randomized write location between beginning and the end of the file and writes a byte value between 0 and 255 to that location in the list. These random writes to the list are performed a number of times equal to the file length in bytes multiplied by the mutation percentage. Once the writes are completed, the list is then converted back to a string, and written to a new file with a new name in the Mutated folder on the desktop. The mutated file’s name, sample file name, and mutation seed are all then placed on the queue.
The mutation process described above is relatively memory intensive, as it carries the entire file in memory as a list. Another function, mutate2, was thus developed as an alternative that uses significantly less memory. mutate2 uses shutil.copy2() to copy the seed file to the mutated folder with a new name, and then the file.seek() function to write random bytes to random addresses in the new copied file. Unfortunately mutate2 is much slower than the first mutation function, so it is only called if the size of the file being mutated is such that it could potentially cause a memory error or does cause a memory error.
Whichever mutate function is chosen mutates all iterations of a given sample file before moving on to the next. At each iteration, the mutator logs its progress in a file such that it can be resumed if it were to crash. This process is repeated until all sample files have been mutated with the proper number of iterations. If the Mutated folder on the desktop exceeds 5 gigabytes, however, the Mutator process stalls to allow the executor processes to clear out the mutated files. This prevents the virtual machine from running out of its limited 25GB hard drive space. While stalling, the Mutator process checks a queue of names of already executed mutated files that Executor processes failed to delete and
attempts to delete them. Once finished, the Mutator puts a “STOP” string on the queue as a poison pill for all other processes, and terminates.
2.5 Executor.py
The Executor process upon first launch gets a new filename off of the queue. If it finds “STOP” on the queue, it replaces it, writes “STOP” to its log file and terminates. If it gets a filename for a mutated file, it logs that it is entering execution of a file and executes that file under the target program with WinAppDbg attached. It then waits for a timeout in seconds, passed in as a parameter upon launch. If a crash is found, a callback function, my_event_handler(), creates a new folder for the crash, in which it puts the seed for the random mutations that caused the crash, the name of the sample file that caused the crash, and the output of the debugger in text files. After a timeout, the Executor kills the target program and logs that it has finished executing. It then attempts to remove the mutated file just executed. If it fails to do so because the target program hasn’t fully died yet, that file is put on a queue to be removed later. Finally, the Executor checks memory usage. If the memory usage of the computer exceeds 90% and the Executor process has been alive long enough to have executed at least two files, the process will self terminate. This is because certain programs (VLC included) cannot be terminated by any of the according WinAppDbg functions, nor Process_Terminate. These processes hang around, taking up memory, until the parent process is terminated. To prevent an accumulation of such processes to the point of a memory fault, the Executors
must be culled if usage gets too high. Not killing Executors that have just begun is enough to ensure that the amount of memory saved by a kill is worth the overhead of restarting an Executor process.
2.6 reMutate.py
reMutate.py is used for post-processing. Specifically to use the crashsrc.txt files in each crash folder and the sample file to re-create a mutated file. It reads the specifications (seed, mutation percentage and sample file name) from a crashsrc.txt file dragged to the reMutate folder on the desktop. Using the name of the sample file, it finds the original sample in the Samples folder on the desktop. It then recreates the mutations of the mutator using the seed and mutation percentage, and creates a new file in the Mutated folder on the desktop.
Emphasis was placed in all parts of the fuzzer on being able to recover from a crash that is severe enough to bring down the fuzzer itself (or just if it needed to be paused or interrupted for any reason). This is accomplished by both the Executor and Mutator processes logging progress throughout the fuzzing run. When Fuzzer.py is run by a user, it prompts the user if a run needs to be resumed. If this option is selected, the Queues are read from serialized backup files and the Mutator and Executor processes read from their respective log files to pick up exactly from where they left off.
3 Fuzzing VLC
3.1 Why VLC?
VLC is listed as having been downloaded 60 million times on download.com, yet just last year, a vulnerability was discovered that allowed an attacker to gain arbitrary code execution on a machine by a user opening a malicious .asf file with the application [4]. With that many people using VLC, chances are, as an attacker, if you post a well disguised, harmful media file on the internet, a large percentage of the people who download it will have VLC. In general, there are also only a few programs that the average Joe Computerowner uses on a regular basis: web browsers, media players, email readers, document readers etc. [15]. Attacking programs like these not only has a high probability of the user having the application, but also of them using it. Even if you are smart enough to avoid downloading malicious content, VLC and other media players install plugins for popular web browsers (Firefox, Chrome, Internet Explorer, Safari etc.), harmful media files embedded in websites can be played without your explicit consent [15]. Furthermore, these programs are not only usually perceived as safe by their users, but often by the software engineers who write the applications themselves; the programmers for these type of applications who are not generally as focused on security as engineers working on something where it is more obviously important, like a financial transaction over the web.
And VLC and other media players are extremely complex, dealing with many different file formats on many different platforms. This complexity makes it easier for programmers to make mistakes, and for those mistakes to go unnoticed. All of these factors combine to make VLC an enticing target for malicious hackers, and an important one for those concerned with cybersecurity. It is for these reasons that VLC was chosen as the target of the fuzzer created for this thesis.
### 3.2 Crashes from VLC
For the large scale test run of the fuzzer created for this thesis the parameters were the following:
- **Mutation Percentage**: 0.01
- **Iterations per Sample File**: 120
- **Number of Executing Threads per Client**: 4
- **Number of Client Machines**: 4
The 77 sample files for the run were downloaded from [http://samples.mplayerhq.hu/](http://samples.mplayerhq.hu/). This is the same body of sample files that a security team at Google used to fuzz media libraries (some of which are also used by VLC) [9]. The version of VLC used for this run (and all other runs) was VLC media player 2.1.2 [15].
The run resulted in 253 crashes total, 25 of which are classified as exploitable by the debugger. From those crashes, there were 35 unique addresses at which faults occurred. Only 9 of the seed files caused crashes when mutated.
Another file seed file was separately found to cause crashes without any mutations prior to the initial fuzzing run, leaving 10 unique seed files and 36 unique crashes. Of 36 unique crashers, VLC crashed in 5 different dll’s and 7 different functions: libavcodec_plugin (start), libsimple_channel_mixer_plugin (start), libvlccore (es_format_InitFromVideo, picture_Release, picture_Hold, picture_pool_Get, vout_ReleasePicture ), libdtstofloat32_plugin (start), libfaad_plugin (start). Other faults occurred in ntdll (RtlFreeHeap, RtlUnhandledExceptionFilter) and msvcrt (memcpy), but a backtrace using GDB did not reveal what function or library in VLC caused the initial problem. Of the dll’s, it appears that at least two of them, libfaad_plugin and libavcodec_plugin are used in other applications. The former is advertised on several websites for download as an open source AAC decoder while the latter has its own Wikipedia page, where it is listed as a component in 57 other applications [1, 8]!
While it is left for future investigation to determine the causes of these crashes or their true exploitability, there is one bug that seems particularly dangerous. Specifically all the errors occurring with mutations of the issue1930.h264 file. The file produces the most unique instruction pointers upon crashing, but that instruction pointer is generally off in unallocated space. The other instruction pointer locations of crashes for mutations of this seed file are in the memcpy function, which notably does not check bounds on the target memory buffer. It seems likely that all of these “unique” crashes are really just the product of one error in which memcpy is sometimes overflowing a buffer and affecting a jump or return address. If this were found to be the case, the error would be highly exploitable.
3.3 Optimizing Fuzzing Parameters
There are four parameters in FuzzerConfig.txt that have an extremely large impact on the efficacy of the run: Mutation Percentage, Number of Iterations per File, Timeout, and number of Executor processes. Using data gathered from the large scale fuzzing run of VLC for this fuzzer and prior research on this topic, we attempted to approximate optimal fuzzing parameters for future fuzzing runs.
3.3.1 Mutation Percentage
Fuzzing files has to walk the line between being structured enough to bypass input checks and other defenses that allow a given program to exit gracefully while also being invalid enough to cause crashes. There is virtually no previous research on this parameter, so, to test various mutation percentages, I took 7 different crash-inducing files (one crash causing mutation of each of the seed files that caused at least one crash). These files were then used as sample files for runs with varying mutation percentages. If the file became too mangled by the second round of mutations, then it would not pass the input checks that VLC performs and thus would not crash. Otherwise, the program should crash as it did before the mutation. The probability of undoing the mutation(s) from the first round and making the file non-buggy is extremely slim, so a file not crashing indicates with a relatively high probability that it was mutated to
severely the second round (as it passed all input checks in the first round).
The graph of Hits vs. Fuzz Percentage above indicates that as the mutation percentage increases, the number of known crashers that pass crash (and thus pass input checks) declines. However, that decline is not particularly steep, and appears even to flatten out as the mutation percentage approaches 20%. Even as we are fuzzing less files, the average percentage of mutated bytes in files being executed and passing input checks is increasing approximately linearly with the fuzz factor as can be seen in the graph below.
More of these mutated bytes getting into executed files means that there is an increased chance that one of those bytes causes a crash, thus it would seem that a higher mutation percentage is better. However, an increase in mutation percentage has an impact on the execution time as well. It slows down the mutation process to the point that the Mutator process, rather than the Executor processes becomes the limiting factor in speed. Thus Hits/Second vs. Mutation Percentage graph below incorporates total execution time, finding the per second percentage of executed bytes. There are two peaks, at 10 and 15 percent, with a steep drop off after 15%. Thus the optimal fuzz factor for this setup is
3.3.2 Number of Iterations per Sample File
The number of iterations may seem at first to be a relatively simple parameter to set. In order to fuzz as many files as possible, the number of iterations should be set as high as possible such that the fuzzing run can be completed in the time available. However, the number of files fuzzed is a combination of two factors: the number of iterations and the number of initial seed files. This begs the question, if we only have a set amount of time and thus can only make a certain number of mutant files, which should we prioritize, the number of seed files or the number of iterations? There has been substantial...
research done on seed selection for mutational fuzzing that helps to develop an answer.
The general consensus is that finding a minimum set of seed files that have the maximum code coverage is the optimal way to select seed files. Most notably, *Optimizing Seed Selection*, makes two strong conclusions to this effect: First that such a set “performed best” out of six methods for seed selection and that “Fuzzing with a reduced set is more efficient in practice” than an equivalent number of files from the full set [11]. Thus code coverage of the fuzzed files is an important metric when fuzzing. Miller reports an 1% increase in code coverage increases the percentage of bugs found by 0.92% [11]. So, when constructing a test set of a constant magnitude equal to the the product of the number of iterations and the number of seed files, we want to maximize code coverage. If we select our seed files with this in mind, with each additional seed file we are increasing code coverage. Each iteration, however, is highly likely to have the exact same code coverage as the seed file which it is mutating. Thus, given the choice, more seed files with different code coverage are preferable to more iterations. If we cannot find seed files with new code coverage however, extra iterations of the seed files is probably equally valuable and doesn’t require gathering any more files. Thus the answer to the question of how many seed files should be chosen relative to the number of iterations of mutations performed on each seed file is that maximizing the number of different (in terms of code coverage) seed files is the priority. Once code coverage has been maximized, each seed file should be iterated as many times as is possible given the allotted time for the run.
3.3.3 Timeout
The timeout parameter sets how long the Executor process will wait before killing an executing target process. There is virtually no previous research done on this setting because it is unique to the target application and environment for the fuzzing run; the slower the computer or the larger the application, the longer it takes for each execution, and thus the longer the timeout must be to accommodate the extra startup time. Furthermore, the type of files affects the amount of time to execute the entire file. Media files can range from seconds to hours long. This makes it difficult to determine a firm timeout for applications that run these files. A subset of unique crash inducing files gathered from the initial large test run on VLC were tested with a mutation percentage of zero and varying timeouts to determine the optimal timeout for a fuzzing run on VLC. The tests were run on an iMac11,2 host (3.06 GHz Intel Core i3 Dual Core Processor, with 4GB of 1333MHz Ram), and the virtual machine was set to 4 cores and 2GB of RAM. The graph plots crash rate (crashes/total files) divided by the total time to execute the entire run against the timeout setting.
The graph above suggests that the 45 second timeout used in the initial test run was not optimal for finding crashes, but rather a timeout closer to 9.25s. Because files are being randomly mutated, they are generally equally perturbed at the beginning and at the end of the file. Thus if a given amount of perturbation has a probability $p$ of causing a crash for a given block of the file, then the block executed first has approximately a probability of $p$ to cause a crash. For the next block to cause a crash, the first block must not crashed, which gives a probability of roughly $(1-p)*p$. The probability of the next block causing a crash is $(1-p)*(1-p)*p$. And so on. Thus, we are far less likely to see crashes later in the execution when compared to the beginning. For media files, it also seems likely that the beginning of the execution is when most of the heavy lifting for the application takes place; once the video begins to play, most of the data being used from the file is just dictating the colors of the pixels.
3.3.4 Number of Executor Processes
This is probably the easiest parameter to figure out. The short and obvious answer is: as many as possible. The data in the graph below is clear and expected: there are very good returns for introducing a little bit of parallelism, but there are diminishing returns as the number of parallel processes increase. Between 4 and 5 executor processes, the improvement begins to flatten out. At 6 Executors or more, the fuzzer begins to become unreliable and unstable. It seems then that running 4 Executors, one for each core in the Virtual Machine, is the optimal number for a fuzzing run, as it retains nearly the greatest productivity at lower risk of failure than with 5 or more Executors.
4. Conclusions and Further Work
The fuzzing run on VLC yielded a lot of important information. First and foremost, at least ten unique crashes, one of which appears to be highly exploitable. These crashes were then useful in determining optimal parameters for future fuzzing runs on VLC. Specifically that the optimal timeout is around 9.25s, the optimal fuzz factor is around 15%. Further testing revealed that running four Executor processes for a fuzzing run is likely to be ideal. The crash files found in this paper exposed bugs in a variety of libraries used by VLC and other programs, and could have serious ramifications if any of them are found to be exploitable. I intend on sending a full bug report to VLC for any of these issues that haven’t yet been resolved.
Given more time, there are several aspects of this project I would have liked to explore further. First of all, another large scale fuzzing run on VLC with the optimized parameters found in this paper could help to confirm the conclusions I drew from the first run, as well as potentially uncover more bugs. Reverse engineering the errors found during the first fuzzing run of VLC and discovering whether any of them are actually exploitable would complete the vulnerability discovery process and assist developers on the project. Also, because the fuzzer will crash occasionally during long fuzzing runs, it would be helpful for the FuzzServer to be checking in on FuzzClients (through a ping-ack protocol for example) to see when they die. If a client dies, the server could notify the human in charge of the fuzzing run that a machine has gone down to minimize downtime for that computer.
5 References
Appendix A: Comparison of Mutator Function Performance
Mutator: Time per File vs. File Size
Mutator2: Time Per File vs. Average File Size
Appendix B: Source Code
# FuzzClient.py
# Dylan Wolff 5/8/15
# FuzzClient immediately makes a connection with a FuzzServer and receives fuzzing files and parameters
# for the run. It then starts a Fuzzer process for the run itself
from socket import *
from multiprocessing import Process
import Fuzzer, os
#function that receives a binary file from the clientSocket and returns it
def recFile(clientSocket, filesize):
s = ''
while len(s) != filesize:
s = s + clientSocket.recv(filesize - len(s))
return s
if __name__ == '__main__':
path = '/Users/Fuzzer/Desktop/'
#Delete files from any previous runs
print "Discarding old sample files, hope you saved everything..."
for root, dirs, files in os.walk(path + "Samples"):
for f in files:
os.unlink(os.path.join(root, f))
#Get server info parameters from the config File
f = open(path + 'FuzzerConfig.txt', 'r')
sl = f.readlines()
serverPort = int(sl[11].strip())
serverIP = sl[13].strip()
f.close()
print "Connecting to " + str(serverPort) + " at " + serverIP
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverIP, serverPort))
# get parameters for the fuzzing run and put in config file
reply = clientSocket.recv(4096)
# Peel out info from the string to give to the Fuzzer process
sl = reply.split('
')
print sl
print sl
timeout = float(sl[1].strip())
fuzzFactor = float(sl[3].strip())
program = sl[5].strip()
iterations = int(sl[7].strip())
numExecs = int(sl[9].strip())
# put the parameters in the config file in case we need to resume
print "rec config"
clientSocket.send("sup")
print "ack"
f = open(path + 'FuzzerConfig.txt', 'w+')
f.truncate()
f.write(reply + '
#Server Port Number
' + str(serverPort) + '
#Server IP Address
' + serverIP + '
#Number of Client Fuzzers
' + '1')
f.close()
# receive files until we get the done sending files token of all 'a's
while True:
# Get the reply from the server
reply = ""
while len(reply) != 4096:
reply = reply + clientSocket.recv(4096-len(reply))
# if all files have been set/received, break
if reply == 4096*'a':
break
# send acknowledgement to server
clientSocket.send("sup")
# peel out the information about the file
s = reply.split('|')
# receive a file of length specified by s[1]
guy = recFile(clientSocket, int(s[1]))
# send acknowledge
clientSocket.send("sup")
# write the received file to the samples folder
f = open(path + 'Samples/' + s[0], 'wb')
f.write(guy)
f.close()
clientSocket.close()
# Now begin the fuzzing run
process = Process(target=Fuzzer.Fuzzer, args=(False, timeout, fuzzFactor, program, iterations, numExecs, serverPort, serverIP, path, True))
process.start()
# FuzzServer.py
# Dylan Wolff 5/8/15
# FuzzServer waits for client connections. Once a connection is made, it sends across fuzzing parameters and
# sample files from the ServSamples folder to each client. Finally it again waits for client connections to
# receive the results from a distributed fuzzing run. The default port for the server to wait on is 12000
import os, uuid, shutil, Executor, pickle, time
from socket import *
from multiprocessing import Process, Queue
# Function that sends a file from the ServSamples folder to a client given a connection socket and the filename
def sendFile(filename, targetSocket):
f = open(path + 'ServSamples/' + filename, 'rb')
s = f.read()
totalBytes = len(s)
targetSocket.send(filename + '|' + str(totalBytes) + '|' + 'x'*(4096 - len(filename) - len(str(totalBytes)) - 2))
# First send over the information about the file, padding the rest of the packet with xs so its the
# number of bytes
# first send across the size of the file so the client knows how much to expect
targetSocket.recv(3)
# ack after every send to prevent consecutive messages from being merged
targetSocket.send(s)
# Actually send the file across
targetSocket.recv(3)
# ack
def distributeSamples(numClients, numExecs, path, timeout, program, fuzzFactor, iterations, serverPort, serverIP):
# this function distributes the sample files evenly across all client fuzzers
clientConfigInfo = '#Timeout: \n' + str(timeout) + '
# Fuzz Factor: \n' + str(fuzzFactor) + '
# Name of Program Being Fuzzed: \n' + program + '
# Number of Mutation iterations per File: \n' + str(iterations) + '
# Number of Executing Threads per Client: \n' + str(numExecs)
# set up serversocket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverIP, serverPort))
serverSocket.listen(numClients)
# get list of files to send to clients
samples = os.listdir(path + "ServSamples")
# samples per client is integer division, so remainder is used for leftovers
samplesPerClient = len(samples)/numClients
remainder = len(samples)%numClients
# while we haven’t sent files to all of the clients
clientSent = 0
while clientSent < numClients:
clientSent = clientSent + 1
connectionSocket, addr = serverSocket.accept()
connectionSocket.send(clientConfigInfo)
connectionSocket.recv(3)
# give the client the parameters for the fuzzing run, then wait for ack
# figure out the appropriate number of sample flies to send over
samplesSent = 0
if remainder > 0:
extra = 1
remainder = remainder - 1
else:
extra = 0
# send them over
while samplesSent < samplesPerClient + extra:
sendFile(samples[0], connectionSocket)
samples.remove(samples[0])
samplesSent = samplesSent + 1
# send the finished sending files message (super bootleg, but whatever)
connectionSocket.send(4096*'a')
def recFile(clientSocket, filesize):
# this function receives a file from a given socket knowing the filesize
s = ''
while len(s) != filesize:
s = s + clientSocket.recv(filesize - len(s))
return s
def aggregateCrashes(path, numClients, serverPort, serverIP):
# this function takes in all the crashes from all the clients
# set up serversocket
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverIP, serverPort))
serverSocket.listen(numClients)
clientsReported = 0
directory = str(uuid.uuid4())
while clientsReported < numClients:
# while we haven't received files from all of the clients
os.makedirs(path + '/servCrashers/' + directory)
#make a directory for our first expected crash folder
clientsReported = clientsReported + 1
#tally the client for reporting in
connectionSocket, addr = serverSocket.accept()
#accept the connection
#receive files until we get the done sending files token
while True:
print "waiting to receive"
reply =
while len(reply) != 4096:
reply = reply + connectionSocket.recv(4096-len(reply))
if reply == 4096*'a':
#if we get the end of folder token, then we create a new folder for the next
batch
directory = str(uuid.uuid4())
os.makedirs(path + '/servCrashers/' + directory)
elif reply == 4096*'b':
#if we then receive the end crashes token, we delete that folder, and get the
next client and their crashes
shutil.rmtree(path + '/servCrashers/' + directory)
break
else:
#otherwise, we begin receiving files, and putting them in that folder.
connectionSocket.send('sup')
s = reply.split(',')
#initial message has the filename and the size in it
guy = recFile(connectionSocket, int(s[1]))
connectionSocket.send('sup')
f = open(path + '/servCrashers/' + directory + '/' + s[0], 'wb')
f.write(guy)
f.close()
serverSocket.close()
print 'All Clients Finished Fuzzing'
def fuzzReport(path, iterations):
# This function does some automatic analysis of a distributed fuzzing run
samples = os.listdir(path + 'ServSamples')
totalFiles = len(samples) * iterations
crashes = os.listdir(path + 'ServCrashers')
totalCrashes = len(crashes)
print '
Of ' + str(totalFiles) + ' files, ' + str(totalCrashes) + ' were crashes'
count = 0
c = 0
rips = []
uniques = 0
for crash in crashes:
try:
f = open(path + 'ServCrashers/' + crash + '/crashlog.txt', 'r')
except:
continue
lines = f.readlines()
f.close()
if 'Exploitable' in lines[2]: # check if crashlog says its Exploitable
count = count + 1
for line in lines:
# check if RIP is unique to this crash
if 'rip=' in line:
rip = (line.split('=')[1]).split(' ')[0]
if rip not in rips:
rips.append(rip)
uniques = uniques + 1
print '
' + str(count) + ' of which are considered Exploitable'
print '
' + str(uniques) + ' of which are unique (by fault address)'
print '\n\n' + str(count) + ' of which are considered Exploitable'
print '\n\n' + str(uniques) + ' of which are unique (by fault address)"
if __name__ == '__main__':
# Get parameters for fuzzing run
path = '/Users/Fuzzer/Desktop/
f = open(path + 'FuzzerConfig.txt', 'r')
sl = f.readlines()
timeout = float(sl[1].strip())
fuzzFactor = float(sl[3].strip())
program = sl[5].strip()
iterations = int(sl[7].strip())
numExecs = int(sl[9].strip())
serverPort = int(sl[11].strip())
serverIP = '10.0.2.15'
# The server is always the local VM IP address for NAT Configuration
numClients = int(sl[15].strip())
f.close()
response = raw_input("Are you in the middle of a run and need to receive files? (y or n)\n")
if (response == 'y'):
response = raw_input("how many clients need to still report in? \n")
aggregateCrashes(path, int(response), serverPort, serverIP)
fuzzReport(path, iterations)
else:
print "Discarding old aggregate crashes"
for root, dirs, files in os.walk(path + "ServCrashers"):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
distributeSamples(numClients, numExecs, path, timeout, program, fuzzFactor, iterations, serverPort, serverIP)
aggregateCrashes(path, numClients, serverPort, serverIP)
from winappdbg import Debug, HexDump, win32, Thread, Crash
from socket import *
import os, uuid, shutil, Executor, pickle, Mutator, time, Fuzzer, ctypes, multiprocessing
class Fuzzer():
def __init__(self, resume, timeout, fuzzFactor, program, iterations, numExecs, serverPort, serverIP, path, distributed):
path = 'C:\Users\Fuzzer\Desktop/'
#Delete remaining files from previous run if not resuming
if not resume:
print "Deleting old files, hope you saved everything..."
for root, dirs, files in os.walk(path + "State"):
for f in files:
os.unlink(os.path.join(root, f))
for root, dirs, files in os.walk(path + "Crashers"):
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
for root, dirs, files in os.walk(path + "Mutated"):
for f in files:
os.unlink(os.path.join(root, f))
fuzzReport(path, iterations)
if resume:
# Get the Queues back from serialized file
print "Resuming previous run..."
try:
qnfilein = open(path + "State/qn", 'rb')
qnList = pickle.load(qnfilein)
qnfilein.close()
except:
qnList = []
try:
qfilein = open(path + "State/q", 'rb')
qList = pickle.load(qfilein)
qfilein.close()
except:
qList = []
else:
qList = []
qnList = []
q = multiprocessing.Queue()
for item in qList:
q.put(item)
qn = multiprocessing.Queue()
for item in qnList:
qn.put(item)
# Give a time estimate in seconds for the run
try:
print "Running", numExecs, " Executor processes. Estimated time = ",
((timeout*iterations*len(os.listdir(path + '/Samples/')))/numExecs)
except:
pass
#begin the Mutator process
process = multiprocessing.Process(target=Mutator.Mutator, args=(path, fuzzFactor, iterations, q, qn,
process.start()
# start appropriate number of Executor processes
eProcesses = [None] * numExecs
for i in range(numExecs):
eProcesses[i] = multiprocessing.Process(target=Executor.Executor, args=(timeout, program, path, q, qn, i, resume))
eProcesses[i].start()
# sit in a loop monitoring Executor processes and checking if the fuzzing run is over
while True:
time.sleep(1)
for i in range(numExecs):
if not eProcesses[i].is_alive():
eProcesses[i] = multiprocessing.Process(target=Executor.Executor, args=(timeout, program, path, q, qn, i, True))
eProcesses[i].start()
if q.qsize() == 1:
top = q.get()
q.put(top)
if top == "STOP":
break
# Wait until all Executors are done. Run each again just to be totally sure everything is done running
for i in range(numExecs):
while eProcesses[i].is_alive():
time.sleep(1)
eProcesses[i] = multiprocessing.Process(target=Executor.Executor, args=(timeout, program, path, q, qn, i, True))
eProcesses[i].start()
for i in range(numExecs):
while eProcesses[i].is_alive():
time.sleep(1)
print "Finished fuzzing run"
# delete any remaining mutated files
fails = 0
for i in range(qn.qsize()):
try:
s = qn.get(False)
except:
continue
try:
os.remove(path + 'Mutated/' + s)
except:
fails = fails + 1
print "unable to delete ", fails, " mutated files"
if(distributed):
print "sending results to server"
self.sendCrashes(path, serverPort, serverIP)
else:
self.fuzzReport(path, iterations)
def fuzzReport(self, path, iterations):
# this function does a cursory automatic analysis of the crashes produced by a run
samples = os.listdir(path + 'Samples')
totalFiles = len(samples) * iterations
crashes = os.listdir(path + 'Crashers')
totalCrashes = len(crashes)
print "Of " + str(totalFiles) + " files, " + str(totalCrashes) + " were crashes"
count = 0
rips = []
uniques = 0
for crash in crashes:
f = open(path + 'Crashers/' + crash + '/crashlog.txt', 'r')
lines = f.readlines()
if 'Exploitable' in lines[2]:
# check if crashlog says its exploitable
count = count + 1
for line in lines:
# check for a unique RIP
uniques = uniques + 1
if 'rip=' in line:
rip = (line.split('=')[1].split(' '))[0]
if rip not in rips:
rips.append(rip)
uniques = uniques + 1
print "\n" + str(count) + " of which are considered Exploitable"
print "\n" + str(uniques) + " of which are unique (by fault address)"
def sendFile(self, fpath, fname, targetSocket):
# this function sends a single file given its name and path across a given socket 4096 bytes at a time
f = open(fpath + '/' + fname, 'rb')
s = f.read()
totalBytes = len(s)
targetSocket.send(fname + '|' + str(totalBytes) + '|' + 'x'*(4096 - len(fname) - len(str(totalBytes)) - 2))
# first send across the size of the file so the receiver knows how much to expect as well as the name, fill up
# the packet with x's
targetSocket.recv(3)
# ack after every send to prevent consecutive messages from being merged
targetSocket.send(s)
# sendfile
targetSocket.recv(3)
# ack
def sendCrashes(self, path, serverPort, serverIP):
# this function sends all of the crashes in the Crashers folder back to the main server for analysis
# set up connection with server
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverIP, serverPort))
# get all crash folders
crashes = os.listdir(path + 'Crashers')
for crash in crashes:
# for each folder (note that windows has a hidden file it sometimes auto creates called desktop.ini.
# it's obviously not a folder, so it produces an error if we were to look inside it)
if crash != 'desktop.ini':
files = os.listdir(path + 'Crashers/' + crash)
for f in files:
#for each file in crash folder, send it across
self.sendFile(path + 'Crashers/' + crash, f, clientSocket)
#4096 a's is the end of a crash folder signal
clientSocket.send(4096*'a')
print "Totally done sending files to server"
#4096 b's is the end of all the crashes from this guy signal
clientSocket.send(4096*'b')
clientSocket.close()
if __name__ == '__main__':
# This is for either non-distributed runs, or to resume a run
response = raw_input("Would you like to resume a previous fuzzing run? (please type either 'y' or 'n'
followed by the enter key)
"
)
if (response != 'n'):
responseDist = raw_input("Is the run distributed? (please type either 'y' or 'n' followed by the enter key)
"
)
else:
responseDist = 'n'
path = 'C:\Users\Fuzzer\Desktop/'
#Get Fuzzing parameters from Config File
f = open(path + 'FuzzerConfig.txt', 'r')
sl = f.readlines()
timeout = float(sl[1].strip())
fuzzFactor = float(sl[3].strip())
program = sl[5].strip()
iterations = int(sl[7].strip())
numExecs = int(sl[9].strip())
serverPort = int(sl[11].strip())
serverIP = sl[13].strip()
f.close()
process = multiprocessing.Process(target=Fuzzer.Fuzzer, args=((response != 'n'), timeout, fuzzFactor, program, iterations, numExecs, serverPort, serverIP, path, (responseDist == 'y')))
process.start()
# Executor.py
# Dylan Wolff 5/8/15
# Receives files to execute under the target program (program_name) from a synchronized queue (q) with
# a debugger attached (using the Debug class from winappdbg). A callback function (my_event_handler)
# records the debugger output upon a crash to a unique folder in the Crashers folder.
from winappdbg import Debug, HexDump, win32, Thread, Crash
from time import time
import os, uuid, shuutil, Queue, subprocess, ctypes, pickle
class Executor():
def __init__(self, timeout, program_name, path, queue_in, qn, my_pid, resume):
self.timeout = timeout
self.queue_in = queue_in
self.program_name = program_name
self.path = path
self.filename = None
self.mutator_specs = None
self.resume = resume
self.my_pid = my_pid
self.qn = qn
self.enterLoop()
def enterLoop(self):
# Function in which the Executor sits in a loop executing files under the target program
fuzzed = 0
while True:
if not self.resume:
# if we didn’t just die, get next file from the queue
try:
obj = self.queue_in.get()
except:
continue
if we can’t get a file off of the queue, try again
continue
#poison pill
if obj == "STOP":
self.queue_in.put("STOP")
fileout = open(self.path + "State/" + str(self.my_pid), 'w')
fileout.truncate()
fileout.write("STOP" + " | " + "pls")
fileout.close()
return
#otherwise we prepare to debug
self.mutator_specs = obj['mutator_specs']
self.filename = obj['filename']
#then log as a new start
fileout = open(self.path + "State/" + str(self.my_pid), 'w+)
fileout.truncate()
fileout.write(self.filename + " | " + self.mutator_specs + " | " + str(False))
fileout.close()
else:
#we've resumed, so set this back
self.resume = False
#if we are recovering from a crash of the executor, load the last file tried
filein = open(self.path + "State/" + str(self.my_pid), 'r')
s = filein.read()
filein.close
params = s.split(" | ")
#if we are supposed to be stopped, just return
if params[0] == "STOP":
return
#if we had already finished executing the previous file before death, this is True
finishedPrevFile = (params[2] == "True")
if finishedPrevFile:
#if we did finish the file we were on, then continue loop at top to look at queue
continue
else: #if we haven't finished the previous file, do so
self.mutator_specs = params[1]
self.filename = params[0]
print "Executing ", self.filename
#run the file
x = [self.program_name, self.path + "Mutated/" + self.filename]
self.simple_debugger(x)
#then log as done
fileout = open(self.path + "State/" + str(self.my_pid), 'w+')
fileout.truncate()
fileout.write(self.filename + " | " + self.mutator_specs + " | " + str(True))
fileout.close()
#try to remove the old mutated file
try:
os.remove(self.path + "Mutated/" + self.filename)
except:
#if we can't because of a zombie executing process, put in on a queue for later
self.qn.put(self.filename)
try:
#serialize qn and add to a file in case of crash
fileout = open(self.path + "State/qn", 'w+')
pickle.dump(self.qndump(), fileout)
fileout.close()
except:
pass
#if we are running short on memory because the executor processes are failing to kill children,
# killing the parent executor will definitely kill the kids and free up memory so that the OS
# doesn't start randomly killing processes
stat = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
if 90 < int(stat.dwMemoryLoad) and fuzzed != 0:
#kill if this executor has run more than one process since last death
print self.my_pid, " committing suicide to save memory"
os.kill(os.getpid(), 9)
fuzzed = fuzzed+1
def my_event_handler(self, event):
# This callback function logs crashes of the target program.
# Credit to the WinAppDbg website for the extremely detailed tutorial used to construct this function
# Get the process ID where the event occurred.
pid = event.get_pid()
# Get the thread ID where the event occurred.
tid = event.get_tid()
# Find out if it's a 32 or 64 bit process.
bits = event.get_process().get_bits()
# Get the value of EIP at the thread.
address = event.get_thread().get_pc()
# Get the event name.
name = event.get_event_name()
# Get the event code.
code = event.get_event_code()
# If the event is an exception...
if code == win32.EXCEPTION_DEBUG_EVENT and event.is_last_chance() and code not in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT):
# Get the exception user-friendly description.
name = event.get_exception_description()
# Get the exception code.
code = event.get_exception_code()
# Get the address where the exception occurred.
try:
address = event.get_fault_address()
except NotImplementedException:
address = event.get_exception_address()
crash = Crash(event)
crash.fetch_extra_data(event, takeMemorySnapshot = 2)
# Log the crash in a new unique crash folder in the Crashers directory
folder = str(uuid.uuid4())
os.makedirs(self.path + '/Crashers/' + folder)
f = open(self.path + '/Crashers/' + folder + '/crashlog.txt', 'w')
f.write(crash.fullReport(bShowNotes = True))
f.close()
f = open(self.path + '/Crashers/' + folder + '/crashsrc.txt', 'w')
f.write(self.mutator_specs)
f.close()
def simple_debugger(self, argv):
# This function creates a Debug object and executes the target program and file under it
# Again, credit to the WinAppDbg website for tutorials on how to use their stuff
# Instance a Debug object, passing it the event handler callback.
debug = Debug( self.my_event_handler, bKillOnExit = True )
maxTime = time()+self.timeout
# Start a new process for debugging.
# Execute the program
currentProcess = debug.execv(argv)
# wait for the timeout
while debug and time() < maxTime:
try:
debug.wait(1000)
# Continue if the timeout hasn't been reached
except WindowsError, e:
if e.winerror in (win32.ERROR_SEM_TIMEOUT, win32.WAIT_TIMEOUT):
continue
raise
try:
debug.dispatch()
finally:
debug.cont()
# stops debugging, kills all child processes according to WinAppDbg documentation
# In practice, this doesn't always work
debug.stop()
#if the target process is still alive, kill it. Equivalent to PROCESS_TERMINATE
try:
currentProcess.kill()
except:
pass
def qndump(self):
# this dumps the queue of undeleted files to a list
qnList = []
while self.qn.qsize() != 0:
qnList.append(self.qn.get())
for item in qnList:
self.qn.put(item)
return qnList
class MEMORYSTATUSEX(ctypes.Structure):
# Taken directly from stackoverflow. See paper bibliography for details.
# Gets information about total system memory usage
_fields_ = [
('dwLength', ctypes.c_ushort),
('dwMemoryLoad', ctypes.c_ushort),
('ullTotalPhys', ctypes.c_ulonglong),
]
def __init__(self):
# have to initialize this to the size of MEMORYSTATUSEX
self.dwLength = ctypes.sizeof(self)
super(MEMORYSTATUSEX, self).__init__()
# Mutator.py
# Dylan Wolff 5/8/15
# Mutator.py is initialized with various fuzzing parameters. It then begins mutating files
# in the samples folder according to those parameters according to these parameters. These
# files are mutated by either the mutate, or mutate2 functions according to file size and
# memory availability. The mutate function uses larger amounts of memory, but is faster
# when compared to the mutate2 function. Mutated files are placed in the Mutated directory
import random, math, os, Queue, shutil, time, pickle, multiprocessing, copy
class Mutator():
def __init__(self, path, fuzzFactor, iterations, q, qn, resume):
self.q = q
self.path = path
self.fuzzFactor = fuzzFactor
self.iterations = iterations
self.qn = qn
if resume:
self.resumer()
# call a function to resume a fuzzing run that is already in progress
else:
# otherwise, we know we have to mutate all sample files
# get list of names of all sample files
samples = os.listdir(self.path + "Samples")
#sort them by size small to large
samples.sort(key = lambda sample: (os.path.getsize(self.path + "Samples/" + sample)))
#mutate each sample
for sample in samples:
self.mutate(self.path, sample, self.fuzzFactor, 0, self.iterations)
self.q.put("STOP")
def log(self, sample, iters):
#this function logs the progress of the mutator in case a fuzzing run is interrupted
fileout = open(self.path + "State/Mutator", 'wb+')
fileout.truncate()
fileout.write(sample + " | " + str(iters) + "\n")
fileout.close
return
def resumer(self):
#this function resumes the mutator if a fuzzing run has been interrupted.
currentFiles = []
#Find the files all Executor processes will resume at
currentStates = os.listdir(self.path + "State")
for thread in currentStates:
if thread != "Mutator":
filein = open(self.path + "State/" + thread, 'rb')
s = filein.read()
filein.close()
name = s.split(" | ")[0]
currentFiles.append(name)
# Get any Mutated files that weren't deleted after execution
qnlist = []
while self.qn.qsize() != 0:
qnlist.append(self.qn.get(False))
# Next Resume mutating files from where the Mutator left off
samples = os.listdir(self.path + 'Samples')
samples.sort(key = lambda sample: (os.path.getsize(self.path + 'Samples/' + sample)))
filein = open(self.path + 'State/Mutator', 'rb')
s = filein.read()
filein.close()
params = s.split(' | ')
#params[0] is name, [1] is number of iters done
#flip through sorted list of seed files until current is found, discarding all others
while params[0] != samples[0]:
samples.pop(0)
#finish the iterations for the current seed file
currentsample = samples.pop(0)
if int(params[1]) != self.iterations - 1:
try:
self.mutate(self.path, currentsample, self.fuzzFactor, int(params[1]) + 1,
self.iterations)
except:
pass
# do all the rest of the seed files
for sample in samples:
try:
self.mutate(self.path, sample, self.fuzzFactor, 0, self.iterations)
except:
pass
self.q.put("STOP")
def mutate2(self, path, fullfilename, fuzzFactor, start, iterations):
# A mutate function that uses less memory
ext = "." + fullfilename.split('.')[-1]
filename = fullfilename[0:len(fullfilename)-(len(ext))]
filesize = os.path.getsize(path + "Samples/" + filename + ext)
# get the filesize
numwrites = int(math.ceil(fuzzFactor * filesize))
# get the number of writes to do (size/factor)
for i in range(start, iterations):
shutil.copy2(path + "Samples/" + filename + ext, path + "Mutated/" + filename + str(i) + ext)
# copy the sample into the new folder with a new name
fileout = open(path+ "Mutated/" + filename + str(i) + ext, 'r+b')
# open the file
random.seed() # seed with system time to get a clean random number
randSeed = str(random.random()) # keep track of our seed
random.seed(randSeed) # seed the thing so that we can recreate mutated file
for j in range(numwrites):
rbyte = random.randrange(256)
# get our random byte
randloc = random.randrange(filesize)
# get our random location to write to
fileout.seek(randloc, 0)
# find a random location in the file
fileout.write(chr(rbyte))
# write the byte as an ascii character to that locale
self.log(fullfilename, i)
# close the file
fileout.close()
self.q.put({'mutator_specs': filename + ext + '~' + str(randSeed) + '~' + str(fuzzFactor),
'filename': filename + str(i) + ext})
def checkTotalMutatedSize(self, path):
# returns the size of the Mutated folder on the desktop
totalsize = 0
currentMutes = os.listdir(path + "Mutated")
for f in currentMutes:
totalsize = totalsize + os.path.getsize(path + "Mutated/" + f)
return totalsize
def mutate(self, path, fullfilename, fuzzFactor, start, iterations):
# This function mutates files quickly, but uses a lot of memory
ext = "." + fullfilename.split('.')[-1]
filename = fullfilename[0:len(fullfilename)-(len(ext))]
# Check how much Hard Drive Space we are taking up with the mutated files. If it exceeds ~5 Gigs,
# we start running out of virtual HD space. Since the Executors need to catch up anyway,
# no harm in sitting around and waiting for them before continuing
filesize = os.path.getsize(path+ "Samples/" + filename + ext)
while self.checkTotalMutatedSize(path) + filesize >= 5000000000:
print "HD Capacity Risk, mutator stalling for more space to be cleared"
for i in range(self.qn.qsize()):
# while stalling, the mutator checks a queue of old mutated files that need
# to be deleted and attempts to delete them
try:
s = qn.get(False)
except:
continue
try:
os.remove(path + 'Mutated/' + s)
except:
os.remove(path + 'Mutated/' + s)
except:
time.sleep(1)
try:
os.remove(path + 'Mutated/' + s)
except:
qn.put(s)
if filesize > 11000000:
print "Extremely Large File, switching mutator functions to conserve memory"
self.mutate2(path, fullfilename, fuzzFactor, start, iterations)
return
# read in the sample to a string
try:
filein = open(path+ "Samples/" + filename + ext, 'rb')
raw = filein.read()
filein.close()
except:
print "Memory Error, switching mutator functions"
del raw
self.mutate2(path, fullfilename, fuzzFactor, start, iterations)
return
# get its length
filesize = len(raw)
numwrites = int(math.ceil(filesize * fuzzFactor))
# get the number of writes to do (size/factor)
for i in range(start, iterations):
# for each mutation iteration
# copy the file into a list, if we get a memory error because the file is too big, use the version of mutate that doesn't use memory
try:
new = list(raw)
except:
print "Memory Error, switching mutator functions"
del raw
del new
self.mutate2(path, fullfilename, fuzzFactor, start, iterations)
return
random.seed() # seed with system time to get a clean random number
randSeed = str(random.random()) # keep track of our seed
random.seed(randSeed) #seed the thing so that we can recreate mutated file
for j in range(numwrites):
rbyte = random.randrange(256)
#get our random byte
randloc = random.randrange(filesize)
#get our random location
#write the byte as an ascii character to that locale in the list
new[randloc] = chr(rbyte)
self.log(fullfilename, i)
#write to the new file
fileout = open(path+ "Mutated/" + filename + str(i) + ext, 'w+b')
fileout.write("\n".join(new))
fileout.close
#print 'on the q'
self.q.put({'mutator_specs': filename + ext + '-' + str(randSeed) + '-' + str(fuzzFactor),
'filename': filename + str(i) + ext})
#serialize q and add to a file in case of crash
fileout = open(self.path + "State/q", 'wb')
pickle.dump(self.qdump(), fileout)
fileout.close()
def qdump(self):
#this dumps the queue of mutated files to a list
qList = []
while self.q.qsize() != 0:
qList.append(self.q.get())
for item in qList:
self.q.put(item)
return qList
import random, os, math
path = 'C:\Users/Fuzzer/Desktop/'
#path hardcoded to be Desktop of VM
fs = os.listdir(path + 'remutateFolder')
j = 0
for f in fs:
j = j + 1
a = open(path + 'remutateFolder/' + f, 'r')
s = a.read()
samplename, sampleseed, fF = s.split('~')
#pull the name of the original sample file, the random seed that gave rise to the mutations,
#and the mutation percentage
a.close()
fuzzFactor = float(fF)
# now use the seed and the same mutation procedure as the mutate function in Mutator.py
# to re-generate the mutated file
random.seed(sampleseed)
sample = open(path + 'Samples/' + samplename, 'rb')
s = sample.read()
sample.close()
filesize = len(s)
numwrites = int(math.ceil(filesize * fuzzFactor))
new = list(s)
for i in range(int(numwrites)):
rbyte = random.randrange(256)
randloc = random.randrange(filesize)
new[randloc] = chr(rbyte)
#write to the new file in the Mutated directory
fileout = open(path + "Mutated/" + str(j) + samplename, 'w+b')
fileout.write("".join(new))
fileout.close
|
{"Source-Url": "https://www.bc.edu/content/dam/files/schools/cas_sites/cs/pdf/academics/honors/15DylanWolff.pdf", "len_cl100k_base": 15434, "olmocr-version": "0.1.50", "pdf-total-pages": 59, "total-fallback-pages": 0, "total-input-tokens": 96155, "total-output-tokens": 19081, "length": "2e13", "weborganizer": {"__label__adult": 0.000370025634765625, "__label__art_design": 0.0004222393035888672, "__label__crime_law": 0.0006422996520996094, "__label__education_jobs": 0.0012378692626953125, "__label__entertainment": 0.0001150965690612793, "__label__fashion_beauty": 0.00014030933380126953, "__label__finance_business": 0.00016450881958007812, "__label__food_dining": 0.0002815723419189453, "__label__games": 0.000957489013671875, "__label__hardware": 0.00109100341796875, "__label__health": 0.00035834312438964844, "__label__history": 0.00021314620971679688, "__label__home_hobbies": 0.00010073184967041016, "__label__industrial": 0.0002715587615966797, "__label__literature": 0.00032019615173339844, "__label__politics": 0.0002052783966064453, "__label__religion": 0.0003371238708496094, "__label__science_tech": 0.028350830078125, "__label__social_life": 0.00011408329010009766, "__label__software": 0.015716552734375, "__label__software_dev": 0.9482421875, "__label__sports_fitness": 0.0001906156539916992, "__label__transportation": 0.00022912025451660156, "__label__travel": 0.00013720989227294922}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67961, 0.01448]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67961, 0.42192]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67961, 0.84933]], "google_gemma-3-12b-it_contains_pii": [[0, 175, false], [175, 982, null], [982, 1330, null], [1330, 1658, null], [1658, 3113, null], [3113, 5189, null], [5189, 6711, null], [6711, 8102, null], [8102, 8545, null], [8545, 10059, null], [10059, 11706, null], [11706, 13571, null], [13571, 15218, null], [15218, 16587, null], [16587, 18019, null], [18019, 19351, null], [19351, 21169, null], [21169, 22567, null], [22567, 23168, null], [23168, 23868, null], [23868, 24530, null], [24530, 26298, null], [26298, 27484, null], [27484, 28519, null], [28519, 29245, null], [29245, 30913, null], [30913, 33111, null], [33111, 33251, null], [33251, 33251, null], [33251, 33251, null], [33251, 34399, null], [34399, 35538, null], [35538, 36938, null], [36938, 38471, null], [38471, 39517, null], [39517, 40916, null], [40916, 42255, null], [42255, 43557, null], [43557, 44644, null], [44644, 45611, null], [45611, 46759, null], [46759, 47978, null], [47978, 49542, null], [49542, 50792, null], [50792, 52342, null], [52342, 53610, null], [53610, 54942, null], [54942, 56163, null], [56163, 57254, null], [57254, 58249, null], [58249, 59521, null], [59521, 60705, null], [60705, 61862, null], [61862, 63222, null], [63222, 64692, null], [64692, 65860, null], [65860, 66876, null], [66876, 67745, null], [67745, 67961, null]], "google_gemma-3-12b-it_is_public_document": [[0, 175, true], [175, 982, null], [982, 1330, null], [1330, 1658, null], [1658, 3113, null], [3113, 5189, null], [5189, 6711, null], [6711, 8102, null], [8102, 8545, null], [8545, 10059, null], [10059, 11706, null], [11706, 13571, null], [13571, 15218, null], [15218, 16587, null], [16587, 18019, null], [18019, 19351, null], [19351, 21169, null], [21169, 22567, null], [22567, 23168, null], [23168, 23868, null], [23868, 24530, null], [24530, 26298, null], [26298, 27484, null], [27484, 28519, null], [28519, 29245, null], [29245, 30913, null], [30913, 33111, null], [33111, 33251, null], [33251, 33251, null], [33251, 33251, null], [33251, 34399, null], [34399, 35538, null], [35538, 36938, null], [36938, 38471, null], [38471, 39517, null], [39517, 40916, null], [40916, 42255, null], [42255, 43557, null], [43557, 44644, null], [44644, 45611, null], [45611, 46759, null], [46759, 47978, null], [47978, 49542, null], [49542, 50792, null], [50792, 52342, null], [52342, 53610, null], [53610, 54942, null], [54942, 56163, null], [56163, 57254, null], [57254, 58249, null], [58249, 59521, null], [59521, 60705, null], [60705, 61862, null], [61862, 63222, null], [63222, 64692, null], [64692, 65860, null], [65860, 66876, null], [66876, 67745, null], [67745, 67961, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67961, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67961, null]], "pdf_page_numbers": [[0, 175, 1], [175, 982, 2], [982, 1330, 3], [1330, 1658, 4], [1658, 3113, 5], [3113, 5189, 6], [5189, 6711, 7], [6711, 8102, 8], [8102, 8545, 9], [8545, 10059, 10], [10059, 11706, 11], [11706, 13571, 12], [13571, 15218, 13], [15218, 16587, 14], [16587, 18019, 15], [18019, 19351, 16], [19351, 21169, 17], [21169, 22567, 18], [22567, 23168, 19], [23168, 23868, 20], [23868, 24530, 21], [24530, 26298, 22], [26298, 27484, 23], [27484, 28519, 24], [28519, 29245, 25], [29245, 30913, 26], [30913, 33111, 27], [33111, 33251, 28], [33251, 33251, 29], [33251, 33251, 30], [33251, 34399, 31], [34399, 35538, 32], [35538, 36938, 33], [36938, 38471, 34], [38471, 39517, 35], [39517, 40916, 36], [40916, 42255, 37], [42255, 43557, 38], [43557, 44644, 39], [44644, 45611, 40], [45611, 46759, 41], [46759, 47978, 42], [47978, 49542, 43], [49542, 50792, 44], [50792, 52342, 45], [52342, 53610, 46], [53610, 54942, 47], [54942, 56163, 48], [56163, 57254, 49], [57254, 58249, 50], [58249, 59521, 51], [59521, 60705, 52], [60705, 61862, 53], [61862, 63222, 54], [63222, 64692, 55], [64692, 65860, 56], [65860, 66876, 57], [66876, 67745, 58], [67745, 67961, 59]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67961, 0.01011]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
aeffe59d50869319bc82cea45e105f2f053a2bf7
|
ON BAYESIAN ESTIMATION FOR SOFTWARE RELIABILITY
Yang Y
US NRC
11555 Rockville Pike, Rockville, MD 20852, USA
Yaguang.yanag@nrc.gov
ABSTRACT
System safety is closely related to system reliability. Safety requirements many times are translated to reliability requirements. Nowadays, software systems exist in many engineering systems. However, there is no consensus method for software reliability estimation. On the other hand, there is an increasing interest in estimating the software reliability due to concerns for safety critical systems. In this paper, we try to close the gap by proposing a systematic and probabilistic method to estimate the software reliability based on software test data.
Key Words: Bayesian method, reliability, software, flow network
1 INTRODUCTION
System safety for safety critical systems is now a part of engineering design [13]. For example, application of probabilistic safety assessment (PSA) is required for nuclear power plants designs [11][12]. However, gaps exist between these design requirements and lacking of applicable methods and tools to implement the requirements. It is noticed in [12] that “at present it is not possible to derive a probabilistic model of software failure”. In reality, safety critical systems rely heavily on the equipment with digital instrumentation and control (DI&C) components/systems which include software. Therefore, there is increasing interest in international organizations, such as the United States Nuclear Regulatory Commission, in reliability and safety analyses for safety-critical DI&C systems, in particular, in the reliability analysis for software systems.
Many attempts have been made for more than four decades to find practical ways to improve software reliability and to estimate the software reliability. Lawrence [17] discussed activities that should be carried out throughout the software life cycle. Parnas, Asmis, and Madey [26] emphasized documentation requirements and quality control, including testing and reviews. Leveson and Harvey [18] proposed software fault tree analysis method. Up to the date, the most extensively investigated software reliability method is the software reliability growth model [6]. Many statistical models, such as the exponential distribution, Poisson distribution, Weibell distribution, and Gamma distribution models have been considered, and many different scenarios have been discussed in [10,14,15,26,30] and references therein. The reliability growth model is more like traditional hardware model in that the failure is time-related. However, unlike hardware-only analog equipment which is due to aging and weariness, therefore, failures are time-related, the software failure mechanism is due to undetected human errors, therefore, failures are not time-related. For this reason, the reliability estimation method for a software system should be different from that used for hardware.
* Office of Research, US NRC.
Because typical software failures are due to undetected human errors in certain parts of the software and failures are triggered by combinations of specific events and input data sets. A more attracted and reasonable estimation for software failure should be test-based probabilistic method, which was first introduced in [23], where a black-box\(^1\) model was proposed. This idea was further studied by many researchers in more recent efforts [3,4,19,20,21,31] for different scenario. These methods consider typically black box situation. There are some drawbacks for using the black-box model because they do not consider the complexity of the software systems. For example, if two different codes have the same number of successful test, black-box method gives the same estimated reliability value even if the sizes of the two codes are completely different or if the sizes are the same but the complexity of the structure of the two codes are drastically different.
Noticing the drawback of the block-box methods, some researchers considered the architecture-based software reliability analysis (see [8,9] and numerous references therein). Although software architectures are considered in this type of methods, these methods consider the architecture in software component level, the structure is at high level that does not provide the detailed structure information inside the software program. Beside, components level reliability estimation is not rigorously based on the probability theory.
For the aforementioned reasons, there is no consensus on an ideal software reliability estimation method [12]. Because of this difficulty, some nuclear plant probability risk analysis (PRA) assumed that software reliability is some constant without giving a method to validate the number, for example, ESBWR (economic simplified boiling water reactor) PRA analysis [1], which is far less than ideal.
In this paper, we restrict our discussion to single thread software, we also assume that the safety critical software under the discussion follows the guidelines\(^2\) in Section 4.4 of [18]. These assumptions on one hand make software structure simple, logic clean, and easy to analyze; on the hand, these assumptions should cover a class of software that are used in safety critical systems, for which design simplicity, deterministic execution time, and high reliability are required or desired. We propose some refinements for a recently developed software reliability estimation method given in [32,33] which is based on test data and software structure. The method is so promising that a hierarchical structure modeling platform has been built for nuclear system analysis [2]. The refinement in this paper makes method rigorously based on probability theory and test data similar to the methods in [19,20,21,23,31] while making full use of the structure of the software as we did in [32,33].
The remainder of the paper is organized as follows. Section 2 presents a flow network model for software structure and a simple example is given to describe it. Section 3 introduces a software reliability estimation method with a Bayesian estimation refinement. Section 4 discusses an automated tool for software reliability calculation. The last section gives the conclusions of this paper.
\(^1\) By black-box, we means that the software is viewed as a whole piece of code without considering the details inside the software.
\(^2\) Many guidelines for safety critical software are provided in [17], such as not using assembly language, not using recursion, interrupt, exception, pointer or indirect addressing, unconditional branches, branching out of loops, etc.
2 SOFTWARE COMPONENT FAILURE MODEL
There is no consensus on a method to be used for software reliability assessments due to lack of objective and rigorous methods, because most existing software reliability estimation methods use models suitable for hardware failures, while software failures are fundamentally different from hardware failures. Typical hardware failures are due to wear out (an example is the moving parts in mechanical systems) or aging-related (an example is mechanical parts made by plastic materials) failures. Therefore, hardware failure models are based on a random failure time that can be described by exponential, Poisson, Weibull, or Gamma distributions. However, typical software failures are due to undetected human errors in certain parts of the software and failures are triggered by combinations of specific events and input data sets. A problematic line of code in a software path may or may not be executed because the path is executed only when certain conditions are met. We call these conditions that determine the execution of a problematic path are triggering events. Even a problematic line of code is executed, the software may or may not fail because the data set used in the problematic line of code may not cause problem, for example, “c=a/b” does not cause any problem if b is not zero. Therefore, a failure occurs when triggering events determine the software to execute a problematic part of the software and a triggering data set is in use. Almost all existing methods that address software reliability issues do not model software failure in an appropriate way. Most software reliability models, such as the most extensively studied reliability growth model, are based on a random failure time which is inappropriate. Our model will consider both triggering events and the probability of existence of human mistakes.
2.1 Software Structure Model
There are several reasons that the software structure should be considered in the software failure model. First, the software structure is related to the triggering events which decide the path of software execution. Second, the complexity and details for every individual software is represented in the flow network model. Third, testing information can be fully used in the reliability analysis. Finally, a complex software can be divided into many simple pieces of codes; there is no branches inside each piece of the code, therefore, estimation reliability for each piece of code is easy to handle mathematically.
We use a flow network (also named as control flow graph (CFG) in software engineering literature [22]) to model the software structure. Let source denote the start point of the software; sink denote the end of the software; n nodes \( n_i \in N \) represent the logic branch or converging points; and edges \( e_{ij} \in E \), \( j = 1, \ldots, m \) denote the software code between node \( i \) and the node next to \( i \). If an edge is executed, then every line inside the edge is executed; i.e., no branch exists inside an edge. It is assumed that there is an infinite capacity in every edge, which means that each edge can have as many tests as desired. Using c/c++ language as an example, the nodes are collections of the beginning and the end of every function, the beginning and the end of every conditional block starting with ‘if’ or ‘switch’; while the edges are collections of pieces of software between nodes that meet one of the following conditions: (a) between the lines of the start of each function and the first ‘if’, ‘switch’ or ‘while’; (b) between the lines ‘if’ and the line ‘else’ or ‘else if’ or the end of ‘if’, or between the line ‘else if’ and the next ‘else if’ or the line that ends ‘if’; (c) between the lines of ‘case’; (d) between the lines after the end of ‘if’ or the line after the end of ‘switch’ and the line before the next ‘if’ or ‘switch’ or the line that ends the function. We use the following simple pseudo c/c++ code to describe the partition and the flow network concept.
Main()
{
Data initialization;
If condition A holds
{
Process data;
If data process success
{
Save result;
}
Else if data process fail
{
Issue a warning;
}
}
Else if condition A does not hold
{
Print "condition fail";
}
Clean memories;
}
It is worthwhile to point out that (a) any node is part of the edge right before the node, (b) there are software toolset capable to convert the software into the flow network [16], therefore, the translation from software to flow network will not be a technical obstacle to use the proposed model even for large software systems.
It is clear that the software structure represented by the flow network is related to the triggering events (checked at nodes) which decide the path of software execution. Also, the complexity [22] and details for every individual software is represented in the flow network model. The complexity and details will be fully considered in the next section when we discuss how to estimate the reliability of the entire software system.
To make the flow network model useful in the software reliability estimation, we need to perform test and record the numbers of successes and failures so that the statistical data can be used to estimate the reliability. After each test, the software development environment will record the software execution path of the test, say for a test the path is $e_{11} \rightarrow e_{21} \rightarrow e_{32} \rightarrow e_{41}$, the software engineer will examine the test result. If the test result meet the expectation, the engineer enters a key to accept the success of the test, the success numbers for all the edges on the path, namely, $e_{11}, e_{21}, e_{32},$ and $e_{41}$, will be increased by one. In a different test with different test data set, if the software execution path in the test is the same, but the result does not meet the expectation, the software engineer will identify the defect, say in edge $e_{32}$, then the engineer enters a key to reject the test result, the software development environment will set the success number of $e_{32}$ to zero because this edge was modified while keep the success numbers of other edges the same because they are not touched. Therefore, useful test information for the edges $e_{11}, e_{21},$ and $e_{41}$ are not lost. This information will be used in the software reliability estimation discussed in the next section. It is worthwhile to point out there are tools that are designed to record the test path [29].
Because each piece of code (edge) is very simple, there is no branch inside, it is easy to model the probability of existence of defect in an edge, which is our next topic.
### 2.2 Software Defect Model
Note that, for any piece of code, there are only two possibilities: either it has defect(s) or it has no defect. Therefore, we can use Bernoulli distribution to model if a piece of code $e_y$ has defect(s) or not, i.e., a binary random variable $D_y$ is used to represent the probability of the existence of defect(s) in a piece of code. Let $D_y = 1$ denote an event in which edge $e_y$ has been executed once and where the test result meets the expectations, therefore, $p_y = P(D_y = 1)$ denote the probability of no defect in this piece of software (there is a probability that a defect exists but is not detected). Let $D_y = 0$ denote an event in which edge $e_y$ has been executed once and where the result fails to meet the expectations because of some defect(s), therefore, $q_y = P(D_y = 0) = 1 - p_y$ is the probability of existence of at least one defect in this piece of code (there is a probability that no defect exists but the test engineer thinks that s/he finds a defect). Therefore, $p_y$ is the probability
of having no defect in \( e_y \) and \( q_y \) is the probability of having at least one defect in \( e_y \). Clearly, the one-time test scenario follows a Bernoulli distribution. It is likely that some edges are executed more than once in the software test stage. These multiple-test scenarios follow a binomial distribution. The main idea of this paper is to determine the probability \( p_{ij} \) by using repeated software test and examine the test results to see if a piece of code passes a test or not. If a piece of software contains some defect(s), then there is a probability that the software with defect(s) will fail if some triggering event occurs and if a triggering data set is in use. Moreover, examining the test result may catch the defect (when this occurs, the defect in the software will be fixed and the software quality will be improved). When testing is finished, the reliability of a piece of software is estimated according to the number of times that this piece of software passes the test after the last modification.
Since a piece of code may be tested many times involving different data set, we model the existence of defect(s) in a piece of software \( e_y \) by using a binomial distribution. Given a piece of code \( e_y \) which has \( h_{ij} \) executions in the test stage, then probability that this piece of code passes test \( k \) times follows a binomial distribution,
\[
p(E_{ij} = k) = C_{h_y}^k p_y^k q_y^{h_y-k},
\]
where \( k = 0,1,2,\ldots, h_y \), and
\[
C_{h_y}^k = \frac{h_y^!}{k!(h_y-k)!}.
\]
In the remainder of the paper, we propose and derive a test-based Bayesian estimation method to estimate reliability of each piece of the code, which is one of the major differences from the method discussed in [32][33]. We also take the structure of the software into consideration in software reliability estimation because (a) it reflects the individual software complexity, and (b) tests are not equally executed in every line of code. This lower level of detail should give better reliability estimations than the black box model [5] because more information is used in the estimation. To simplify our presentation and save space, we focus on software which is used in safety critical systems and follows the guidelines in [18].
### 3 SOFTWARE RELIABILITY ESTIMATION
There are two major differences in software reliability between the method proposed in this paper and the method proposed in [32,33]. First, the reliability estimation for a single edge proposed here uses rigorous Bayesian method while the method discussed in [32,33] uses a subjective heuristic method. Second, the method proposed here estimates the software reliability directly and the method discussed in [32,33] estimates failure rate and then translates to the reliability.
#### 3.1 Reliability Estimation for a Single Edge Using Bayesian Method
Let \( T_{ij} \) be the average execution time of the edge \( e_y \) of the software and \( h_{ij} \) be the total number of executions of \( e_y \) in the software test stage. If an edge \( e_y \) of the software is executed in a test
scenario, we consider that the test scenario covers the edge $e_{ij}$. As we discussed above, some edges may be tested more times than other edges. A main question in a multiple-test scenario is how to determine probability of no defect or reliability in these situations. The proposed reliability estimation is based on the test result using the Bayesian method. Let $t_i$ be the outcome of the $i$th test. The posterior density of $p_{ij}$ is sourced from earlier work, as follows [28]:
$$p(p_{ij} \mid t_1, \ldots, t_{h_{ij}}) = \frac{p(t_1, \ldots, t_{h_{ij}} \mid p_{ij})g(p_{ij})}{f(t_1, \ldots, t_{h_{ij}})} = \frac{p(t_1, \ldots, t_{h_{ij}} \mid p_{ij})g(p_{ij})}{f(t_1, \ldots, t_{h_{ij}})} , \quad (3)$$
where
$$f(t_1, \ldots, t_{h_{ij}}) = \int p(t_i \mid p_{ij}) \Lambda p(t_{h_{ij}} \mid p_{ij})g(p_{ij})dp_{ij} , \quad (4)$$
and $g(p_{ij})$ is a conjugate prior of distribution, which, for binomial distribution, is a Beta distribution with a pair of parameters $(\alpha_{ij}, \beta_{ij})$ [7,25] where $\alpha_{ij} > 0$ and $\beta_{ij} > 0$ are chosen to reflect any existing belief or information about $e_{ij}$. If the piece of code $e_{ij}$ has been tested $n$ times, among these tests, $e_{ij}$ has passed the test $k$ times, then, the posterior density is also a Beta distribution with the parameter $(\alpha_{ij} + k, \beta_{ij} + n - k) > 0$ which is given as
$$p(p_{ij}) = \frac{1}{B(\alpha_{ij} + k, \beta_{ij} + n - k)} p_{ij}^{k+\alpha_{ij}-1}(1-p_{ij})^{n-k+\beta_{ij}-1} , \quad (5)$$
where $B(\alpha_{ij} + k, \beta_{ij} + n - k)$ is the Beta function. Given $n$ tests with $k$ success incident, the reliability estimation for a piece of code $e_{ij}$ is the mean of $p_{ij}$ which is given by
$$R_{ij} = E(p_{ij} \mid k, n, \alpha_{ij}, \beta_{ij}) = \frac{\alpha_{ij} + k}{\alpha_{ij} + \beta_{ij} + n} . \quad (6)$$
In software testing practice, if a test does not meet the expectation, an investigation is conducted to find the defect and a fix is made. The total test and successful times is reset$^3$. Therefore, we always have $n = k = h_{ij}$. But we may adjust parameters $(\alpha_{ij}, \beta_{ij}) > 0$ after a fix is made since we gain confidence as the software matures. We can do so by increase $\alpha_{ij}$ or decreasing $\beta_{ij}$. To calculate failure probability, we simply use
$$q_{ij} = 1 - p_{ij} . \quad (7)$$
Therefore, at the end of the test stage, the software reliability can be modeled by a flow network whose structure is represented by nodes and edges, moreover, each edge has its reliability (probability of no defect) determined by the test results and is estimated by (6). Based on this observation, it becomes possible to simplify the software reliability model by repeatedly combining either serial-connected edges or parallel-connected edges into a combined artificial edge until we reduce the entire software to a single edge whose reliability is then the software reliability. In the following discussions, we present the procedures and details pertaining to the combining of parallel-connected edges or serial-connected edges into a single artificial edge; we will also provide formulae to estimate the reliability of the combined artificial edge depending on whether these edges are serial-connected or parallel-connected edges.
$^3$ Except the retest for the failed cases, each test should be created independently.
3.2 Reliability Estimation for Parallel Edge
Unlike serial edges, parallel edges exist naturally in software because of statements such as “if-else” or “case” etc. During the test stage, each edge under the same node may not be executed the same number of times and the execution time for each edge can be different. Therefore, when we combine the parallel edges into a single edge, we should weight the probability of each edge differently according to the number of execution times and average execution times (because these considerations are related to operational profile [24]). For an edge that execute more times than other edges in the test stage, we should give it a heavier weight than other edges. Similarly, for an edge that need more time to finish the execution, we should give it a heavier weight than other edges. First, for a block under node $n_i$ composed of $m_j$ parallel-connected edges, the total number of executions of all parallel-connected edges $e_{ij}$ during the test stage is
$$h_i = \sum_{j=1}^{m_j} h_{ij}$$ (8)
and the total execution time of all parallel-connected edges $e_{ij}$ under node $n_i$ during the test stage is the summation of the execution time multiplied by the number of executions of every edge, i.e.,
$$T_i = \sum_{j=1}^{m_j} T_{ij} h_{ij}.$$ (9)
Given that edge $e_{ij}$ has $h_{ij}$ executions in the test stage and each parallel edge with multiple tests follows a binomial distribution,
$$(p_{ij} + q_{ij})^{h_{ij}} = \sum_{k=0}^{h_{ij}} C_{h_{ij}}^k p_{ij}^k q_{ij}^{h_{ij}-k} = 1$$ (10)
holds for every parallel-connected edge immediately under node $n_i$. As every edge in the parallel structure has its own binomial distribution $(p_{ij} + q_{ij})^{h_{ij}}$ and its own execution time $h_{ij} T_{ij}$, the binomial distribution for the entire parallel structure which has a total execution time of $T_i$ should be a convex combination of the binomial distributions of individual edges weighted by $\frac{h_{ij} T_{ij}}{T_i}$; i.e., an edge that has longer execution time and executed more times has a larger weight, and the summation of all of the weights is $\sum_{j=1}^{m_j} \frac{h_{ij} T_{ij}}{T_i} = 1$. Therefore, the distribution of parallel edges should satisfy, considering (9) and (10), the following relationship:
$$\sum_{j=1}^{m_j} \frac{h_{ij} T_{ij}}{T_i} (p_{ij} + q_{ij})^{h_{ij}} = \sum_{j=1}^{m_j} \frac{h_{ij} T_{ij}}{T_i} = 1.$$ (11)
Hence, immediately following (11), the reliability of the block composed of the parallel-connected edges under node $n_i$ (i.e., the probability of no defect for the edges under the node $n_i$) is the event that every test has successfully passed. The probability of this event is given by
$$R_{i1} = \sum_{j=1}^{m_j} \frac{h_{ij} T_{ij}}{T_i} R_{y_j}$$ (12)
The number of executions of the combined artificial edge used in the next model reduction step is taken as the summation of the number of the executions of all of the edges in the parallel block,
$$H_{ji} = \sum_{j=1}^{i} h_{ij} \quad (13)$$
The equivalent execution time for the combined artificial edge (from the parallel block) used in the next model reduction step is
$$T_{ji} = \frac{1}{H_{ji}} \sum_{j=1}^{i} T_{ij} h_{ij} \quad (14)$$
The same method can be applied to the parallel-connected blocks, including blocks that are reduced to artificial edges.
3.3 Reliability Estimation for Serial Edge
Serial edge connection does not exist in the initial flow network or CFG. However, if a single edge is connected to a set parallel edges, after we merge the parallel edge into a single edge, it creates a connection of two serial edges. Therefore, we need to have a formula to combine the serial connected edges and be able to estimate the reliability of the combined edges. For a block under node $n_i$, composed of nodes $i_1, K, i_s$ and serial-connected edges (assume that there are no parallel-connected edges in all nodes $i_1, K, i_s$), the total number of executions of all serial-connected edges $e_{ij}$ during the test stage is $h_i = h_{ij}$ for any $i \in i_1, K, i_s$, and the total execution time of all serial-connected edges $e_{ij}$ under node $n_i$ during the test stage is the summation of the execution time multiplied by the number of executions of every edge, i.e.,
$$T_i = \sum_{i=1}^{i_1} T_{ij} h_{ij} \quad (15)$$
Given that edge $e_{ij}$ has exactly $h_{ij}$ executions in the test stage and each serial edge with multiple tests follows a binomial distribution,
$$(p_{ij} + q_{ij})^{h_{ij}} = \sum_{k=0}^{h_{ij}} C_{h_{ij}}^k p_{ij}^k q_{ij}^{h_{ij}-k} = 1 \quad (16)$$
holds for all serial-connected edges immediately under node $n_i$. For the serial-connected edges, the reliability of the entire block is the minimum of the reliabilities of the individual edges. Considering (14), the following relationship immediately holds:
---
4 For serial-connected edges, the method of [32,33] uses the product of the reliabilities of the individual edges as the reliability of the serial-connected edges. A drawback of using the product of the reliabilities of the individual edges is the inconsistence in the following scenario: if we artificially divide an edge into a set of serial-connected edges, then the reliability for the edge and the reliability for the set of serial-connected edges using formula involving the product of the reliabilities of the individual artificial edges are not consistent. But using the minimum for this scenario will lead to a consistent presentation. Another reason that a minimum is used in (18) is because when a test is successful and one of serially connected edge is in the path, all serially connected edges are in the path and all these edges pass the test.
\[
\prod_{i \in n_k} (p_{ij} + q_{ij})^{h_{ij}} = 1. \tag{17}
\]
Hence, the reliability of the block composed of serial-connected edges under the node \( n_k \) in the software (i.e., the probability of no defect for the block composed of serial-connected edges under the node \( n_k \)) is the event that every test has successfully passed. The probability of this event is given by
\[
R_{n_k} = \min(R_{ij}). \tag{18}
\]
The number of executions of the combined artificial edge used in the next model reduction step is taken as the number of executions of any edge \( h_{ij} \), where \( i \in i_s, K, i_s \), in the serial block, and
\[
H_{h_{ij}} = h_{ij}. \tag{19}
\]
The equivalent execution time for the combined artificial edge (from the serial block) used in the next model reduction step is
\[
T_{h_{ij}} = \sum_{i \in n_k} T_{ij}. \tag{20}
\]
The same method can be applied to the serial-connected blocks, including blocks that are reduced to artificial edges.
### 3.4 Overall Reliability Estimation for the Software
The overall reliability of the software is estimated as follows. First, construct the flow network as discussed in Section 2. As testing proceeds, repeatedly use (6) to update the reliability for each edge. The reliability of each edge is obtained when the test finishes. Given the reliabilities of all of the edges, one can use equations (12-14) to simplify parallel-connected edges into a single artificial edge and use equations (18-20) to simplify serial-connected edges into a single artificial edge. The software reliability is obtained by repeating the process until all of the edges are combined into a single artificial edge. We then obtain the total equivalent test time \( T \) and the software reliability \( R \). An example is used to describe the process in the next subsection.
### 3.5 An Example
The pseudo c/c++ code example introduced in Section 2 is used to demonstrate how this software reliability estimation method works. The software partitioned as in Fig. 2 (a) has five nodes and six edges. Assume also that three tests are conducted. The first test path is \( e_1e_2, e_3, e_4, \) the second test path is \( e_1e_2, e_3e_4, \) and the third test path is \( e_1e_2e_4. \) Assume further that the total test time is \( T = .00011 \) hours and \( T_y = .00001 \) hours for every edge. Therefore, \( h_{11} = h_{41} = 3, \ h_{21} = 2, \) and \( h_{22} = h_{31} = h_{32} = 1. \) Assume
\[
R_{11} = \frac{\alpha_{11} + h_{11}}{\alpha_{11} + \beta_{11} + h_{11}} = \frac{\alpha_{41} + h_{41}}{\alpha_{41} + \beta_{41} + h_{41}} = R_{41} = 0.9999999 \quad \text{for} \quad e_1 \text{ and } e_4; \]
Similarly assuming
\[
R_{31} = R_{32} = R_{22} = \frac{\alpha_{31} + h_{31}}{\alpha_{31} + \beta_{31} + h_{31}} = \frac{\alpha_{32} + h_{32}}{\alpha_{32} + \beta_{32} + h_{32}} = \frac{\alpha_{22} + h_{22}}{\alpha_{22} + \beta_{22} + h_{22}} = 0.99 \quad \text{yields, and assuming}
\]
\[
R_{21} = \frac{\alpha_{21}}{\alpha_{21} + \beta_{21}} = R_{22} = \frac{\alpha_{22}}{\alpha_{22} + \beta_{22}} = 0.99.
\]
\[ R_{21} = \frac{\alpha_{21} + h_{21}}{\alpha_{21} + \beta_{21} + h_{21}} = 0.99 \, . \]
The following steps are used to obtain the reliability, starting from the blocks that are composed of only either parallel edges or serial edges:
- First, combining \( e_{31} \) and \( e_{32} \) gives \( T_3 = h_{31}T_{31} + h_{32}T_{32} = 0.00002 \, , \quad \frac{h_{31}T_{31}}{T_3} = \frac{h_{32}T_{32}}{T_3} = \frac{1}{2} \); using (12) for the parallel edges \( e_{31} \) and \( e_{32} \), the flow network is reduced to Fig. 2 (b) with \( R_{31} = 0.99 \, . \) Using (13) and (14), we obtain \( H_{31} = \sum_{j=1}^{2} h_{3j} = 2 \, , \) and \( T_{31} = \frac{1}{2} \sum_{j=1}^{2} T_{3j} h_{3j} = 0.00001 \, . \)
- Using (18) for the serial connection \( e_{21} \) and \( E_{31} \) to obtain the combined edge, the flow network is reduced to Fig. 2 (c) with \( R_{21} = \min(0.9999, 0.99) = 0.99 \, . \) Using (19) and (20), we have \( T_{21} = \sum_{i=2}^{3} T_{i1} = 0.00002 \, , \) and \( H_{21} = h_{21} = H_{31} = 2 \, . \)
- Considering the parallel connection in Fig. 2 (c), \( T_2 = H_{21}T_{21} + h_{22}T_{22} = 0.00005 \, , \quad \frac{H_{21}T_{21}}{T_2} = \frac{4}{5} \, , \) and \( \frac{h_{22}T_{22}}{T_2} = \frac{1}{5} \, , \) and using (12) for the parallel connection \( E_{21} \) and \( e_{22} \), we
reduce Fig. 2 (c) to Fig. 2 (d) with \( R_{21} = \frac{0.99 \times 4}{5} + \frac{0.99 \times 1}{5} = 0.99 \). Using (13) and (14), we obtain \( H_{21} = \sum_{j=1}^{2} h_{2j} = 3 \) and \( T_{21} = \frac{1}{3} \sum_{j=1}^{3} T_{2j} h_{2j} = 0.00001 \times \frac{5}{3} \).
- Finally using (18) for serial connection \( e_1, E_{21}, \) and \( e_{41} \), we have
\[
R = \min(0.99, 0.99, 0.99) = 0.99.
\]
### 3.6 Software Failure Rate
For our analysis, the software failure rate can be obtained from the reliability assuming time dependency of the triggering conditions. Let \( T \) be the total test time. Let the software reliability be \( R \) during the total test time \( T \); thus, the software failure probability is \( (1 - R) \) during the total test time \( T \). Let \( t \) be some unit time of the operational period, for instance one year, of continuous operation. Therefore, for the unit time of operational period \( t \), the software failure rate is given by
\[
(1 - R) \frac{t}{T}.
\]
In some cases, the software is not always running. It is executed only on demand. In this case, we need to modify the definitions of \( T \) and \( t \) slightly. Let \( T \) be the total number of test runs and \( t \) be the number of estimated demands in a unit time of the operational period (i.e., one year). In such a case, (21) continues to hold.
### 4 AUTOMATED TOOL
It will be a tedious process if we directly apply the methods described in the previous sections without automated processes for software partition, data collection, edge reliability and total reliability estimations, as it is tedious to count and record all \( n_i \in N, e_y \in E, T_{ij}, T, \) and \( h_{ij} \) values manually; to update all \( q_{ij} \) and \( p_{ij} \) manually; and to estimate the overall software reliability manually using the model reduction method. However, with an automated tool, the estimation of the software reliability should be straightforward and free from human effort.
In many software development environments, the software structure, including the relationships between the calling and the called functions, is provided. For example, LabView provides this relationship in a tree structure. Therefore, it is possible, with some work, to develop a tool to generate the flow network structure. Some of the work has been done, for example [16], but extra work may be needed.
Also, a number of popular operating systems and software development environments, such as Microsoft Visual Studio and vxWorks, can select different modes, such as debug and release modes. Different modes compile and run the software differently. For example, if the debug mode is selected, it can record the execution time for any part of the software under the test. Therefore, techniques for determining the CPU times $T_{ij}$, $T$, and the number of executions $h_{ij}$ during the entire test stage are available.
We propose to add a test mode to the software development environment. It should have the following features:
1. When the software is compiled in the test mode, the tool should record nodes $n_i \in N$, edges $e_{ij} \in E$, and should create the flow network structure of the software.
2. When testing starts, in every test scenario run, the development environment should record the path tested. For each edge, $h_{ij}$ and average of $T_{ij}$ should be recorded, and $T$ should be accumulated.
3. Software test engineers are required to examine and accept/reject the test result. If the engineer accepts the test result, the development environment should update $q_{ij}$ and $p_{ij}$, according to (6-7).
4. If a software defect is identified in edge $e_{ij}$, the defect should be fixed. For all edges $e_{ij}$ involved in the fix (they may belong to different threads), $h_{ij}$ and $T_{ij}$ should be reset to zero, after which the test will continue and all edge reliability estimation processes will be updated for $q_{ij}$ and $p_{ij}$ using (6-7) as before.
5. When all testing is complete, estimate the software reliability according to (12-14) and (18-20) use the procedure presented in Sections 3.2-3.4.
6. To improve the reliability of the software, the edges tested least should undergo more tests. Therefore, the information on these edges should be provided.
7. The information on the software reliability should be kept in the release mode. It should be available for reading if a request is made.
In summary, an automated tool in the software development environment is desirable, and it should have the features listed above to facilitate software reliability estimation. We believe, with some extra effort on top of the existing software development environment, that software development tool vendors should be able to provide all of the information to assess software reliability using the proposed method.
5 CONCLUSIONS
In this paper, we proposed a systematic and probabilistic method to estimate software reliability. The method is rigorously based on test data, flow network, binomial distribution, and Bayesian estimations rather than a subjective judgement. For any components or system involving both hardware and software, the reliability estimation has been discussed in [33].
6 REFERENCES
|
{"Source-Url": "https://www.nrc.gov/docs/ML1835/ML18353A961.pdf", "len_cl100k_base": 8890, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 40005, "total-output-tokens": 11837, "length": "2e13", "weborganizer": {"__label__adult": 0.00036454200744628906, "__label__art_design": 0.00031280517578125, "__label__crime_law": 0.00039267539978027344, "__label__education_jobs": 0.0006628036499023438, "__label__entertainment": 7.617473602294922e-05, "__label__fashion_beauty": 0.0001512765884399414, "__label__finance_business": 0.0002999305725097656, "__label__food_dining": 0.0004222393035888672, "__label__games": 0.0007486343383789062, "__label__hardware": 0.0013666152954101562, "__label__health": 0.0007648468017578125, "__label__history": 0.0002834796905517578, "__label__home_hobbies": 0.00011408329010009766, "__label__industrial": 0.0005908012390136719, "__label__literature": 0.00028014183044433594, "__label__politics": 0.00020205974578857425, "__label__religion": 0.00037384033203125, "__label__science_tech": 0.06451416015625, "__label__social_life": 8.469820022583008e-05, "__label__software": 0.007720947265625, "__label__software_dev": 0.9189453125, "__label__sports_fitness": 0.0003135204315185547, "__label__transportation": 0.0006279945373535156, "__label__travel": 0.00022029876708984375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42332, 0.03278]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42332, 0.71225]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42332, 0.87993]], "google_gemma-3-12b-it_contains_pii": [[0, 2957, false], [2957, 6630, null], [6630, 10666, null], [10666, 11023, null], [11023, 14492, null], [14492, 17605, null], [17605, 21003, null], [21003, 23785, null], [23785, 26722, null], [26722, 29792, null], [29792, 31109, null], [31109, 33506, null], [33506, 36344, null], [36344, 39666, null], [39666, 42332, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2957, true], [2957, 6630, null], [6630, 10666, null], [10666, 11023, null], [11023, 14492, null], [14492, 17605, null], [17605, 21003, null], [21003, 23785, null], [23785, 26722, null], [26722, 29792, null], [29792, 31109, null], [31109, 33506, null], [33506, 36344, null], [36344, 39666, null], [39666, 42332, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42332, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42332, null]], "pdf_page_numbers": [[0, 2957, 1], [2957, 6630, 2], [6630, 10666, 3], [10666, 11023, 4], [11023, 14492, 5], [14492, 17605, 6], [17605, 21003, 7], [21003, 23785, 8], [23785, 26722, 9], [26722, 29792, 10], [29792, 31109, 11], [31109, 33506, 12], [33506, 36344, 13], [36344, 39666, 14], [39666, 42332, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42332, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
da889cb7518220392fcf6b21fe42eb25bb2da305
|
HPC User Environment 2
Feng Chen
HPC User Services
LSU HPC & LONI
sys-help@loni.org
Louisiana State University
Baton Rouge
June 14, 2017
Outline
- Review HPC User Environment 1 topics
- Available HPC resources
- Accounts and Allocations
- Cluster architecture
- Connect to clusters
- Software management using softenv and module
- Things to be covered in this training
- Job management
- Interactive vs Batch jobs
- Submit and monitor your jobs
- Understanding Job scheduling
- Job priority
- Backfill
- Compiling and analyze codes on cluster
- Serial program
- Parallel program
Brief Review of Session 1
HPC User Environment 2
Inside A QB2 Compute Node (Dell C8000)
- Accelerator 1 (GPU)
- Accelerator 2 (GPU)
- Storage
- Processor
- Processor
- Network Card
- Memory
Conceptual Relationship
Cluster
Compute Node
CPUs
GPUs
Memory
HPC User Environment 2 Summer 2017
# Cluster Nomenclature
<table>
<thead>
<tr>
<th>Term</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cluster</td>
<td>The top-level organizational unit of an HPC cluster, comprising a set of nodes, a queue, and jobs.</td>
</tr>
<tr>
<td>Node</td>
<td>A single, named host machine in the cluster.</td>
</tr>
<tr>
<td>Core</td>
<td>The basic computation unit of the CPU. For example, a quad-core processor is considered 4 cores.</td>
</tr>
<tr>
<td>Job</td>
<td>A user's request to use a certain amount of resources for a certain amount of time on cluster for his work.</td>
</tr>
</tbody>
</table>
HPC Cluster Architectures
- **Major architecture**
- Intel x86_64 clusters
- Vendor: Dell
- Operating System: Linux (RHEL 4/5/6)
- Processor: Intel
Accessing cluster using ssh (Secure Shell)
- **On Unix and Mac**
- use ssh on a terminal to connect
- **Windows box (ssh client):**
- Putty, Cygwin ([http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html))
- `ssh username@mike.hpc.lsu.edu`
- **Host name**
- LONI: `<cluster_name>.loni.org`
- `<cluster_name>` can be:
- `eric.loni.org`
- `qb.loni.org`
- LSU HPC: `<cluster_name>.hpc.lsu.edu`
- `<cluster_name>` can be:
- `mike.hpc.lsu.edu`
- `smic.hpc.lsu.edu`
- `philip.hpc.lsu.edu`
HPC User Environment 2
Review Questions for Section 1
Access to cluster
- How do I connect to HPC/LONI cluster?
a) By logging onto HPC webpage at www.hpc.lsu.edu
b) Using an ssh (secure shell) client such as Putty
c) Go to the machine room in ISB in downtown Baton Rouge and connect my laptop to the nodes using a cable 😊
Software Management
- How do we manage the software installed on HPC/LONI clusters?
- Using softenv/modules
- Using a drop down menu on the www.hpc.lsu.edu webpage
Account and Allocation Policy
➢ Who can apply for allocations?
a) Graduate student
b) PostDoc
c) Full time faculty
d) All of the above
Account Security
How to get your account suspended?
a) Give your password to your friend/lab colleagues and let him/her use it.
b) Give your password to your advisor so he/she can use your account to see your data.
c) Run my simulation on the login node.
d) All of the above
More on Job Queues
Cluster Environment
- Multiple compute nodes
- Multiple users
- Each user may have multiple jobs running simultaneously
- Multiple users may share the same node
Job submission basics
1. Find appropriate queue
2. Understand the queuing system and your requirements and proceed to submit jobs
3. Monitor jobs during execution
Job Queues
- Nodes are organized into queues. Nodes can be shared.
- Each job queue differs in
- Number of available nodes
- Max run time
- Max running jobs per user
- Nodes may have special characteristics: GPU/Xeon Phi’s, Large memory, etc.
- Jobs need to specify resource requirements
- Nodes, time, queue
- It’s called a queue for a reason, but jobs don’t run on a “First Come First Served” policy,
- This will be detailed in later slides
## Queue Characteristics – LONI clusters
<table>
<thead>
<tr>
<th>Machine</th>
<th>Queue</th>
<th>Max Runtime</th>
<th>ppn</th>
<th>Max running jobs</th>
<th>Max nodes per job</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr>
<td>Eric</td>
<td>workq</td>
<td>3 days</td>
<td>8</td>
<td>16</td>
<td>24</td>
<td>Unpreemptable</td>
</tr>
<tr>
<td></td>
<td>checkpoint</td>
<td></td>
<td>8</td>
<td></td>
<td>48</td>
<td>Preemptable</td>
</tr>
<tr>
<td></td>
<td>single</td>
<td></td>
<td>1</td>
<td>32</td>
<td>1</td>
<td>ppn=1/2/4/6/8</td>
</tr>
<tr>
<td>QB2</td>
<td>workq</td>
<td>3 days</td>
<td>20</td>
<td>128</td>
<td></td>
<td>Unpreemptable</td>
</tr>
<tr>
<td></td>
<td>checkpoint</td>
<td></td>
<td>20</td>
<td></td>
<td>256</td>
<td>Preemptable</td>
</tr>
<tr>
<td></td>
<td>single</td>
<td>7 days</td>
<td>1,2,4,6,8</td>
<td>1</td>
<td></td>
<td>Single node jobs</td>
</tr>
</tbody>
</table>
# Queue Characteristics – LSU Linux clusters
<table>
<thead>
<tr>
<th>Machine</th>
<th>Queue</th>
<th>Max Runtime</th>
<th>ppn</th>
<th>Max running jobs</th>
<th>Max nodes per job</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr>
<td>SuperMike II</td>
<td>workq</td>
<td>3 days</td>
<td>16</td>
<td></td>
<td>128</td>
<td>Unpreemptable</td>
</tr>
<tr>
<td></td>
<td>checkpt</td>
<td>3 days</td>
<td>16</td>
<td></td>
<td>128</td>
<td>Preemptable</td>
</tr>
<tr>
<td></td>
<td>bigmem</td>
<td>2 days</td>
<td>16</td>
<td>34</td>
<td>16</td>
<td>Job using GPU</td>
</tr>
<tr>
<td></td>
<td>gpu</td>
<td>3 days</td>
<td>16</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>single</td>
<td>3 days</td>
<td>1,2,4,8</td>
<td></td>
<td>1</td>
<td>Single node jobs</td>
</tr>
<tr>
<td>Philip</td>
<td>workq</td>
<td>3 days</td>
<td>8</td>
<td>5</td>
<td>4</td>
<td>Unpreemptable</td>
</tr>
<tr>
<td></td>
<td>checkpt</td>
<td>3 days</td>
<td>8</td>
<td></td>
<td>4</td>
<td>Preemptable</td>
</tr>
<tr>
<td></td>
<td>bigmem</td>
<td>8</td>
<td>8</td>
<td></td>
<td>2</td>
<td>Big memory</td>
</tr>
<tr>
<td></td>
<td>single</td>
<td>14 days</td>
<td>4</td>
<td>50</td>
<td>1</td>
<td>Single processor</td>
</tr>
<tr>
<td>SuperMIC</td>
<td>workq</td>
<td>3 days</td>
<td>20</td>
<td>34</td>
<td>128</td>
<td>Unpreemptable</td>
</tr>
<tr>
<td></td>
<td>checkpt</td>
<td>3 days</td>
<td>20</td>
<td></td>
<td>360</td>
<td>Preemptable</td>
</tr>
</tbody>
</table>
Queue Characteristics
- “qstat -q” will give you more info on the queues
[fchen14@mike2 ~]$ qstat -q
server: mike3
<table>
<thead>
<tr>
<th>Queue</th>
<th>Memory</th>
<th>CPU</th>
<th>Time</th>
<th>Walltime</th>
<th>Node</th>
<th>Run</th>
<th>Que</th>
<th>Lm</th>
<th>State</th>
</tr>
</thead>
<tbody>
<tr>
<td>workq</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>128</td>
<td>31</td>
<td>6</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>mwfa</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>8</td>
<td>3</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>bigmem</td>
<td>--</td>
<td>--</td>
<td>48:00:00</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>lasigma</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>28</td>
<td>28</td>
<td>7</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>bigmemtb</td>
<td>--</td>
<td>--</td>
<td>48:00:00</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>priority</td>
<td>--</td>
<td>--</td>
<td>168:00:00</td>
<td>128</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>single</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>1</td>
<td>62</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>gpu</td>
<td>--</td>
<td>--</td>
<td>24:00:00</td>
<td>16</td>
<td>1</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>preempt</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>--</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>checkpoint</td>
<td>--</td>
<td>--</td>
<td>72:00:00</td>
<td>128</td>
<td>31</td>
<td>137</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>admin</td>
<td>--</td>
<td>--</td>
<td>24:00:00</td>
<td>--</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
<tr>
<td>scalemp</td>
<td>--</td>
<td>--</td>
<td>24:00:00</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>--</td>
<td></td>
<td>E R</td>
</tr>
</tbody>
</table>
- For a more detailed description use mdiag
156 150
Queue Querying – Linux Clusters
- Displays information about active, eligible, blocked, and/or recently completed jobs: `showq` command
```
$ showq
active jobs------------------------
<table>
<thead>
<tr>
<th>JOBID</th>
<th>USERNAME</th>
<th>STATE</th>
<th>PROCS</th>
<th>REMAINING</th>
<th>STARTTIME</th>
</tr>
</thead>
<tbody>
<tr>
<td>236875</td>
<td>ebeigi3</td>
<td>Running</td>
<td>16</td>
<td>1:44:29</td>
<td>Mon Sep 15 20:00:22</td>
</tr>
<tr>
<td>236934</td>
<td>mwu3</td>
<td>Running</td>
<td>16</td>
<td>00:03:27</td>
<td>Mon Sep 15 19:04:20</td>
</tr>
</tbody>
</table>
... eligible jobs----------------------
<table>
<thead>
<tr>
<th>JOBID</th>
<th>USERNAME</th>
<th>STATE</th>
<th>PROCS</th>
<th>WCLIMIT</th>
<th>QUEUETIME</th>
</tr>
</thead>
<tbody>
<tr>
<td>236795</td>
<td>dmarce1</td>
<td>Idle</td>
<td>1456</td>
<td>00:15:00</td>
<td>Mon Sep 15 16:38:45</td>
</tr>
<tr>
<td>236753</td>
<td>rsmith</td>
<td>Idle</td>
<td>2000</td>
<td>4:00:00</td>
<td>Mon Sep 15 14:44:52</td>
</tr>
<tr>
<td>236862</td>
<td>dlamas1</td>
<td>Idle</td>
<td>576</td>
<td>2:00:00</td>
<td>Mon Sep 15 17:28:57</td>
</tr>
</tbody>
</table>
121 eligible jobs
blocked jobs----------------------
<table>
<thead>
<tr>
<th>JOBID</th>
<th>USERNAME</th>
<th>STATE</th>
<th>PROCS</th>
<th>WCLIMIT</th>
<th>QUEUETIME</th>
</tr>
</thead>
<tbody>
<tr>
<td>232741</td>
<td>myagho1</td>
<td>Idle</td>
<td>2000</td>
<td>1:00:00:00</td>
<td>Mon Sep 8 07:22:12</td>
</tr>
<tr>
<td>235545</td>
<td>tanping</td>
<td>Idle</td>
<td>1</td>
<td>2:21:10:00</td>
<td>Fri Sep 12 16:50:49</td>
</tr>
<tr>
<td>235546</td>
<td>tanping</td>
<td>Idle</td>
<td>1</td>
<td>2:21:10:00</td>
<td>Fri Sep 12 16:50:50</td>
</tr>
</tbody>
</table>
...
Submit and Monitor Your Jobs
Two Job Types
- **Interactive job**
- Set up an interactive environment on compute nodes for users
- Advantage: can run programs interactively
- Disadvantage: must be present when the job starts
- Purpose: testing and debugging, compiling
- Do not run on the head node!!!
- Try not to run interactive jobs with large core count, which is a waste of resources
- **Batch job**
- Executed without user intervention using a job script
- Advantage: the system takes care of everything
- Disadvantage: can only execute one sequence of commands which cannot changed after submission
- Purpose: production run
Submitting Jobs on Linux Clusters
- **Interactive job example:**
```
qsub -I -X -V \
-l walltime=<hh:mm:ss>,nodes=<num_nodes>:ppn=<num_cores> \
-A <Allocation> \
-q <queue name>
```
**DO NOT directly ssh to compute nodes, unless the nodes are assigned to you by the job scheduler.**
- Add `-X` to enable X11 forwarding
- **Batch Job example:**
```
qsub job_script
```
Check Your Available Allocations
[fchen14@mike2 ~]$ balance
============= Allocation information for fchen14 =============
<table>
<thead>
<tr>
<th>Proj. Name</th>
<th>Alloc</th>
<th>Balance</th>
<th>Deposited</th>
<th>%Used</th>
<th>Days Left</th>
<th>End</th>
</tr>
</thead>
<tbody>
<tr>
<td>hpc_hpcadmin3</td>
<td>282854.91</td>
<td>350000.00</td>
<td>19.18</td>
<td>16</td>
<td>2017-06-30</td>
<td></td>
</tr>
<tr>
<td>hpc_trn17mike2</td>
<td>20305.62</td>
<td>25000.00</td>
<td>18.78</td>
<td>291</td>
<td>2018-04-01</td>
<td></td>
</tr>
</tbody>
</table>
Note: Balance and Deposit are measured in CPU-hours
[fchen14@mike2 ~]$ showquota
Hard disk quotas for user fchen14 (uid 32584):
<table>
<thead>
<tr>
<th>Filesystem</th>
<th>MB used</th>
<th>quota</th>
<th>files</th>
<th>fquota</th>
</tr>
</thead>
<tbody>
<tr>
<td>/homem</td>
<td>4518</td>
<td>5000</td>
<td>94354</td>
<td>0</td>
</tr>
<tr>
<td>/work</td>
<td>424228</td>
<td>0</td>
<td>286002</td>
<td>400000</td>
</tr>
<tr>
<td>/project</td>
<td>65346</td>
<td>100000</td>
<td>1119432</td>
<td>400000</td>
</tr>
</tbody>
</table>
CPU Allocation SUs remaining:
hpc_hpcadmin3: 282854.91
hpc_trn17mike2: 20305.62
Submit An Interactive Job on SuperMike2
[fchen14@mike1 ~]$ qsub -I -X -l nodes=1:ppn=16,walltime=2:00:00 -q workq -A hpc_trn17mike2
qsub: waiting for job 675733.mike3 to start
qsub: job 675733.mike3 ready
Running PBS prologue script
...
Job ID: 675733.mike3
Username: fchen14
Group: Admins
Date: 13-Jun-2017 15:34
Node: mike044 (62703)
PBS has allocated the following nodes:
mike044
A total of 16 processors on 1 nodes allocated
Concluding PBS prologue script - 13-Jun-2017 15:34:19
[fchen14@mike044 ~]$
PBS Job Script – Serial Job
```bash
#!/bin/bash
#PBS -l nodes=1:ppn=1 # Number of nodes and processor
#PBS -l walltime=24:00:00 # Maximum wall time
#PBS -N myjob # Job name
#PBS -o <file name> # File name for standard output
#PBS -e <file name> # File name for standard error
#PBS -q single # The queue for serial jobs
#PBS -A <loni_allocation> # Allocation name
#PBS -m e # Send mail when job ends
#PBS -M <email address> # Send mail to this address
<shell commands>
<path_to_executable> <options>
<shell commands>
```
Tells the job scheduler how much resource you need.
How will you use the resources?
PBS Job Script – Parallel Job
#!/bin/bash
#PBS -l nodes=2:ppn=16 #Number of nodes and processors per node
#PBS -l walltime=24:00:00 #Maximum wall time
#PBS -N myjob #Job name
#PBS -o <file name> #File name for standard output
#PBS -e <file name> #File name for standard error
#PBS -q checkpt #Queue name
#PBS -A <allocation_if_needed> #Allocation name
#PBS -m e #Send mail when job ends
#PBS -M <email address> #Send mail to this address
<shell commands>
mpirun -machinefile $PBS_NODEFILE -np 32 <path_to_executable> <options>
<shell commands>
Tells the scheduler how much resource you need.
How will you use the resources?
True or False?
- I have the below job script on QB2, since I used nodes=2:ppn=20, my script will run in parallel using 2 nodes with 40 cores.
a) True
b) False
```bash
#!/bin/bash
#PBS -l nodes=2:ppn=20
#PBS -l walltime=24:00:00
#PBS -N myjob
#PBS -j oe
#PBS -q checkpt
#PBS -A my_allocation
./my_executable.out
```
Job Monitoring - Linux Clusters
- Check details on your job using **qstat**
$ qstat -n -u $USER : For quick look at nodes assigned to you
$ qstat -f jobid : For details on your job
- Check approximate start time using **showstart**
$ showstart jobid
- Check details of your job using **checkjob**
$ checkjob jobid
- Check health of your job using **qshow**
$ qshow jobid
- Please pay close attention to the load and the memory consumed by your job!
Using the “top” command
- The top program provides a dynamic real-time view of a running system.
```plaintext
top - 19:39:56 up 89 days, 4:13, 1 user, load average: 0.63, 0.18, 0.06
Tasks: 489 total, 2 running, 487 sleeping, 0 stopped, 0 zombie
Cpu(s): 6.3%us, 0.0%sy, 0.0%ni, 93.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 65909356k total, 3389616k used, 62519740k free, 151460k buffers
Swap: 207618040k total, 5608k used, 207612432k free, 947716k cached
<table>
<thead>
<tr>
<th>PID</th>
<th>USER</th>
<th>PR</th>
<th>NI</th>
<th>VIRT</th>
<th>RES</th>
<th>SHR</th>
<th>S</th>
<th>%CPU</th>
<th>%MEM</th>
<th>TIME+</th>
<th>COMMAND</th>
</tr>
</thead>
<tbody>
<tr>
<td>39595</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>266m</td>
<td>257m</td>
<td>592</td>
<td>R</td>
<td>99.9</td>
<td>0.4</td>
<td>0:06.94</td>
<td>a.out</td>
</tr>
<tr>
<td>39589</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>17576</td>
<td>1812</td>
<td>980</td>
<td>R</td>
<td>0.3</td>
<td>0.0</td>
<td>0:00.05</td>
<td>top</td>
</tr>
<tr>
<td>38479</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>108m</td>
<td>2156</td>
<td>1348</td>
<td>S</td>
<td>0.0</td>
<td>0.0</td>
<td>0:00.03</td>
<td>bash</td>
</tr>
<tr>
<td>39253</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>103m</td>
<td>1340</td>
<td>1076</td>
<td>S</td>
<td>0.0</td>
<td>0.0</td>
<td>0:00.00</td>
<td>236297.mike3.SC</td>
</tr>
<tr>
<td>39254</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>103m</td>
<td>1324</td>
<td>1060</td>
<td>S</td>
<td>0.0</td>
<td>0.0</td>
<td>0:00.00</td>
<td>bm_laplace.sh</td>
</tr>
<tr>
<td>39264</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>99836</td>
<td>1908</td>
<td>992</td>
<td>S</td>
<td>0.0</td>
<td>0.0</td>
<td>0:00.00</td>
<td>sshd</td>
</tr>
<tr>
<td>39265</td>
<td>fchen14</td>
<td>20</td>
<td>0</td>
<td>108m</td>
<td>3056</td>
<td>1496</td>
<td>S</td>
<td>0.0</td>
<td>0.0</td>
<td>0:00.03</td>
<td>bash</td>
</tr>
</tbody>
</table>
```
PBS Environmental Variables
[fchen14@mike315 ~]$ echo $PBS_
$PBS_ENVIRONMENT $PBS_MOMPORT $PBS_NUM_PPN $PBS_O_MAIL
$PBS_QUEUE $PBS_WALLTIME $PBS_GPUFILE $PBS_NODEFILE
$PBS_O_HOME $PBS_O_PATH $PBS_SERVER $PBS_JOBCOOKIE
$PBS_NODENUM $PBS_O_HOST $PBS_O_QUEUE $PBS_TASKNUM
$PBS_JOBID $PBS_NP $PBS_O_LANG $PBS_O_SHELL
$PBS_VERSION $PBS_JOBNAME $PBS_NUM_NODES $PBS_O_LOGNAME
$PBS_O_WORKDIR $PBS_VNODENUM
Pay attention to single queue usage
- Single queue - Used for jobs that will only execute on a single node, i.e. `nodes=1:ppn=1/2/4/6/8`.
- Jobs in the single queue should not use:
- More than 2GB memory per core for Eric, Philip and SuperMike2 (32G/16).
- More than 3.2GB memory per core for QB2 (64G/20).
- If applications require more memory, scale the number of cores (ppn) to the amount of memory required: i.e. max memory available for jobs in single queue is 8GB for ppn=4 on SuperMikeII.
- Typical type of warning:
- E124 - Exceeded memory allocation. This Job XXXX appears to be using more memory (GB) than allocated (9 > 3).
- E123 - Exceeded ppn/core allocation. This Job XXXX appears to be using more cores than allocated (6 > 1). Please allocate the number of cores that the job will use, (ppn=6). This Job has 1 core(s) allocated (ppn=1).
Core and Memory in Single queue
20 cores
64GB memory
64/20 = 3.2GB
**Question:**
On QB2, if my job needs 7GB memory, what ppn value should I use?
On SuperMike2, if my job needs 7GB memory, what ppn value should I use?
More things to be noticed
- Eric is old and will be retired in the near future LONI users are encouraged to migrate their codes to QB-2 as soon as possible.
- The purpose of bigmem queue on QB-2 is for jobs costing big (larger than 64 GB) memory not for jobs using more number of cores.
- GPU is available to workq or checkpt queues on QB2.
- Xeon Phi is available to workq or checkpt queues on SuperMIC.
- There is no single queue on SuperMIC.
- Users are encouraged to use accelerators (GPU/Xeon Phi) whenever possible. Application for allocation involving with usage of accelerators will be easier to be approved.
Job Submission Quiz
- **How to suspend your account? (cont’d)**
- Use more memory than allowed. (e.g. use 5GB memory on SuperMike2 with ppn=1)
- Seriously underutilize node resources (e.g. allocate 32 nodes but just use 1 core)
- Submit job to the big memory queue but use only few MB of memory
- **How to monitor core and memory usage?**
Job Scheduling Basics
As a user, you interact with the scheduler and/or resource manager whenever you submit a job, or query on the status of your jobs or the whole cluster, or seek to manage your jobs.
Resource managers give access to compute resource
- Takes in a resource request (job) on login node
- Finds appropriate resource and assigns you a priority number
- Positions your job in a queue based on the priority assigned.
- Starts running jobs until it cannot run more jobs with what is available.
Job Scheduler
- HPC & LONI Linux clusters use TORQUE, an open source version of the **Portable Batch System (PBS)** together with the MOAB Scheduler, to manage user jobs.
- **Resource Manager - Torque**
- Manages a queue of jobs for a cluster of resources
- Launches job to a simple FIFO job queue
- **Workload Manager - Moab**
- A scheduler that integrates with one or more Resource Managers to schedule jobs across domains of resources (servers, storage, applications)
- Prioritizes jobs
- Provides status of running and queued jobs, etc.
- **The batch queuing system determines**
- The order jobs are executed
- On which node(s) jobs are executed
Job management philosophy
- **Working Philosophy**
- Prioritize workload into a queue for jobs
- **Backfill** idle nodes to maximize utilization
- Will be detailed later...
Job Priorities
- Jobs with a higher job priority are scheduled ahead of jobs with a lower priority.
- Job priorities have contributions from the following:
- credential priority
- fairshare priority
- resource priority
- service priority
- Priority determination for each queued job, use
• mdiag -p:
```shell
$ mdiag -p
```
```
diagnosing job priority information (partition: ALL)
Job PRIORITY* Cred( User:Class) FS( User: WCA) Serv(QTime:XFctr) Res( Proc)
Weights------- 100( 10: 10) 100( 10: 50) 2( 2: 20) 30( 10)
236172 246376 40.6(100.0: 0.0) 8.6( 19.6: 0.3) 4.0(1480.: 99.7) 46.8(2048.)
235440 242365 41.3(100.0: 0.0) 4.6( 8.2: 0.6) 6.6(3959.: 6.5) 47.5(512.0)
235441 242365 41.3(100.0: 0.0) 4.6( 8.2: 0.6) 6.6(3959.: 6.5) 47.5(512.0)
235442 242361 41.3(100.0: 0.0) 4.6( 8.2: 0.6) 6.6(3958.: 6.5) 47.5(512.0)
236396 241821 41.4(100.0: 0.0) 8.8( 19.6: 0.3) 2.2(664.0: 67.4) 47.6(1456.)
```
Priority components
- **Credential priority** = credweight * (userweight * job.user.priority)
= 100 * (10 * 100) = 100000
It is a constant for all users.
- **Fairshare priority** = fsweight * min (fscap, (fsuserweight * DeltaUserFSUsage))
= 100 * (10 * DeltaUserFSUsage)
If you have not submitted jobs in the past 7 days, DeltaUserFSUsage = 20000
- **Service priority** = serviceweight * (queuetimeweight * QUEUETIME + xfactorweight * XFACTOR )
= 2 * (2 * QUEUETIME + 20 * XFACTOR ),
where XFACTOR = 1 + QUEUETIME / WALLTIMELIMIT.
- **Resource priority** = resweight * min (rescap, (procweight * TotalProcessorsRequested))
= 30 * min (3840, (10 * TotalProcessorsRequested))
- See [http://www.hpc.lsu.edu/docs/pbs.php](http://www.hpc.lsu.edu/docs/pbs.php) , click “Job priority”.
02/08/2017
HPC User Environment 2 Summer 2017
43
How to get higher priority?
- Do not submit too many jobs within one week.
- Submit your job early to accumulate the queue time.
- **More on resource priority:**
- Request more compute nodes.
- Request a smaller walltime limit.
- see next few slides...
How to maximize the usage of a cluster?
- Fill in high-priority (large) jobs
- Backfill low-priority (small) jobs
An Overview of Backfilling (1)
- Backfill is a scheduling optimization that allows a scheduler to make better use of available resources by running jobs out of order.
- Enabling backfill allows the scheduler to start other, lower-priority jobs so long as they do not delay the highest priority job.
- If the FIRSTFIT algorithm is applied, the following steps are taken:
- The list of feasible backfill jobs is filtered, selecting only those that will actually fit in the current backfill window.
- The first job is started.
- While backfill jobs and idle resources remain, repeat step 1.
An Overview of Backfilling (2)
- Although by default the start time of the highest priority job is protected by a reservation, there is nothing to prevent the third priority job from starting early and possibly delaying the start of the second priority job.
- Command to show current backfill windows:
- `showbf`
- Shows what resources are available for immediate use.
- This command can be used by any user to find out how many processors are available for immediate use on the system. It is anticipated that users will use this information to submit jobs that meet these criteria and thus obtain quick job turnaround times.
- Example:
```
[fchen14@eric2 ~]$ showbf -c workq
Partition Tasks Nodes Duration StartOffset StartDate
--------- ----- ----- ------------- -------------- --------------
ALL 40 5 18:50:35 00:00:00 11:16:49_09/04
ALL 8 1 INFINITY 00:00:00 11:16:49_09/04
```
How Much Time Should I Ask for?
- **It should be**
- Long enough for your job to complete
- As short as possible to increase the chance of backfilling
Frequently Asked Questions
- I submitted job A before job B. Why job B started earlier than job A?
- There are free nodes available, why my job is still waiting and not running?
- Why my job is not get accelerated when running on cluster?
- Is your job utilizing the parallel resource on the cluster?
- Does your job have lots of I/O tasks?
- See next section...
HPC User Environment 2
Compile and Analyze Codes on Cluster
Compilers
- Serial compilers
<table>
<thead>
<tr>
<th>Language</th>
<th>Linux cluster</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fortran</td>
<td>ifort, pgf77, pgf90, gfortran</td>
</tr>
<tr>
<td>C</td>
<td>icc, pgcc, gcc</td>
</tr>
<tr>
<td>C++</td>
<td>icpc, pgCC, g++</td>
</tr>
</tbody>
</table>
- Parallel compilers
<table>
<thead>
<tr>
<th>Language</th>
<th>Linux clusters</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fortran</td>
<td>mpif77, mpif90</td>
</tr>
<tr>
<td>C</td>
<td>mpicc</td>
</tr>
<tr>
<td>C++</td>
<td>mpiCC</td>
</tr>
</tbody>
</table>
Example compiling serial code
- `icc hello_cpu_elapsed.c`
- `gfortran test_hello2.f90`
- **List symbols for executables:**
`nm` - list symbols from object files
**Example:**
```
[fchen14@mike2 hello]$ nm ./a.out | grep intel
000000000060eb60 B __intel_cpu_indicator
[fchen14@mike2 hello]$ nm ./a.out | grep gfortran
U __gfortran_set_args@@GFORTTRAN_1.0
```
CPU time vs Elapsed time
- **CPU time (or process time):**
- The amount of time for which a central processing unit (CPU) was used for processing instructions of a computer program or operating system, as opposed to, for example, waiting for input/output (I/O) operations or entering low-power (idle) mode.
- **Elapsed real time (or simply real time, or wall clock time):**
- The time taken from the start of a computer program until the end as measured by an ordinary clock. Elapsed real time includes I/O time and all other types of waits incurred by the program.
- **If a program uses parallel processing, total CPU time for that program would be more than its elapsed real time.**
- \((\text{Total CPU time})/(\text{Number of CPUs})\) would be same as elapsed real time if work load is evenly distributed on each CPU and no wait is involved for I/O or other resources.
Compiling and Analyzing C serial program
```c
#include <stdio.h>
#include <time.h>
int main(char *argc, char **argv) {
double s=0.0;
// fundamental arithmetic type representing clock tick counts.
clock_t start, end;
int i;
start = clock();
for (i=0;i<1000000000;i++)
s+=i*2.0; // doing some floating point operations
end = clock();
double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
printf("cputime_in_sec: %e\n", time_elapsed_in_seconds);
start = clock();
system("sleep 5"); // just sleep, does this accumulate CPU time?
end = clock();
time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
printf("cputime_in_sec: %e\n", time_elapsed_in_seconds);
return 0;
}
Watch the actual cpu time using “time”
[fchen14@mike429 serial]$ gcc hello_cpu_elapsed.c
[fchen14@mike429 serial]$ time ./a.out
cputime_in_sec: 2.740000e+00
cputime_in_sec: 0.000000e+00
real 0m7.782s
user 0m2.750s
sys 0m0.005s
Some additional info about “time”
- **Use the Linux command `time` to evaluate the actual time usage**
- time a simple command or give resource usage
- **Real refers to actual elapsed time (wall clock time)**
- Time from start to finish of the call. This is all elapsed time including time used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).
- **User and Sys refer to CPU time used only by the process.**
- User is the amount of CPU time spent in user-mode code (outside the kernel) within the process.
- Sys is the amount of CPU time spent in the kernel within the process.
- **Purpose of this example:**
- real < user: The process is CPU bound and takes advantage of parallel execution on multiple cores/CPUs.
- real ≈ user: The process is CPU bound and takes no advantage of parallel execution.
- real > user: The process is I/O bound. Execution on multiple cores would be of little to no advantage.
Two parallel schemes
- **Shared Memory system**
- A single multicore compute node
- Open Multi-processing (OpenMP)
- **Distributed Memory system**
- Multiple compute nodes
- Message Passing Interface (MPI)
**MPI**: Distributed Memory System
**OpenMP**: Shared Memory System
Typically less memory overhead/duplication. Communication often implicit, through cache coherency and runtime.
Example compiling threaded OpenMP code
- Compiling OpenMP code often requires the `openmp` compiler flags, it varies with different compiler
- Environment Variable `OMP_NUM_THREADS` sets the number of threads
- Examples:
```
[fchen14@mike2 src] $ gcc -fopenmp hello_openmp.c
[fchen14@mike2 src] $ ifort -openmp hello_openmp.f90
```
<table>
<thead>
<tr>
<th>Compiler</th>
<th>Compiler Options</th>
<th>Default behavior for # of threads (OMP_NUM_THREADS not set)</th>
</tr>
</thead>
<tbody>
<tr>
<td>GNU (gcc, g++, gfortran)</td>
<td>-fopenmp</td>
<td>as many threads as available cores</td>
</tr>
<tr>
<td>Intel (icc ifort)</td>
<td>-openmp</td>
<td>as many threads as available cores</td>
</tr>
<tr>
<td>Portland Group (pgcc,pgCC,pgf77,pgf90)</td>
<td>-mp</td>
<td>one thread</td>
</tr>
</tbody>
</table>
Sample OpenMP C code
```c
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int nthreads, tid;
/* Fork a team of threads with their own copies of variables */
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0) {
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
} /* All threads join master thread and disband */
}
```
Sample OpenMP Fortran code
```fortran
program hello
integer nthreads, tid, omp_get_num_threads, omp_get_thread_num
!
!
! fork a team of threads giving them their own copies of variables
!$omp parallel private(nthreads, tid)
!
! obtain thread number
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
02/08/2017 HPC User Environment 2 Summer 2017 60
Analyzing a parallel (OpenMP) program
What will be the CPU time and elapsed time for the following code segment:
See (on SuperMike II):
/home/fchen14/userenv/src/openmp/hello_openmp_cpu_elapse.c
// fundamental arithmetic type representing clock tick counts.
clock_t start, end;
struct timeval r_start, r_end;
int i;
gettimeofday(&r_start, NULL);
start = clock();
#pragma omp parallel for // spawn the openmp threads
for (i=0; i<N; i++) a = i*2.0; // doing some floating point operations
end = clock();
gettimeofday(&r_end, NULL);
double cputime_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
double realtime_elapsed_in_seconds = ((r_end.tv_sec * 1000000 +
r_end.tv_usec) - (r_start.tv_sec * 1000000 +
r_start.tv_usec))/1000000.0;
## Available MPI libraries on LONI & HPC
<table>
<thead>
<tr>
<th>Cluster Resource</th>
<th>Name</th>
<th>Mvapich</th>
<th>Mvapich2</th>
<th>OpenMPI</th>
<th>MPICH</th>
<th>Default serial compiler</th>
</tr>
</thead>
<tbody>
<tr>
<td>LONI</td>
<td>Eric</td>
<td>0.98, 1.1</td>
<td>1.4, 1.6, 1.8.1</td>
<td>1.3.4</td>
<td>X</td>
<td>Intel 11.1</td>
</tr>
<tr>
<td></td>
<td>QB2</td>
<td>X</td>
<td>2.0</td>
<td>1.8.1</td>
<td>3.0.3</td>
<td>Intel 14.0.2</td>
</tr>
<tr>
<td>LSU</td>
<td>SuperMikell</td>
<td>X</td>
<td>1.9, 2.0.1</td>
<td>1.6.2</td>
<td>3.0.2</td>
<td>Intel 13.0.0</td>
</tr>
<tr>
<td></td>
<td>Philip</td>
<td>X</td>
<td>X</td>
<td>1.4.3, 1.6.1</td>
<td>1.2.7, 1.3.2, 1.4.1</td>
<td>Intel 11.1</td>
</tr>
<tr>
<td></td>
<td>SuperMIC</td>
<td>X</td>
<td>2.0</td>
<td>1.8.1</td>
<td>3.0.3, 3.1.1</td>
<td>Intel 14.0.2</td>
</tr>
</tbody>
</table>
## MPI Compilers (1)
<table>
<thead>
<tr>
<th>Language</th>
<th>Linux clusters</th>
<th>AIX clusters</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fortran</td>
<td>mpif77, mpif90</td>
<td>mpxlf, mpxlf90</td>
</tr>
<tr>
<td>C</td>
<td>mpicc</td>
<td>mpcc</td>
</tr>
<tr>
<td>C++</td>
<td>mpiCC</td>
<td>mpCC</td>
</tr>
</tbody>
</table>
mpif90 hello.f90
mpicc hello.c
mpicxx hello.cpp
These MPI compilers are actually wrappers
- They still use the compilers we've seen on the previous slide
- Intel, PGI or GNU
- They take care of everything we need to build MPI codes
- Head files, libraries etc.
- What they actually do can be reveal by the \texttt{-show} option
It’s extremely important that you compile and run your code with the same version of MPI!
- Use the default version if possible
Compiling a MPI C program
- Compiling Hello world in C version:
```c
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
int name_len, world_size, world_rank;
char processor_name[MPI_MAX_PROCESSOR_NAME];
//Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number and rank of processes
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
// Get the name of the processor
MPI_Get_processor_name(processor_name, &name_len);
// Print off a hello world message
printf("I am from processor %s, rank %d out of %d processors\n",
processor_name, world_rank, world_size);
// Finalize the MPI environment.
MPI_Finalize();
}
```
Compiling a MPI Fortran program
- Compiling Hello world in Fortran:
- mpif90 hellp_mpi.f90
```fortran
program hello_mpi
include 'mpif.h'
!use mpi
character 10 name
! Initialize the MPI library:
call MPI_Init(ierr)
! Get size and rank
call MPI_Comm_Size(MPI_COMM_WORLD, numtasks, ierr)
call MPI_Comm_Rank(MPI_COMM_WORLD, rank, ierr)
! print date
if (nrank == 0) then
write( , )'System date'
call system('date')
endif
call MPI_Barrier(MPI_COMM_WORLD, ierr)
! print rank
call MPI_Get_Processor_Name(name, len, ierr)
write( , )'I am ', nrank, ', ', numtasks, ' on ', name
! Tell the MPI library to release all resources it is using:
call MPI_Finalize(ierr)
end program hello_mpi
```
Notes for compiling a MPI program (1)
- Always verify what compiler/library is being used:
$ mpicc -show
icc -I/usr/local/packages/openmpi/1.6.2/Intel-13.0.0/include -L/usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib -lmpi -ldl -lm -Wl,--export-dynamic -lrt -lncurses -lm -lutil
$ mpif90 -show
ifort -I/usr/local/packages/openmpi/1.6.2/Intel-13.0.0/include -I/usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib -L/usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib -lmpi_f90 -lmpi_f77 -lmpi -ldl -lm -Wl,--export-dynamic -lrt -lncurses -lutil -lm -lutil
Notes for compiling a MPI program (2)
➢ Always verify what library is being used: Before and after:
```bash
$ ldd a.out # ldd - print shared library dependencies
linux-vdso.so.1 => (0x00007fff907ff000)
libmpi_f90.so.1 => /usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib/libmpi_f90.so.1 (0x00002b9ae577e000)
libmpi_f77.so.1 => /usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib/libmpi_f77.so.1 (0x00002b9ae5982000)
libmpi.so.1 => /usr/local/packages/openmpi/1.6.2/Intel-13.0.0/lib/libmpi.so.1 (0x00002b9ae5bb9000)
...
libpthread.so.0 => /lib64/libpthread.so.0 (0x0000003b2180000)
...
libifport.so.5 => /usr/local/compilers/Intel/composer_xe_2013.0.079/compiler/lib/intel64/libifport.so.5 (0x00002b9ae61ee000)
libifcore.so.5 => /usr/local/compilers/Intel/composer_xe_2013.0.079/compiler/lib/intel64/libifcore.so.5 (0x00002b9ae641d000)
```
Running and Analyzing MPI program
- Make sure you are running your jobs on the correct nodes
- Important if you want to run less processes than `ppn`
- Understand the usage of `$PBS_NODEFILE`
```bash
[fchen14@mike2 ~]$ qsub -I -X -l nodes=2:ppn=16 -l walltime=01:00:00 -q gpu ...
[fchen14@mike429 ~]$ echo $PBS_NODEFILE
/var/spool/torque/aux//236660.mike3
[fchen14@mike429 ~]$ cat $PBS_NODEFILE
mike429
... # 16 repeats of mike429
mike429
mike430
... # 16 repeats of mike430
mike430
[fchen14@mike429 hybrid]$ cat $PBS_NODEFILE| uniq > hosts
[fchen14@mike429 hybrid]$ cat hosts
mike429
mike430
```
Running and Analyzing MPI program
[fchen14@mike315 mpi]$ mpicc hello_mpi.c
[fchen14@mike315 mpi]$ mpirun -np 32 -hostfile $PBSNODEFILE ./a.out
Iam from processor mike315, rank 1 out of 32 processors
Iam from processor mike315, rank 6 out of 32 processors
Iam from processor mike315, rank 9 out of 32 processors
Iam from processor mike315, rank 12 out of 32 processors
Iam from processor mike315, rank 0 out of 32 processors
Iam from processor mike315, rank 2 out of 32 processors
Iam from processor mike315, rank 3 out of 32 processors
Iam from processor mike315, rank 7 out of 32 processors
Iam from processor mike315, rank 10 out of 32 processors
Iam from processor mike315, rank 5 out of 32 processors
Iam from processor mike315, rank 13 out of 32 processors
Iam from processor mike315, rank 4 out of 32 processors
Iam from processor mike315, rank 8 out of 32 processors
Iam from processor mike334, rank 17 out of 32 processors
Iam from processor mike315, rank 11 out of 32 processors
Iam from processor mike315, rank 14 out of 32 processors
Iam from processor mike315, rank 15 out of 32 processors
Iam from processor mike334, rank 18 out of 32 processors
Compiling hybrid (MPI+OpenMP) program
- **See** /home/fchen14/userenv/src/hybrid/hello_hybrid.c for complete source
- **Use command:**
- $ mpicc -openmp hello_hybrid.c
```c
#pragma omp parallel default(shared) private(itd, np)
{
gtd = omp_get_num_threads(); //get total num of threads in a process
itd = omp_get_thread_num(); // get thread id
gid = nrank*gtd + itd; // global id
printf("Gid %d from thd %d out of %d from process %d out of %d on %s\n",
gid, itd, gtd, nrank, numprocs, processor_name);
if (nrank==0 && itd==0)
{
// system("pstree -ap -u $USER");
system("for f in `cat $PBS_NODEFILE|uniq`; do ssh $f pstree -ap -u $USER; done;");
system("sleep 10");
}
}
```
Analyzing a hybrid program
[fchen14@mike315 hybrid]$ export OMP_NUM_THREADS=4
[fchen14@mike315 hybrid]$ mpirun -np 2 -x OMP_NUM_THREADS ./a.out
Gid 0 from thread 0 out of 4 from process 0 out of 2 on mike315
Gid 2 from thread 2 out of 4 from process 0 out of 2 on mike315
Gid 1 from thread 1 out of 4 from process 0 out of 2 on mike315
Gid 3 from thread 3 out of 4 from process 0 out of 2 on mike315
Gid 4 from thread 0 out of 4 from process 1 out of 2 on mike315
Gid 6 from thread 2 out of 4 from process 1 out of 2 on mike315
Gid 5 from thread 1 out of 4 from process 1 out of 2 on mike315
Gid 7 from thread 3 out of 4 from process 1 out of 2 on mike315
bash,108067
├-mpirun,110651 -np 2 -x OMP_NUM_THREADS ./a.out
│ ├-a.out,110652
│ │ ├-sh,110666 -c ...
│ │ │ `-ssh,110670 mike315 pstree -ap -u fchen14
│ │ │ `-{a.out},110654
│ │ │ `-{a.out},110656
│ │ │ `-{a.out},110662
│ │ │ `-{a.out},110663
│ │ │ `-{a.out},110664
│ │ │ `-{a.out},110665
│ │ `-{a.out},110666
│ `-{a.out},110665
2/08/2017
Exercise
- Submit a small job to run “sleep 180” and “print PBS variables”
- Create a script to submit a 5 min job and print from within the job script PBS variables $PBS_NODEFILE, $PBS_WORKDIR. Also run “sleep 180” to give you a few minutes to verify status.
- Once the job is running, find out the Mother Superior node and other slave nodes assigned to your job using qstat.
- Log into MS node and verify that your job is running and find your temporary output file
- Modify your script to print hello from each of your assigned nodes
- Run a shell script using mpirun to print process id of shell
Future Trainings
- **Next week training: Introduction to LaTeX**
- Wednesdays 9:00am, June 21, Frey Computing Service Center 307
- **Programming/Parallel Programming workshops**
- Usually in summer
- **Keep an eye on our webpage: www.hpc.lsu.edu**
|
{"Source-Url": "http://www.hpc.lsu.edu/training/weekly-materials/2017-Summer/HPC_UserEnv_2017_Summer_session_2.pdf", "len_cl100k_base": 14018, "olmocr-version": "0.1.50", "pdf-total-pages": 74, "total-fallback-pages": 0, "total-input-tokens": 123303, "total-output-tokens": 16773, "length": "2e13", "weborganizer": {"__label__adult": 0.0005335807800292969, "__label__art_design": 0.0010061264038085938, "__label__crime_law": 0.0005526542663574219, "__label__education_jobs": 0.05670166015625, "__label__entertainment": 0.00023734569549560547, "__label__fashion_beauty": 0.0003380775451660156, "__label__finance_business": 0.0009007453918457032, "__label__food_dining": 0.0005354881286621094, "__label__games": 0.0017957687377929688, "__label__hardware": 0.007297515869140625, "__label__health": 0.0008602142333984375, "__label__history": 0.0007662773132324219, "__label__home_hobbies": 0.00043082237243652344, "__label__industrial": 0.001880645751953125, "__label__literature": 0.0004808902740478515, "__label__politics": 0.00045371055603027344, "__label__religion": 0.000995635986328125, "__label__science_tech": 0.1866455078125, "__label__social_life": 0.0004153251647949219, "__label__software": 0.027679443359375, "__label__software_dev": 0.70703125, "__label__sports_fitness": 0.0008444786071777344, "__label__transportation": 0.0012884140014648438, "__label__travel": 0.0004127025604248047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39987, 0.03431]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39987, 0.0154]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39987, 0.64686]], "google_gemma-3-12b-it_contains_pii": [[0, 139, false], [139, 623, null], [623, 673, null], [673, 673, null], [673, 815, null], [815, 918, null], [918, 1844, null], [1844, 2007, null], [2007, 2694, null], [2694, 2749, null], [2749, 3024, null], [3024, 3193, null], [3193, 3341, null], [3341, 3618, null], [3618, 3637, null], [3637, 3799, null], [3799, 3965, null], [3965, 4421, null], [4421, 5284, null], [5284, 6739, null], [6739, 8085, null], [8085, 9407, null], [9407, 9436, null], [9436, 10072, null], [10072, 10472, null], [10472, 11351, null], [11351, 11860, null], [11860, 12527, null], [12527, 13155, null], [13155, 13483, null], [13483, 13962, null], [13962, 15274, null], [15274, 15768, null], [15768, 16630, null], [16630, 16852, null], [16852, 17470, null], [17470, 17817, null], [17817, 17839, null], [17839, 18324, null], [18324, 18992, null], [18992, 19174, null], [19174, 20154, null], [20154, 21018, null], [21018, 21278, null], [21278, 21393, null], [21393, 21989, null], [21989, 22916, null], [22916, 23072, null], [23072, 23442, null], [23442, 23503, null], [23503, 23871, null], [23871, 24254, null], [24254, 25136, null], [25136, 25896, null], [25896, 26127, null], [26127, 27108, null], [27108, 27506, null], [27506, 28402, null], [28402, 29035, null], [29035, 30468, null], [30468, 31213, null], [31213, 31972, null], [31972, 32272, null], [32272, 32685, null], [32685, 33407, null], [33407, 34174, null], [34174, 34731, null], [34731, 35593, null], [35593, 36192, null], [36192, 37352, null], [37352, 38098, null], [38098, 39123, null], [39123, 39733, null], [39733, 39987, null]], "google_gemma-3-12b-it_is_public_document": [[0, 139, true], [139, 623, null], [623, 673, null], [673, 673, null], [673, 815, null], [815, 918, null], [918, 1844, null], [1844, 2007, null], [2007, 2694, null], [2694, 2749, null], [2749, 3024, null], [3024, 3193, null], [3193, 3341, null], [3341, 3618, null], [3618, 3637, null], [3637, 3799, null], [3799, 3965, null], [3965, 4421, null], [4421, 5284, null], [5284, 6739, null], [6739, 8085, null], [8085, 9407, null], [9407, 9436, null], [9436, 10072, null], [10072, 10472, null], [10472, 11351, null], [11351, 11860, null], [11860, 12527, null], [12527, 13155, null], [13155, 13483, null], [13483, 13962, null], [13962, 15274, null], [15274, 15768, null], [15768, 16630, null], [16630, 16852, null], [16852, 17470, null], [17470, 17817, null], [17817, 17839, null], [17839, 18324, null], [18324, 18992, null], [18992, 19174, null], [19174, 20154, null], [20154, 21018, null], [21018, 21278, null], [21278, 21393, null], [21393, 21989, null], [21989, 22916, null], [22916, 23072, null], [23072, 23442, null], [23442, 23503, null], [23503, 23871, null], [23871, 24254, null], [24254, 25136, null], [25136, 25896, null], [25896, 26127, null], [26127, 27108, null], [27108, 27506, null], [27506, 28402, null], [28402, 29035, null], [29035, 30468, null], [30468, 31213, null], [31213, 31972, null], [31972, 32272, null], [32272, 32685, null], [32685, 33407, null], [33407, 34174, null], [34174, 34731, null], [34731, 35593, null], [35593, 36192, null], [36192, 37352, null], [37352, 38098, null], [38098, 39123, null], [39123, 39733, null], [39733, 39987, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39987, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39987, null]], "pdf_page_numbers": [[0, 139, 1], [139, 623, 2], [623, 673, 3], [673, 673, 4], [673, 815, 5], [815, 918, 6], [918, 1844, 7], [1844, 2007, 8], [2007, 2694, 9], [2694, 2749, 10], [2749, 3024, 11], [3024, 3193, 12], [3193, 3341, 13], [3341, 3618, 14], [3618, 3637, 15], [3637, 3799, 16], [3799, 3965, 17], [3965, 4421, 18], [4421, 5284, 19], [5284, 6739, 20], [6739, 8085, 21], [8085, 9407, 22], [9407, 9436, 23], [9436, 10072, 24], [10072, 10472, 25], [10472, 11351, 26], [11351, 11860, 27], [11860, 12527, 28], [12527, 13155, 29], [13155, 13483, 30], [13483, 13962, 31], [13962, 15274, 32], [15274, 15768, 33], [15768, 16630, 34], [16630, 16852, 35], [16852, 17470, 36], [17470, 17817, 37], [17817, 17839, 38], [17839, 18324, 39], [18324, 18992, 40], [18992, 19174, 41], [19174, 20154, 42], [20154, 21018, 43], [21018, 21278, 44], [21278, 21393, 45], [21393, 21989, 46], [21989, 22916, 47], [22916, 23072, 48], [23072, 23442, 49], [23442, 23503, 50], [23503, 23871, 51], [23871, 24254, 52], [24254, 25136, 53], [25136, 25896, 54], [25896, 26127, 55], [26127, 27108, 56], [27108, 27506, 57], [27506, 28402, 58], [28402, 29035, 59], [29035, 30468, 60], [30468, 31213, 61], [31213, 31972, 62], [31972, 32272, 63], [32272, 32685, 64], [32685, 33407, 65], [33407, 34174, 66], [34174, 34731, 67], [34731, 35593, 68], [35593, 36192, 69], [36192, 37352, 70], [37352, 38098, 71], [38098, 39123, 72], [39123, 39733, 73], [39733, 39987, 74]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39987, 0.07299]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
d98564f7c98a3aa1a8044e6eb671edfaea2482f6
|
Comparison of (order-independent) transparency algorithms with osgTT
Bachelor Thesis
Christoph Blümel
Degree programme: BSc Computer Science
2015-11-06
Supervisor: Jun.-Prof. Dr. Mario Hlawitschka
Scientific Visualization Group
Abstract
Christoph Blümel
Comparison of (order-independent) transparency algorithms with osgTT
This thesis documents the evaluation of several transparency techniques in aspects of quality and performance. Depth sorted alpha blending and the order-independent transparency techniques additive blending, multiplicative blending, unsorted alpha blending and depth peeling are examined. The theoretical concepts of these techniques are explained. In this work, the transparency library osgTT is extended with additive and multiplicative blending and integrated into the visualization software FAnToM. Many test cases are investigated for the quality comparison. The performance benchmarks are conducted with three different scenes.
## Contents
1 Introduction .................................................. 1
1.1 Motivation ............................................. 1
1.2 Problem description .................................... 1
1.3 Structure of thesis ..................................... 2
2 Background .................................................. 3
2.1 The OpenGL rendering pipeline ......................... 3
2.2 Blending .................................................. 5
2.3 Alpha blending ......................................... 6
2.4 Order-independent transparency ......................... 8
2.4.1 Additive blending .................................. 8
2.4.2 Multiplicative blending ........................... 8
2.4.3 Depth peeling ..................................... 9
3 osgTT .......................................................... 13
3.1 OpenSceneGraph ........................................ 13
3.2 Description .............................................. 14
3.3 Extension ............................................... 15
3.4 Integration into FAnToM ............................... 17
4 Quality ...................................................... 19
4.1 General comparison ..................................... 19
4.2 Influence of alpha value ................................ 23
4.3 Shader ................................................... 25
4.4 Intersecting geometries ................................. 27
4.5 Cyclically overlapping geometries ..................... 30
4.6 Self-overlapping geometries ........................... 33
4.6.1 Two-sided geometries .............................. 33
4.6.2 Limitations of depth sorting ...................... 33
4.7 Depth peeling ............................................ 36
4.7.1 Number of passes .................................. 36
4.7.2 Limitations ........................................ 36
4.8 Further limitations of depth sorted mode .......... 40
## Contents
5 Performance .......................... 41
5.1 Method ............................ 41
5.2 Distribution of frame times .......... 43
5.3 Average frame times ................ 45
5.4 Discussion ......................... 46
6 Conclusion ............................ 51
7 Future work ............................ 53
Bibliography ............................. 55
List of Figures .......................... 59
List of Tables ........................... 61
Listings ................................. 63
Acknowledgments ........................ 65
CHAPTER 1
Introduction
In everyday life transparent objects are a regular phenomenon, for example when one sees through glass. In computer graphics, transparency effects are important to create realistic scenes. Technically, a transparent object is fully translucent and thus not visible, unless refraction or reflection of light occurs. More precise terms to describe the effect are semi-transparent, partially transparent and translucent. In the following, these terms and transparent are used interchangeably.
FAnToM [31, 1] is a scientific visualization system which was initiated by Prof. Scheuermann in 1999. The name is an acronym for Field Analysis using Topological Methods. It is used for flow visualization research with applications in engineering disciplines, like fluid mechanics. In recent years, a redesign of FAnToM has been conducted. Algorithms to process data can be implemented as plugins, so-called toolboxes. There are two types of algorithms: data algorithms and visualization algorithms. Typically, data algorithms process scalar, vector or tensor fields. The output can be used as input for further data algorithms or visualized with a visualization algorithm. This pipeline structure is represented in the user interface as a data flow network graph.
1.1 Motivation
When a data set is visualized, it can happen that several surfaces overlap. In order to see the hidden surfaces and to have a better understanding of the data, it is necessary to employ a transparency effect. Currently, FAnToM is able to render transparent surfaces with alpha blending and primitive-based depth sorting. Unfortunately, this approach has problems with certain spatial arrangements and can be quite costly. Therefore, it is interesting to include other transparency techniques in FAnToM. The transparency library osgTT is a fitting start for this undertaking as it already supports three transparency techniques and uses the same rendering back end as FAnToM, namely OpenSceneGraph. Furthermore, two additional transparency algorithms shall be examined whether they are suitable: additive and multiplicative blending.
1.2 Problem description
The aim of this thesis is to integrate osgTT into FAnToM and to extend the library with additive and multiplicative blending. Moreover, all transparency algorithms need to be evaluated in terms of quality and performance. For the integration solutions have to be found how to
merge osgTT with FAnToM’s back end, how toolboxes can make use of osgTT, and how to provide transparency settings in the user interface. Additive and multiplicative blending need to be implemented in osgTT’s existing structure. For the quality comparison scenes must be created which bring out the visual differences and flaws of the transparency techniques. The performance evaluation requires a reliable way of measuring frame times and scenes which produce an appropriate amount of load.
1.3 Structure of thesis
The next chapter deals with the theoretical background of transparency techniques in OpenGL. Problems stemming from OpenGL’s design and several solutions are described. The third chapter gives attention to osgTT, its extension and the integration into FAnToM. Chapters four and five constitute the evaluation. The former focuses on quality whereas the latter concentrates on performance. In the end, a conclusion is formulated and possible topics for future work are mentioned.
CHAPTER 2
Background
In this chapter, problems which occur when drawing translucent geometries and solutions to them are described. First, an overview of the OpenGL pipeline is given. Secondly, blending is covered. Then, different transparency algorithms are presented, beginning with an order-dependent one and proceeding with order-independent algorithms.
2.1 The OpenGL rendering pipeline
OpenGL does not support rendering translucent primitives directly [14]. To illustrate this, I give an overview of the OpenGL 4 rendering pipeline as described in [23, 24, pp. 10-14]. Figure 2.1 depicts the different pipeline stages.
In the first stage, vertex specification [29], an ordered list of vertices is submitted to the graphics card. The component format of the vertices is defined; several floating-point and integer types are possible. Furthermore, it is specified how this list has to be interpreted, for example as lines or triangles.
In the second stage, the vertex shader, each individual vertex is processed by a user defined program. This program can have multiple outputs and the vertex is usually transformed from object to clip space.
The following tessellation stage [25] is optional. Here, geometry can be tessellated which increases the number of primitives, thus yielding better-looking models. Tessellation consists of three stages of which the first and the last are programmable. First, the tessellation control shader determines how much tessellation to apply. Then, the fixed-function tessellation process subdivides patches of vertices based on the tessellation control shader’s outputs. Lastly, the tessellation evaluation shader computes the vertex position for each newly-generated vertex, much like a vertex shader.
The next stage is the programmable and optional geometry shader. It can remove primitives, generate completely new ones or alter vertex values.
Vertex post-processing consists of several steps: ‘Transform Feedback is the process of capturing Primitives generated by the [v]ertex [p]rocessing step(s), recording data from those primitives into [b]uffer [o]bjects. This allows one to preserve the post-transform rendering state of an object and resubmit this data multiple times’ [27]. Another step is clipping where primitives outside of the viewing volume are discarded and primitives both inside and outside
are divided in a way that only the part inside remains. Furthermore, in vertex post-processing the vertices are transformed from clip space to window space.
In the following stage, primitive assembly, the vertex data from the previous stages is composed into a sequence of primitives. A limited form of primitive assembly is executed before tessellation or geometry shaders if they are active. Next, face culling is performed where triangles facing away from the viewer are usually discarded because they are occluded in closed surfaces.
In the subsequent stage, rasterization, primitives are rasterized into fragments which can be used to compute the final data for a pixel.
The pixel shader is the penultimate stage and programmable. Generally, lighting is calculated and the colour of a fragment is determined here. It is also possible to employ texture mapping or discard a fragment.
The per-fragment (or per-sample) operations compose the last stage. It consists of several tests which discard fragments if the test fails. After these tests additional operations take place. First, the pixel ownership test determines whether OpenGL is allowed to write to the pixel associated with the fragment. This is not allowed if another window overlaps the OpenGL window in that pixel. Secondly, fragments pass the scissor test only if they lie within a designated rectangular area. Thirdly, the stencil test compares the fragment with the associated location in the stencil buffer. Most typically, this is used to prevent drawing inside or outside an irregularly shaped region. Fourthly, the depth test compares the fragment’s depth with the according value in the depth buffer. If the test passes, the fragment’s depth value is written to the depth buffer. In general, this is used for hidden-surface elimination by drawing only the foremost fragments.
After these tests, blending occurs where the fragment’s colour can be combined with the colour in the framebuffer at that location via predefined equations. Instead of blending, logical operations can be performed. Here, the fragment’s colour and the colour in the framebuffer are combined via bitwise operations. With the write mask, writes to the depth and stencil buffers or to individual colour channels in the framebuffer can be disabled.
Eventually, the pixel data in the framebuffer is displayed on the screen.
As described, none of these stages provide functionality for simple and direct transparency. With naive rendering, only the fragment which was processed last at each pixel’s position is visible. These fragments correspond to the primitives which were processed last. If the depth test is enabled, the foremost fragments are visible. When translucent objects overlap, we see a combination of the objects’ colours. In the OpenGL pipeline it is possible to mix colours via blending or the fragment shader. In the next sections, I describe blending in detail and how it can be utilized for transparency effects.
2.2 Blending
Without blending [24, pp. 166-171] an incoming fragment would overwrite the pixel colour in the framebuffer. With blending it is possible to combine the fragment’s colour with the colour in the framebuffer. The result of this combination is written to the framebuffer. The way of this combination can be defined in two kinds: the blend equation and blending factors. The colour of the incoming fragment is called source colour and the pixel colour in the frame buffer is called destination colour. The blend equation is the basic mathematical operation with which the source and destination colour are combined. Both colours are scaled by one factor each before the equation is applied: the source blending factor and the destination blending factor.
The blend equation can be set with glBlendEquation. It is possible to set different equations for the RGB components and the alpha component via glBlendEquationSeparate. Table 2.1 shows the blending equations provided by OpenGL and the corresponding identifiers with which the equation can be set via the aforementioned functions. There are equations to compute the addition, difference, minimum, or maximum of the source and destination colour components. $C_s$ and $C_d$ denote the source and destination colours. $S$ and $D$ represent the source and destination blending factors.
These blending factors can be set with glBlendFunc or with glBlendFuncSeparate for the RGB components and the alpha component separately. Table 2.2 displays possible blending factors. Subscripts $s$ and $d$ denote the source and destination colour components, respectively. Some factors scale the source or destination colour components by one, zero, source alpha, destination alpha, the according source colour channels, or destination colour channels. Furthermore, there are factors which scale by the above-mentioned values subtracted from one. Moreover, it is possible to define a constant colour for blending. The appropriate function to specify this colour is glBlendColor. In the table, the constant colour is represented by the subscript $c$. Additionally, the fragment shader can output a second source colour for blending. This is called dual-source blending [24, pp. 198-200]. The usage of this second source colour is denoted by the subscript $s_1$ in the table. The next sections describe how to use blending for transparency.
<table>
<thead>
<tr>
<th>Blending equation identifier</th>
<th>Mathematical operation</th>
</tr>
</thead>
<tbody>
<tr>
<td>GL_FUNC_ADD</td>
<td>$C_s S + C_d D$</td>
</tr>
<tr>
<td>GL_FUNC_SUBTRACT</td>
<td>$C_s S - C_d D$</td>
</tr>
<tr>
<td>GL_FUNC_REVERSE_SUBTRACT</td>
<td>$C_d D - C_s S$</td>
</tr>
<tr>
<td>GL_MIN</td>
<td>$\min(C_s S, C_d D)$</td>
</tr>
<tr>
<td>GL_MAX</td>
<td>$\max(C_s S, C_d D)$</td>
</tr>
</tbody>
</table>
2.3 Alpha blending
The most common technique to render translucent objects is alpha blending (described in [13, pp. 199-202, 19]). When a translucent objects overlaps an opaque one, one sees a mixture of the colours of both objects. The intensity of the colour in the front depends on the opacity of the object in front. The colour of the object behind is attenuated to some degree compared to the case when we see the opaque object only. This attenuation equals the opacity of the object in front. In computer graphics the opacity of a colour is represented by the alpha value. A fully opaque colour has an alpha value of 1 whereas complete transparency is represented by 0. Values in between give an effect of translucency. Thus, we see the colour of the object behind only by the alpha value of the object in front subtracted from one. The following equation illustrates this combination and is used for alpha blending.
\[ \text{blend}_\alpha(C_s, C_d, \alpha_s) = C_s \times \alpha_s + C_d \times (1 - \alpha_s) \]
(2.1)
2.3 Alpha blending
Equation (2.1) computes the resulting colour by adding the colour $C_s$ of the incoming fragment (the translucent object) weighted by its opacity $\alpha_s$ to the colour in the framebuffer (the object behind) weighted by $1 - \alpha_s$. This can be realized in OpenGL by using the blending equation `GL_FUNC_ADD`. Additionally, specifying `GL_SRC_ALPHA` as the source blend factor and `GL_ONE_MINUS_SRC_ALPHA` as the destination blend factor is necessary. Figure 2.2 illustrates alpha blending: A translucent sphere is blended with an image of clouds in the sky. The result is that the sky behind the sphere is attenuated realistically.
The alpha blending equation can be rewritten as eq. (2.3). The second term contains a subtraction. Since subtraction is not commutative, alpha blending is not commutative. This means that it is important to blend fragments from back to front in order to get correct results.
\[
\text{blend}_\alpha(C_s, C_d, \alpha_s) = C_s \cdot \alpha_s + C_d - C_d \cdot \alpha_s \tag{2.2}
\]
\[
= C_d + \alpha_s \cdot (C_s - C_d) \tag{2.3}
\]
In order to blend fragments in the right order, primitives have to be submitted to the graphics card in back-to-front order. This so-called depth sorting [13, pp. 204-205, 28] has to be done on the CPU and can be quite costly. If opaque primitives are drawn first and translucent ones second, it suffices to sort translucent geometry only. Problems can occur with sorting: Intersecting primitives have to be split at their intersections (fig. 2.3(a)). Cyclic overlaps can not be sorted as the polygons are in the front and in the back at the same time (fig. 2.3(b)). They would have to be split for perfect sorting, too. But splitting of primitives increases cost. Even if no problematic arrangements like the above mentioned exist, it can be difficult to sort correctly: In fig. 2.3(c) A represents the viewer. B and C are translucent polygons. The correct order is to draw C after B. If depth sorting were done by the distance of the centre of each polygon to the viewer, B would be mistakenly drawn last as its centre is closer to the viewer. This incorrect order persists if sorting were done by the nearest or farthest vertex instead of the centre. Often, a simplified depth sorting is done by sorting objects via their bounding boxes only. This is faster, but overlapping primitives of the object can be blended in the wrong order or only the foremost fragments are drawn if the depth test is enabled, thus omitting fragments behind.
**Figure 2.2:** Alpha blending (chequered areas indicate translucency). Source: adapted from [3]
2.4 Order-independent transparency
As alpha blending with depth sorting is costly and problematic under certain conditions, order-independent transparency (OIT) techniques have been an area of active research. ‘Order-independent transparency is a technique where blending operations are carried out in a manner such that rasterization order is not important’ [24, p. 609]. This research has yielded approximative blending formulas which are commutative. Other approaches sort fragments via the GPU in contrast to primitives in depth sorting. In the next sections I describe two commutative blending formulas and one OIT-technique which sorts fragments.
2.4.1 Additive blending
Additive blending [19] simply adds the source and destination colours component-wise without any scaling. As eq. (2.4) shows, this can be implemented in OpenGL by setting the blend equation GL_FUNC_ADD and specifying GL_ONE for both blend factors. GL_ONE leaves all components unchanged by multiplying them simply with one. The alpha value which is the real indicator of the translucency of a fragment is ignored. Furthermore, as the maximum value of a colour component is one, blending multiple fragments reaches this limit quickly. Then, additional fragments cannot influence this colour channel any more. Consequently, additive blending produces only an approximative result.
\[
blend_{add}(C_s, C_d) = C_s \times 1 + C_d \times 1 = C_s + C_d
\] (2.4)
Figure 2.4 displays an example of additive blending. As no scaling is applied, there is no attenuation in colour. The colours of the sky and the sphere are simply added which produces a bright combination. Although the output in this example is not as realistic as with alpha blending, this ‘type of blending is often used for particle effects, where each particle might be a spark or other, small lighted point. It can also be used to simulate flames’ [19].
2.4.2 Multiplicative blending
With multiplicative blending [19] source and destination colour are multiplied component-wise. This can be achieved with OpenGL in the following way: GL_ZERO is set as the source blend factor. This eliminates the first term of the blending equation GL_FUNC_ADD. Specifying GL_SRC_COLOR which represents the source colour as the destination blend factor results in
2.4 Order-independent transparency
The multiplication of source and destination colour as depicted in eq. (2.5). Again, the alpha value has no influence which leads to an approximation of realistic blending.
\[
\text{blend}_{\text{mult}}(C_s, C_d) = C_s \times 0 + C_d \times C_s = C_d \times C_s
\]
(2.5)
Figure 2.5 gives an example of multiplicative blending. Here, the sky behind the sphere is attenuated. As the values in the colour components are fractions, multiplying them with another colour results in even smaller fractions. This mimics the natural attenuation of objects behind translucent materials. Moreover, the area around the sphere is completely black in the blended image. The reason for this is that the area around the sphere is filled with fully transparent black in the original image of the sphere. If the area around the sphere is blended with the sky, the colour components of the sky are multiplied with zero (as the colour black has the value zero in all of its colour channels), producing zero again and thus black.
2.4.3 Depth peeling
Depth peeling is a multi-pass fragment-level depth sorting technique for order-independent transparency described in [8]. In depth peeling the scene is separated into consecutive layers of surfaces one behind the other. One pass over the scene is necessary to peel a single layer. Compositing these layers produces the final image.
Figure 2.6 gives a diagrammatic view of depth peeling. The images depict the peeling of successive layers. As the images show, each layer consists of multiple depths; more precisely,
one depth per fragment. Evidently, the peeling process happens at the fragment level. The first layer is the nearest surface of the scene. The second layer constitutes the second nearest surface, and so on. The idea of a second or nth nearest surface is rather unintuitive. Figure 2.7 illustrates this notion with a red teapot on a blue ground plane. The interior of the teapot is green. This colouring helps to distinguish the different layers. Layer 0 represents the nearest surface. Layer 1 is mostly in green which marks the teapot’s inside. Layer 2 consists mostly of a shape of a teapot in blue. This means that the fragments of this layer are from the ground plane. Layer 3 only consists of few and small parts.
The standard depth test gives us the nearest fragments, and thus the nearest surface. Unfortunately, it does not provide a way to determine the nth nearest surface. Depth peeling solves this problem. With n passes, we can get n layers deep into the scene. Each layer consists of depth and colour information. Depth peeling is a straightforward multi-pass algorithm. In the first pass we render regularly which gives the nearest surface with the standard depth test. In the second pass the depth buffer from the first pass is used to ‘peel away’ fragments with depths that are less than or equal to the nearest depths from the first pass. Then, only the fragments behind the nearest surface remain. Now, we can generate the second nearest surface and use its depth buffer to peel away the first and second nearest surfaces in the third pass. There is one obstacle with this algorithm: It needs two depth tests per pass, but OpenGL provides only one.
To better explain the process of depth peeling, the pseudocode in listing 2.1 uses two depth units. \( A \) and \( B \) represent depth buffers. They are switched with every pass since the depth buffer from the previous pass is used in the current. Depth unit 0 is used to discard previously nearest fragments, that is previously nearest surfaces from former passes. This is not necessary in the first pass. In this case depth unit 0 is disabled. Depth unit 1 employs regular depth testing. After removing fragments processed in previous passes via depth unit 0, depth unit 1 computes the depth buffer for the surface of the current pass. The depth buffer of unit 1 in pass \( i \) is used as ‘peeling’ depth buffer for unit 0 in pass \( i + 1 \) with which unit 0 can discard the nearest fragments of pass \( i \) and all previous passes. It is important to disable depth writes on unit 0. Otherwise, the buffer would be updated with depth values of fragments passing the test of unit 0. This destroys the depth values of the nearest surface of the previous pass in the depth buffer which are needed for depth unit 0 to function properly. Eventually, the rendered scene is saved as layer \( i \). To compute the final image, the layers are composited via alpha blending (section 2.3) in back-to-front order (e.g. via viewport-sized textured quads).
As OpenGL provides only one depth unit, a different implementation for one of the units is required. Depth unit 0 can be implemented easily via a fragment shader which discards fragments with greater depth value than in the depth buffer of unit 1 in the previous pass. The contents of unit 1’s depth buffer can be passed to the shader via a depth texture. Alternatively, it is possible to realize depth unit 0 by clever usage of shadow mapping [8]. With this approach, depth peeling can be implemented with the fixed-function OpenGL pipeline. The standard depth test is used for depth unit 1.
For completely correct results, it is necessary to compute additional passes until there are no transparent fragments. In reality, as fragments farther back have diminished effect on the final image, it suffices to truncate the number of passes for a reasonable and efficient approximation.
2.4 Order-independent transparency
Figure 2.6: Depth peeling strips away depth layers with each successive pass. The frames show the frontmost (leftmost) surfaces as bold black lines, hidden surfaces as thin black lines, and ‘peeled away’ surfaces as light grey lines. Source: [8]
Figure 2.7: These images illustrate the layers of depth peeling from the nearest surface to the fourth nearest surface. Source: [8]
for (i=0; i<num_passes; i++)
{
clear color buffer
A = i % 2
B = (i+1) % 2
depth unit 0:
if(i == 0)
disable depth test
else
enable depth test
bind buffer A
disable depth writes
set depth func to GREATER
depth unit 1:
bind buffer B
clear depth buffer
enable depth writes
enable depth test
set depth func to LESS
render scene
save color buffer RGBA as layer i
}
This chapter deals with the transparency library osgTT. First, I give an overview of OpenSceneGraph which is used by both FAnToM and osgTT. This is followed by a description of osgTT. After that, I illustrate how I extended osgTT with additive and multiplicative blending. Finally, the integration of osgTT into FAnToM is depicted.
3.1 OpenSceneGraph
OpenSceneGraph (OSG) is a rendering middleware written in C++ and based on OpenGL. It reduces the complexity of the OpenGL low-level API by providing a higher-level abstraction. OSG provides modularity and object-orientation for OpenGL concepts like graphics primitives and materials. The basis for OSG’s retained rendering system is the theory of scene graphs. Such graphs collect rendering commands and data for executing them later. This is in contrast to immediate rendering systems where function calls have direct and instantaneous effect. By collecting commands, OSG is able to perform optimizations, e.g. reordering of commands. In general a scene graph is a hierarchical graph which encapsulates the spatial and logical relationships of a graphical scene. Usually, a tree is built, but nodes can also have multiple parents in OSG. At the top, a root-level node is located. At the bottom, leaf nodes represent the bottom layer of the tree. In between, there are group nodes which can have an arbitrary number of children. With group nodes, children can be treated as one. Furthermore, group nodes propagate their information and effects of operations to their children.
In 1998, Don Burns initiated the development of OpenSceneGraph. In the following year, Robert Osfield took over the project and made it open source. OSG is licensed under the OpenSceneGraph Public License (OSGPL) which is based on the GNU Lesser General Public License (LGPL). The year 2007 saw the release of OSG 2.0 with improved multi-core and multi-GPU support. OpenGL 3, OpenGL 4 and OpenGL ES support was introduced with OSG 3.0 in 2011. OSG is available for many platforms including Microsoft Windows, Linux, FreeBSD, Android, and Mac OS X. Class documentation can be found at [15]. Unfortunately, descriptions are not very extensive or lack completely.
OpenSceneGraph consists of four core libraries and several additional libraries known as NodeKits. Moreover, it is extensible via plugins. The core comprises the OpenThreads, osg, osgDB and osgUtil libraries. OpenThreads provides an object-oriented interface for threads. The osg library includes basic elements, such as nodes, geometries or textures. It
also contains mathematics classes for matrix operations. Reading and writing files as well as stream input/output operations are handled by the osgDB library. The osgUtil library helps in building the rendering backend, e.g. tree traversal and culling. An important NodeKit library is osgViewer. It provides viewer-related classes which integrate the scene graph with a wide variety of windowing systems. The osgFX NodeKit provides special effects and helps in implementing new ones. There are NodeKits for shadow techniques, particle effects, text, and volume rendering, among other things.
3.2 Description
osgTT (OSG Transparency Toolkit or Tool) [20, 12] is a transparency library for OpenSceneGraph developed by the American company AlphaPixel, LLC. It is open source via the MIT License and supports three transparency techniques: alpha blending with depth sorting and two unsorted methods, namely, depth peeling and ‘delayed blend’. These modes are implemented using only the fixed-function OpenGL pipeline; no shaders are used. AlphaPixel’s website indicates that the toolkit is to be extended with two single-pass techniques, A-buffer and weighted average, in the future, but there have not been any changes to the repository since January 2014. osgTT is comprised of two main classes: TransparencyGroup and DepthPeeling. A few other classes exist which provide demo applications.
The class TransparencyGroup inherits from OSG’s group node and mimics its behaviour. Its children are applied with the currently set transparency mode. In this class all modes, except depth peeling, are implemented. Children can be added with the function addChild( osg::Node* child, bool transparent, bool twoSided ) whose last two arguments are not existing with a regular group node. The first argument determines the subgraph which should be added. The second argument specifies whether transparency should be applied to the subgraph. If a subgraph with translucent geometry is added and this argument is set to false, the geometry is rendered as opaque. Except with depth peeling, here, this setting is ignored. With the last argument it is possible to indicate that back faces should be drawn. The active transparency technique can be defined with setTransparencyMode( TransparencyMode mode ). Its argument is an element of the enumeration TransparencyMode which provides constants for the supported transparency techniques and one to disable transparency. There are also methods to get the current transparency mode and to set a different instance of the DepthPeeling class.
In general, the transparency modes are implemented by setting an osg::StateSet when a child is added. As the two boolean parameters of osgTT’s addChild method give four different choices, there are four state sets: A pair of state sets for transparent children and a pair for opaque ones. The state sets in each pair differ in whether back faces are culled. The two state sets for two-sided children have face culling disabled.
The depth sorted mode employs regular depth testing and uses alpha blending. Depth sorting is realized by using OSG’s transparent render bin. Geometries in this bin are sorted by the centre of their bounding boxes and are rendered back-to-front [16].
[12, TransparencyGroup.h] describes delayed blend as follows: ‘Transparent objects are rendered using multiplicative alpha blending’. The word ‘multiplicative’ is misleading as regular alpha blending is applied but without depth sorting. Depth buffer updates are disabled in this mode.
Depth peeling is handled by a DepthPeeling object. According to a comment in [12,
DepthPeeling.h], the code was adapted from an example available at [21]. It is important to set the number of passes, the texture unit to be used, and the size of the viewport. The viewport size determines the size of the texture for the peeling layers. The multi-pass algorithm is implemented by using osg::Camera objects which render to textures. For each pass, one camera is created which renders one peeling layer. This implementation utilizes shadow mapping as depth test. In the end, another camera composites the layers as textured quads via alpha blending.
### 3.3 Extension
The aim is to extend osgTT with additive and multiplicative blending. The source code of osgTT with the new modes is located at [9, branch devs/mam09btk/osgtt] (integrated into FAnToM). The two new modes are similar to delayed blend which is already supported. I could use the implementation of delayed blend as a basis for the new modes. The biggest difference among these modes is the blending operation. Blending factors can be defined in OSG with the osg::BlendFunc class. I added two new BlendFunc objects to the TransparencyGroup:
```cpp
_blendFuncAdd = new osg::BlendFunc( GL_ONE, GL_ONE );
_blendFuncMult = new osg::BlendFunc( GL_ZERO, GL_SRC_COLOR );
```
The BlendFunc constructor takes two arguments. The first one is the source blending factor and the second is the destination blending factor. The additive blending object _blendFuncAdd uses GL_ONE for both arguments as described in section 2.4.1. The multiplicative blending object _blendFuncMult is constructed with GL_ZERO as source factor and GL_SRC_COLOR as destination factor (see section 2.4.2). Both modes use the blending equation GL_FUNC_ADD. This equation is the default, thus it need not be specified explicitly.
The transparency modes are implemented in the function setTransparencyMode( TransparencyMode mode ). Originally, there were several if-else clauses which tested which mode is specified via the argument `mode`. I changed this to a more elegant switch statement. The enumeration TransparencyMode was extended with two constants for the new modes: ADDITIVE_BLEND and MULTIPLICATIVE_BLEND.
Listings 3.1 and 3.2 display the implementation of additive and multiplicative blending. Depth writes are disabled so that not only the foremost fragments are blended. The appropriate blending factors are set in lines 12 and 18.
```cpp
switch( mode )
{
[...]
case ADDITIVE_BLEND:
{
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask( false );
_transparentState->setAttributeAndModes( depth.get(), osg::StateAttribute::ON );
_transparentState->setRenderingHint( osg::StateSet::DEFAULT_BIN );
_transparentState->setRenderBinDetails( 12, "RenderBin" );
```
Listing 3.1: Source code for additive blending
switch( mode )
{
[...]
case MULTIPLICATIVE_BLEND:
{
osg::ref_ptr<osg::Depth> depth = new osg::Depth;
depth->setWriteMask( false );
_transparentState->setAttributeAndModes( depth.get( ), osg::StateAttribute::ON );
_transparentState->setRenderingHint( osg::StateSet::DEFAULT_BIN );
_transparentState->setRenderBinDetails( 12, "RenderBin" );
_transparentState->setAttributeAndModes( _blendFuncMult.get( ), osg::StateAttribute::ON );
Group::addChild( _scene.get( ) );
}
break;
[...]
3.4 Integration into FAnToM
In order to integrate osgTT into FAnToM, changes to the back end had to be made and new GUI elements had to be added to control the transparency mode and the number of passes. The source code of FAnToM with integrated osgTT can be found at [9, branch devs/mam09btk/osgtt]. Two approaches were explored while designing the GUI elements, as the first turned out to be flawed. At first, I created a submenu for transparency in the preferences top menu. Here, it was possible to set the transparency mode. Unfortunately, one could not see which mode is currently active. The same problem would have arisen for the number of passes in depth peeling. Therefore, I began a second approach where I created a separate view for transparency, the Transparency View. This view contains a combo box to choose the transparency mode and a slider to specify the number of passes. With this second approach it is always possible to see the currently active transparency settings. Figure 3.1 displays the new GUI elements.
In the back end, osgTT’s TransparencyGroup had to be integrated in FAnToM’s scene graph. Originally, there was a scene node below the clipping node. Nodes of algorithms were added as children to this scene node. Now, a TransparencyGroup is in place of this scene node. This TransparencyGroup has four child nodes. These four nodes correspond to the parameter combinations of the addChild method. Therefore, there is a transparent, an opaque, a transparent/two-sided, and an opaque/two-sided node. Nodes of algorithms are supposed to be added to one of these nodes depending on their transparency settings.
If the transparency settings of a node are changed, it has to be moved to the correct node of the four nodes. I realized this by adding a new class OsgTransparentGraphics which is derived from OsgGraphics. OsgTransparentGraphics has two methods to set whether it is transparent and whether it is two-sided. An OsgGraphics object adds or removes its nodes from the scene graph whether it is set to be visible. The node under which it should insert its nodes is supplied at construction time. Originally, this was the scene node which was mentioned earlier. The constructor of OsgTransparentGraphics has arguments for the four nodes which represent the transparency settings. As an OsgTransparentGraphics object knows these four nodes, it can add its nodes to the right node when its transparency settings are changed. To handle this I implemented the method OsgTransparentGraphics::updateParent() which determines which of the four nodes is the correct new parent node. To set the new parent, the method setParent( osg::ref_ptr< osg::Group > newParent ) was added to OsgGraphics. It moves the nodes of this OsgGraphics object from the old parent to the new parent. Now, algorithms can use OsgTransparentGraphics to alter transparency settings.
I adapted the show surface algorithm of the grid toolbox to use the two transparency options of OsgTransparentGraphics. This results in two new checkboxes, Enable transparency and Set two-sided, in the options view of this algorithm. Now, it is possible to enable transparency and two-sidedness for the rendered surface. The altered show surface source code is available at [10, branch devs/mam09btk/osgtt].
The interface GraphicsEngine was extended with methods to specify and retrieve the transparency mode options for osgTT. These methods are implemented in OsgGraphicsEngine. With setTransparency( Transparency mode ) it is possible to set the transparency mode. The type Transparency is an abstraction of the TransparencyMode enumeration of osgTT. The method
setTransparencyPasses( unsigned int numPasses ) specifies the number of passes for multi-pass modes, here depth peeling. Both methods are used by the transparency view.
osgTT’s DepthPeeling class needs the size of the viewport to work properly. Therefore, the DepthPeeling instance has to be informed when FAnToM’s main graphics window is resized. This was implemented with a resize callback which sets the viewport size in the DepthPeeling object. The GraphicsPainter class was extended with functionality to register callbacks for resize events. Now, a resize callback can be added with the addResizeCallback method.
In this chapter the transparency algorithms are evaluated by their difference in image quality and realism. The number of passes used for depth peeling is given in brackets. Fixed-function lighting was used for the comparisons except in section 4.3. A light was inserted above the camera. Its position is updated to stay above the camera when the camera perspective is changed. The source code for this mechanism is available at [9, branch devs/mam09btk/ffpLight].
4.1 General comparison
Figure 4.1 gives a general overview of the different transparency modes. In the front, the scene uses the Stanford dragon [26] coloured in cyan. Behind, there is a Utah teapot [6] in magenta. In the back, a yellow Stanford bunny [26] is placed. Both the dragon and the teapot have an alpha value of 0.5 whereas the bunny is completely opaque.
Figure 4.1(a) displays the scene with transparency disabled. Thus, only the dragon and a small part of the teapot are visible.
Figures 4.1(b) and 4.1(c) compare additive blending with a black and a white background. With a white background most of the image is white because the white of the background is added to the colour of transparent geometries in front of it. Since the bunny is not transparent, it is not blended with the background. Thus, its yellow colour is visible with additively blended colours of the models in front of it. A black background does not influence the colour of transparent objects with additive blending. Consequently, a lot more of the scene is recognizable. Here, the colour of overlapping, transparent objects becomes brighter. The middle of the image where all three models overlap is almost completely white. In general, the more transparent, overlapping objects exist, the brighter the image becomes as the colours are added and get closer to the maximum of white.
Figures 4.1(h) and 4.1(i) compare multiplicative blending with the background in white or black, respectively. This mode has some similarities to additive blending. With a black background most of the image is black because the black of the background is multiplied by the colours of transparent geometries in front of it. Since black has the value zero in all colour channels the result of the multiplication is zero in all channels and thus black overall. As the bunny is not transparent, it is not blended with the background and we can see it blended with the dragon and the teapot. With a white background this flaw of multiplicative blending does not occur as white with the value one in all channels does not influence multiplicative blending.
Where transparent objects overlap, the colour becomes darker because the values in the colour channels are fractions and give even smaller fractions if multiplied with other colours. As a consequence, if in the blending series of a pixel at least one fragment has a colour channel with value zero, the channel is zero for the result colour of the pixel. This happens with the bunny as it becomes green because it ‘loses’ its red channel since the red channel of the cyan dragon equals zero. Other examples are the teapot which becomes blue and the middle of the image which appears in black.
As seen, for both additive and multiplicative blending it is important to choose the colour of the background judiciously since it can influence the quality of the image greatly.
Depth peeling (fig. 4.1(f)) and depth sorting (fig. 4.1(g)) produce the most realistic images with depth peeling being even better. In the depth sorted image some artefacts are visible with the teapot: First, the edge where the lid meets the body and the handle should be more opaque and magenta. Second, a bit of the sprout where it joins the body is cut off. These cases are due to the enabled depth test which causes discardment of important fragments if not handled in the right order (see section 4.6.2 for a detailed test case).
Figure 4.1(d) shows delayed blending. The order in which the geometries are drawn depends on their (coincidental) order in the scene graph. In this case the teapot is rendered erroneously last as if it were in front of the dragon. In fig. 4.1(e) the objects were manually ordered, but this should be regarded as an exception. Here, the rendered image looks as good as with depth peeling. In order to create comparable images of the unordered delayed mode, the order with which the teapot is rendered last was reproduced manually for the following test cases.
4.1 General comparison
(a) None
(b) Additive (white background)
(c) Additive (black background)
(d) Delayed
(e) Delayed (manually ordered)
(f) Depth peeling (6)
(g) Depth sorted
(h) Multiplicative (white background)
4.2 Influence of alpha value
This section examines how the transparency algorithms handle a different alpha value. The scene is the same as in the general comparison (section 4.1) except that the alpha value is with 0.3 lower.
Delayed blending, depth peeling and depth sorted transparency (figs. 4.2(c) to 4.2(e)) compute the alpha value correctly. That is, the dragon and teapot are more translucent. The images of additive and multiplicative blending (figs. 4.2(b) and 4.2(f)) look exactly the same as the ones with higher alpha value in figs. 4.1(c) and 4.1(h). This is not surprising as both algorithms only use the colour channels in their blending functions and thus ignore the alpha value.
(a) None
(b) Additive
(c) Delayed
(d) Depth peeling (6)
4.3 Shader
In this comparison it is determined whether shaders work with the transparency modes. The scene of the general comparison (section 4.1) is used again, but this time lighting is calculated by a simple Blinn-Phong shader provided by FAnToM. Figure 4.3 displays the scene rendered with the shader. One difference between the shader and fixed-function lighting is that the bunny is brighter.
All algorithms work correctly with the shader except depth peeling. In fig. 4.3(d) one can see that there is no transparency at all. osgTT’s depth peeling does not work with shaders. As depth peeling is implemented via the fixed-function pipeline in osgTT, there seems to be a problem with the programmable pipeline.
(a) None
(b) Additive
(c) Delayed
(d) Depth peeling (6)
4.4 Intersecting geometries
This section describes how the algorithms cope with intersecting objects. The scene contains one Stanford dragon and a box [7] which intersects it in its middle. Both objects are translucent.
In this test case depth sorted transparency is interesting because OSG’s depth sorting via bounding boxes cannot sort the objects correctly as none is completely in front of or behind the other. Depending on the camera angle the image is rendered as if the box were behind (fig. 4.4(e)) or in front of (fig. 4.4(f)) the dragon. In the first case, the middle part of the dragon is missing due to the enabled depth test. In the second case, the part of the box overlapped by the dragon is missing for the same reason.
Delayed mode with its coincidental order renders the whole box as if it were in front of the dragon (fig. 4.4(c)). Depth peeling renders the scene perfectly (fig. 4.4(d)). Additive (fig. 4.4(b)) and multiplicative (fig. 4.4(g)) modes are not affected by intersecting objects.
(a) None
(b) Additive
(c) Delayed
(d) Depth peeling (4)
4.4 Intersecting geometries
Figure 4.4: The dragon and the box intersect
(e) Depth sorted
(f) Depth sorted with a different camera angle
(g) Multiplicative
4.5 Cyclically overlapping geometries
The scene for this test case contains four triangles which cyclically overlap. This means that the yellow triangle overlaps the blue one, the blue one overlaps the red triangle which overlaps the green one and the green triangle overlaps the yellow one reaching a cycle in this way.
This arrangement is interesting for depth sorted transparency for the same reason as described in section 4.4. But in this case the problem occurs without intersecting objects. As pictured in figs. 4.5(e) and 4.5(f) it depends on the camera angle again which overlapped corners are visible. In the first case the green and the red corner are visible and rendered in the correct order, but the blue and yellow ones are not drawn because of the depth test. In the second case it is the other way round. With further camera angles other combinations of corners are visible.
Delayed blending (fig. 4.5(c)) draws only the blue corner correctly in this case of coincidence. The other corners are drawn as if they were in the front but, in reality, they are in the back. Depth peeling (fig. 4.5(d)) has no problems with this scene and renders it flawlessly. Additive (fig. 4.5(b)) and multiplicative (fig. 4.5(g)) blending produce typical results without problems stemming from the cyclic overlaps.
4.5 Cyclically overlapping geometries
(a) None
(b) Additive
(c) Delayed
(d) Depth peeling (2)
Figure 4.5: The triangles overlap cyclically
4.6 Self-overlapping geometries
In this section the transparency modes are tested with self-overlapping geometries. First, osgTT’s two-sided option is examined which can create self-overlapping geometries. Second, a limitation of the depth sorted mode is described in detail.
4.6.1 Two-sided geometries
Here, osgTT’s two-sided option is tested with the transparency modes. Enabling two-sidedness effects that back faces are drawn, too. Consequently, geometries are self-overlapping as they overlap their back faces. The scene from the general comparison (section 4.1) is used but with two-sidedness enabled for the dragon and the teapot. These two models are partly self-overlapping without two-sidedness. With the option enabled, they are completely self-overlapping and have twice as many layers.
Comparing two-sided geometries in fig. 4.6 with one-sided ones in fig. 4.1, the following differences are apparent. Additive mode is brighter and less details are recognizable as the additional layers add more colour (fig. 4.6(a)). Multiplicative mode is darker as the additional layers reduce the final colour of a pixel (fig. 4.6(e)). Furthermore, a part of the dragon’s crest (spikes) on his back of his middle body part is more noticeable now. This makes the dragon’s middle body look as if it were curved differently. Delayed, depth peeling and depth sorted modes (figs. 4.6(b) to 4.6(d)) are more opaque because of the additional layers’ colours. They are not as bright since the white of the background is much less significant with the additional layers. Depth peeling is rendered with eight passes which is not enough to incorporate all layers, but additional passes do not yield recognizable differences. In depth sorted mode, the teapot has more artefacts than without two-sidedness (fig. 4.1(g)). The reason is the same as stated in section 4.1: The depth test discards important fragments.
4.6.2 Limitations of depth sorting
In fig. 4.7 the camera is being tilted over a transparent dragon in depth sorted mode. At first, the self-overlapping body parts are visible (fig. 4.7(a)). With progressing tilt, they gradually disappear (figs. 4.7(b) and 4.7(c)). Eventually, only the foremost parts of the dragon are visible as if it were not translucent.
This behaviour occurs with self-overlapping geometries if the polygons of the object are not sorted by depth which does not happen with OSG’s depth sorting. As a consequence self-overlapped parts of a geometry are only visible in osgTT’s depth sorted mode if the polygons are processed back to front. If they are not processed in the right order, the depth test discards fragments of self-overlapped parts if a fragment in front of them has already been processed. Depending on the camera position the order of polygons is coincidentally adequate or yields flawed images. The orientation of the dragon in the general comparison (fig. 4.1(g)) is very fitting for osgTT’s depth sorted mode. But if the dragon were rotated by 180 degrees around its y-axis or with the camera angles in fig. 4.7, only pieces of its self-overlapped body parts are drawn correctly.
(a) Additive
(b) Delayed
(c) Depth peeling (8)
(d) Depth sorted
4.6 Self-overlapping geometries
Figure 4.6: Two-sided geometries (back faces visible)
(a) Multiplicative
Figure 4.7: Tilting the camera in depth sorted mode
(b)
4.7 Depth peeling
In this section characteristics unique to depth peeling are described. In contrast to the other modes, depth peeling is a multi-pass technique. Hence, the effect of the number of passes on the quality of the rendered image is examined. Furthermore, a bug in osgTT with depth peeling is described.
4.7.1 Number of passes
In this section the influence of the number of passes with depth peeling is described. Figure 4.8 displays the scene from the general comparison (section 4.1) from zero to six passes with depth peeling. Six passes are enough to incorporate all layers of this scene.
Zero passes only produce an image of the background because the geometries are not processed at all (fig. 4.8(a)). The first pass shows only the dragon and a part of the teapot as if transparency was disabled, but both models are blended with the white of the background (fig. 4.8(b)). With two passes the dragon is transparent and the bunny as well as the remaining part of the teapot appear, but the teapot itself is not translucent, though (fig. 4.8(c)). Not until the scene is rendered with three passes does the teapot become transparent (fig. 4.8(d)). The next three passes give improvements where all three models overlap and self-overlapping of the dragon and the teapot occurs (figs. 4.8(e) to 4.8(g)). The differences of the last two passes are virtually not recognizable without magnification.
4.7.2 Limitations
There is a bug with depth peeling which manifests itself when zooming or changing the camera angle. Figure 4.9 shows this bug when zooming. If you zoom in or out the scene is eventually cut off in the back or the front, respectively. In fig. 4.9(a) the bunny is not completely rendered and in fig. 4.9(c) parts of the dragon are cut off. It is possible to work around this by changing to a different transparency mode and then changing back to depth peeling. This was done in figs. 4.9(b) and 4.9(d). Via changing the camera angle, one can trigger this bug, too.
The authors of osgTT possibly hint at this bug in the source code:
I believe there is currently a bug which manifests itself when a user switches dynamically between the various TransparencyModes that causes OSG to miscalculate the near/far values for the topmost Camera. [12, see TransparencyGroup.h]
4.7 Depth peeling
(a) 0 passes
(b) 1 pass
(c) 2 passes
(d) 3 passes
Figure 4.8: Effect of the number of passes with depth peeling
Figure 4.9: Bug when zooming with depth peeling
4.8 Further limitations of depth sorted mode
Due to depth sorting via bounding boxes, it is possible that the depth sorted mode creates flawed images even if there are no problematic arrangements of geometries like intersections or cyclic overlaps. Figure 4.10 illustrates this: Depending on the camera position the half-moon is fully drawn or a part is missing.
Figure 4.10: Problems with depth sorting via bounding boxes
CHAPTER 5
Performance
In this chapter the performance of the transparency algorithms is evaluated. For multi-pass modes (depth peeling), the number of passes is given in brackets.
5.1 Method
For measuring the performance of the algorithms, three different scenes were created. They are called **wide scene**, **deep scene** and **deep, occluded scene**. Each scene contains the Stanford Dragon model [26] ten times. In the wide scene the models are arranged in a wide and horizontal way with a bit of overlap. In the deep scene the ten dragons overlap very much and minimal horizontal shift is used. The deep, occluded scene is virtually identical to the deep scene, except that a completely opaque, white triangle is placed in front of the models. Figures 5.4 to 5.6 show these three scenes.
The Stanford Dragon consists of 1,132,830 triangles and 566,098 vertices [26]. So, each scene comprises about 11 million triangles. The colour of the models changes from $RGB = (0,1,1)$ (cyan) to $RGB = (1,0,1)$ (magenta) from front to back. This colour gradient is realized by increasing the $R$ component and decreasing the $G$ component by 0.1 with every model further.
```cpp
void OsgView::paint()
{
[...] // ... draw code
timing.start();
osgViewer->frame();
glFinish();
timing.pause();
[...] // ... draw code
}
```
**Listing 5.1:** Part of the paint method with frame time measurement
behind. The alpha channel of every dragon equals 0.5.
The deep scene is intended to surface performance differences with many overlapping triangles compared to the wide scene. The idea in placing an opaque triangle in front of the scene in the deep, occluded scene is the following: In the rendered image only the white triangle is visible. Therefore, the ten dragon models behind it are irrelevant for the final image and could be discarded from the rendering process. With the deep, occluded scene we can measure whether a transparency algorithm makes use of this saving.
The test system uses an Intel Core i7-980 processor, which has six cores and a clock rate of 3.33 GHz [4]. Moreover, it is equipped with 24 GiB of main memory and an Nvidia GeForce GTX 580 [11] with 3072 MiB of video memory.
Listing 5.1 displays the code which was used to measure the frame times. At first, the time measurement is started with a timing object (5). Then, the actual OSG rendering method is called (7) [17]. Calling glFinish() in line 8 guarantees that rendering is complete [24, p. 31]. Finally, the time measurement is stopped (10).
In order to create a representative set of frame times, 100 values were measured. These values were obtained by calling the paint method 100 times consecutively. The source code used for the benchmarks can be found at [9, branch devs/mam09btk/bench].

5.2 Distribution of frame times
Figures 5.1 to 5.3 display the distribution of all frame times via box plots. In the whole series of benchmarks there are only two outliers, one with the wide scene (16.048 ms) and one with the deep scene (15.640 ms), both with transparency disabled. All other values differ by less than 1 ms, referring to one set of frame times. This shows that the measurement method is reliable and the transparency algorithms provide consistent frame times. As a consequence the box plots are degenerate and resemble mere strokes. Moreover, one can see a linear increase with depth peeling in the figures.
Figure 5.2: Distribution of frame times of the deep scene
Figure 5.3: Distribution of frame times of the deep, occluded scene
5.3 Average frame times
Table 5.1 displays the average frame times. The mean values of single pass modes are very similar and vary in a range of 10 to 11 ms. No transparency is virtually as fast as single-pass transparency. Depth peeling with one pass is about 0.2 ms slower than the other single pass modes. The frame time of depth peeling increases almost linearly with the number of passes: With multi-pass depth peeling the increase per pass is a bit more than the frame time of single-pass depth peeling. It is more than 12 ms with the wide scene and more than 11 ms with the other scenes, respectively. In general, the wide scene is a bit slower than the other scenes: Here, single pass modes are approximately 0.4 ms slower. There is practically no performance difference between the deep and the deep, occluded scene.
<table>
<thead>
<tr>
<th>Transparency mode</th>
<th>Frame time [ms] of scene</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>wide</td>
</tr>
<tr>
<td>None</td>
<td>10.613</td>
</tr>
<tr>
<td>Additive</td>
<td>10.597</td>
</tr>
<tr>
<td>Delayed</td>
<td>10.597</td>
</tr>
<tr>
<td>Depth sorted</td>
<td>10.648</td>
</tr>
<tr>
<td>Multiplicative</td>
<td>10.538</td>
</tr>
<tr>
<td>Depth peeling (1)</td>
<td>10.776</td>
</tr>
<tr>
<td>Depth peeling (2)</td>
<td>23.223</td>
</tr>
<tr>
<td>Depth peeling (3)</td>
<td>35.655</td>
</tr>
<tr>
<td>Depth peeling (4)</td>
<td>48.068</td>
</tr>
<tr>
<td>Depth peeling (5)</td>
<td>60.451</td>
</tr>
<tr>
<td>Depth peeling (6)</td>
<td>72.792</td>
</tr>
<tr>
<td>Depth peeling (7)</td>
<td>85.388</td>
</tr>
<tr>
<td>Depth peeling (8)</td>
<td>97.821</td>
</tr>
<tr>
<td>Depth peeling (9)</td>
<td>110.195</td>
</tr>
<tr>
<td>Depth peeling (10)</td>
<td>122.238</td>
</tr>
</tbody>
</table>
5.4 Discussion
Only depth sorting and depth peeling include additional steps compared to the other modes. Moreover, in each mode the complete geometry has to be processed at least once. Thus, very similar frame times among single-pass modes, even disabled transparency, are logical. The minute differences among them are explained by coincidental load on the test system.
Depth sorting doesn’t impact performance in the test cases. According to [16], OSG uses bounding boxes for depth sorting and sorts by the middle of the box. Furthermore, it doesn’t sort inside a geometry. Sorting the ten dragons by their bounding boxes only seems to be too fast to impact performance significantly.
Single-pass depth peeling tends to be a little bit slower than the other single-pass modes. Here, a slight overhead seems to occur. Plus, this mode does not provide any transparency. Depth peeling performance decreases linearly with the number of passes as the algorithm does not reduce the amount of geometry per pass. Consequently, the whole geometry has to be processed in every pass and the linear increase results. The increase in frame time in multi-pass depth peeling is more than the frame time of single-pass depth peeling. Here, additional steps of the algorithm seem to impact performance. One of these steps is to composite the images of the passes into the final image.
The performance of the deep and deep, occluded scene is virtually identical. The slower values of the wide scene are result of coincidental load, rather than the scene itself because the amount of geometry is the same as in the deep scene and no mode is sophisticated enough to take advantage of the arrangement of the scene. Consequently, the triangle in the deep, occluded scene has no effect. One could think that the depth test could save work in this case by discarding fragments behind the triangle. But the depth test is positioned at the very end of the graphics pipeline in the per-sample operations [24, p. 13] after the expensive steps of vertex processing and shading.
5.4 Discussion
(a) None
(b) Additive
(c) Delayed
Figure 5.4: Wide scene in different transparency modes
- (d) Depth peeling (4)
- (e) Depth sorted
- (f) Multiplicative
5.4 Discussion
(a) None
(b) Additive
(c) Delayed
(d) Depth peeling (5)
Figure 5.5: Deep scene in different transparency modes
Figure 5.6: Deep occluded scene: only a white triangle is visible
CHAPTER 6
Conclusion
The purpose of this thesis was to bring new transparency techniques to FAnToM and evaluate them. This was done with the integration of osgTT. A suitable implementation in FAnToM’s back end was found with the alteration of the scene graph and the addition of OsgTransparentGraphics. The ShowSurface algorithm was successfully adapted. Moreover, I created a fitting way to expose the transparency settings in the user interface with the Transparency View. Additive and multiplicative blending were added to osgTT and work as expected.
Several test cases for the quality comparison were conducted. Depth peeling, depth sorted mode and multiplicative mode provide satisfactory quality. Depth peeling produces flawless results, unfortunately osgTT’s implementation does not work with shaders. The depth sorted mode has problems with certain spatial arrangements and sometimes self-overlapping parts of a geometry are not drawn. Its sorting with bounding boxes is a good compromise between speed and quality. The multiplicative mode gives a sufficient approximation in most cases and does not require sorting. But it may not be used if a black background is required. As delayed blend’s quality depends mainly on coincidence in form of the structure of the scene graph, it is not reliable and not recommended to use. Manual sorting is possible, but not user-friendly at all. Additive blending’s way of adding colour with every translucent surface is contrary to natural transparency, yielding unrealistic outputs.
The performance evaluation revealed that all algorithms, except depth peeling, are identical in speed. Moreover, they are as fast as rendering without transparency. Depth peeling’s performance decreases linearly with the number of passes. This can lead to problems with scenes which require lots of passes to be rendered satisfactorily. Rotating and zooming may be jerky and especially animations may not be smooth.
CHAPTER 7
Future work
Different opportunities for future works can be pursued:
A major improvement of the depth peeling implementation would be the support of shaders. The code it is based on has been updated and possibly supports shaders now [21]. This could be used as a basis. Another bug in depth peeling is that the near and far values are not updated properly (see 4.7.2). This issue could be looked into more closely.
Moreover, other transparency techniques could be included and evaluated. Another commutative blending technique to be examined could be additive blending with influence of the alpha value. Described in [13, pp. 201-202], this technique uses source alpha as source blending factor. [5] introduces dual depth peeling which needs only half as many passes as regular depth peeling. This eases depth peeling’s downside of poor performance with many passes.
ShowSurface is the only visualization algorithm which has been adapted. Currently, specifying whether a surface is transparent has to be done manually. This can be automatized by observing the alpha value. FAnToM includes many more visualization toolboxes which could be updated. A spinner could be a more fitting tool than a slider to set the number of passes in the Transparency View. A spinner widget has yet to be abstracted from the underlying Qt framework.
Bibliography
List of Figures
2.1 OpenGL 4 rendering pipeline. Blue boxes represent programmable stages. Source: [23] ................................................................. 4
2.2 Alpha blending (chequered areas indicate translucency). Source: adapted from [3] ............................................................. 7
2.3 Problems with depth sorting ................................................... 8
2.4 Additive blending (chequered areas indicate translucency). Source: adapted from [3] ............................................................. 9
2.5 Multiplicative blending (chequered areas indicate translucency). Source: adapted from [3] ......................................................... 9
2.6 Depth peeling strips away depth layers with each successive pass. The frames show the frontmost (leftmost) surfaces as bold black lines, hidden surfaces as thin black lines, and ‘peeled away’ surfaces as light grey lines. Source: [8] . . . 11
2.7 These images illustrate the layers of depth peeling from the nearest surface to the fourth nearest surface. Source: [8] ................................ 11
3.1 New GUI elements in FAnToM ............................................. 18
4.1 General comparison (alpha equals 0.5) ......................................... 23
4.2 Alpha value lowered to 0.3 ..................................................... 25
4.3 Lighting via shader .................................................................. 27
4.4 The dragon and the box intersect .............................................. 29
4.5 The triangles overlap cyclically .................................................. 32
4.6 Two-sided geometries (back faces visible) .................................. 35
4.7 Tilting the camera in depth sorted mode .................................... 35
4.8 Effect of the number of passes with depth peeling ....................... 38
4.9 Bug when zooming with depth peeling ....................................... 39
4.10 Problems with depth sorting via bounding boxes ..................... 40
5.1 Distribution of frame times of the wide scene ............................ 42
5.2 Distribution of frame times of the deep scene ............................. 43
5.3 Distribution of frame times of the deep, occluded scene ............... 44
5.4 Wide scene in different transparency modes ............................ 48
5.5 Deep scene in different transparency modes ............................. 50
5.6 Deep occluded scene: only a white triangle is visible ................ 50
59
## List of Tables
<table>
<thead>
<tr>
<th>Table</th>
<th>Description</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>2.1</td>
<td>Blending equations. Source: [24, p. 171]</td>
<td>5</td>
</tr>
<tr>
<td>2.2</td>
<td>Blending factors. Source: [24, p. 169]</td>
<td>6</td>
</tr>
<tr>
<td>5.1</td>
<td>Mean frame times from 100 measurements</td>
<td>45</td>
</tr>
</tbody>
</table>
Listings
2.1 Pseudocode for layer extraction in depth peeling using two depth buffers. Source: [8] ................................. 12
3.1 Source code for additive blending ........................................ 15
3.2 Source code for multiplicative blending ............................. 16
5.1 Part of the paint method with frame time measurement .............. 41
Acknowledgments
I thank Mario Hlawitschka for giving me the opportunity to write this bachelor thesis and for his professional advice.
I would also like to thank Jakob, Svø, Jenny, Gabriele and Wolfgang for existing.
Eigenständigkeitserklärung
Ich versichere, dass ich die vorliegende Arbeit selbständig und nur unter Verwendung der angegebenen Quellen und Hilfsmittel angefertigt habe, insbesondere sind wörtliche oder sinngemäße Zitate als solche gekennzeichnet. Mir ist bekannt, dass Zuwiderhandlung auch nachträglich zur Aberkennung des Abschlusses führen kann.
Christoph Blümel
|
{"Source-Url": "http://lips.informatik.uni-leipzig.de/files/bathesis_cbluemel_digital_0.pdf", "len_cl100k_base": 15567, "olmocr-version": "0.1.53", "pdf-total-pages": 76, "total-fallback-pages": 0, "total-input-tokens": 121320, "total-output-tokens": 20517, "length": "2e13", "weborganizer": {"__label__adult": 0.00046753883361816406, "__label__art_design": 0.00438690185546875, "__label__crime_law": 0.0003712177276611328, "__label__education_jobs": 0.0014829635620117188, "__label__entertainment": 0.00029921531677246094, "__label__fashion_beauty": 0.00022161006927490232, "__label__finance_business": 0.00025081634521484375, "__label__food_dining": 0.0004086494445800781, "__label__games": 0.0012655258178710938, "__label__hardware": 0.0014801025390625, "__label__health": 0.0003838539123535156, "__label__history": 0.0006756782531738281, "__label__home_hobbies": 0.00012385845184326172, "__label__industrial": 0.0005135536193847656, "__label__literature": 0.0005331039428710938, "__label__politics": 0.00033593177795410156, "__label__religion": 0.000728607177734375, "__label__science_tech": 0.10198974609375, "__label__social_life": 0.0001354217529296875, "__label__software": 0.0189056396484375, "__label__software_dev": 0.86376953125, "__label__sports_fitness": 0.0002837181091308594, "__label__transportation": 0.0005779266357421875, "__label__travel": 0.0002944469451904297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 76776, 0.04486]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 76776, 0.41299]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 76776, 0.88613]], "google_gemma-3-12b-it_contains_pii": [[0, 232, false], [232, 232, null], [232, 962, null], [962, 962, null], [962, 3045, null], [3045, 3639, null], [3639, 3639, null], [3639, 3639, null], [3639, 6072, null], [6072, 7066, null], [7066, 9426, null], [9426, 12409, null], [12409, 15309, null], [15309, 16339, null], [16339, 18969, null], [18969, 21262, null], [21262, 22850, null], [22850, 26756, null], [26756, 27171, null], [27171, 27614, null], [27614, 30163, null], [30163, 33788, null], [33788, 36550, null], [36550, 37157, null], [37157, 40808, null], [40808, 41428, null], [41428, 44017, null], [44017, 45885, null], [45885, 45997, null], [45997, 46111, null], [46111, 46810, null], [46810, 46866, null], [46866, 47584, null], [47584, 47643, null], [47643, 48658, null], [48658, 48717, null], [48717, 48877, null], [48877, 50193, null], [50193, 50291, null], [50291, 50336, null], [50336, 53463, null], [53463, 53530, null], [53530, 53695, null], [53695, 55995, null], [55995, 56067, null], [56067, 56129, null], [56129, 56177, null], [56177, 56602, null], [56602, 58016, null], [58016, 59469, null], [59469, 60155, null], [60155, 60223, null], [60223, 62221, null], [62221, 64277, null], [64277, 64329, null], [64329, 64449, null], [64449, 64524, null], [64524, 64646, null], [64646, 66595, null], [66595, 66595, null], [66595, 67940, null], [67940, 67940, null], [67940, 69874, null], [69874, 72369, null], [72369, 72850, null], [72850, 72850, null], [72850, 75392, null], [75392, 75392, null], [75392, 75784, null], [75784, 75784, null], [75784, 76158, null], [76158, 76158, null], [76158, 76377, null], [76377, 76377, null], [76377, 76776, null], [76776, 76776, null]], "google_gemma-3-12b-it_is_public_document": [[0, 232, true], [232, 232, null], [232, 962, null], [962, 962, null], [962, 3045, null], [3045, 3639, null], [3639, 3639, null], [3639, 3639, null], [3639, 6072, null], [6072, 7066, null], [7066, 9426, null], [9426, 12409, null], [12409, 15309, null], [15309, 16339, null], [16339, 18969, null], [18969, 21262, null], [21262, 22850, null], [22850, 26756, null], [26756, 27171, null], [27171, 27614, null], [27614, 30163, null], [30163, 33788, null], [33788, 36550, null], [36550, 37157, null], [37157, 40808, null], [40808, 41428, null], [41428, 44017, null], [44017, 45885, null], [45885, 45997, null], [45997, 46111, null], [46111, 46810, null], [46810, 46866, null], [46866, 47584, null], [47584, 47643, null], [47643, 48658, null], [48658, 48717, null], [48717, 48877, null], [48877, 50193, null], [50193, 50291, null], [50291, 50336, null], [50336, 53463, null], [53463, 53530, null], [53530, 53695, null], [53695, 55995, null], [55995, 56067, null], [56067, 56129, null], [56129, 56177, null], [56177, 56602, null], [56602, 58016, null], [58016, 59469, null], [59469, 60155, null], [60155, 60223, null], [60223, 62221, null], [62221, 64277, null], [64277, 64329, null], [64329, 64449, null], [64449, 64524, null], [64524, 64646, null], [64646, 66595, null], [66595, 66595, null], [66595, 67940, null], [67940, 67940, null], [67940, 69874, null], [69874, 72369, null], [72369, 72850, null], [72850, 72850, null], [72850, 75392, null], [75392, 75392, null], [75392, 75784, null], [75784, 75784, null], [75784, 76158, null], [76158, 76158, null], [76158, 76377, null], [76377, 76377, null], [76377, 76776, null], [76776, 76776, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 76776, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 76776, null]], "pdf_page_numbers": [[0, 232, 1], [232, 232, 2], [232, 962, 3], [962, 962, 4], [962, 3045, 5], [3045, 3639, 6], [3639, 3639, 7], [3639, 3639, 8], [3639, 6072, 9], [6072, 7066, 10], [7066, 9426, 11], [9426, 12409, 12], [12409, 15309, 13], [15309, 16339, 14], [16339, 18969, 15], [18969, 21262, 16], [21262, 22850, 17], [22850, 26756, 18], [26756, 27171, 19], [27171, 27614, 20], [27614, 30163, 21], [30163, 33788, 22], [33788, 36550, 23], [36550, 37157, 24], [37157, 40808, 25], [40808, 41428, 26], [41428, 44017, 27], [44017, 45885, 28], [45885, 45997, 29], [45997, 46111, 30], [46111, 46810, 31], [46810, 46866, 32], [46866, 47584, 33], [47584, 47643, 34], [47643, 48658, 35], [48658, 48717, 36], [48717, 48877, 37], [48877, 50193, 38], [50193, 50291, 39], [50291, 50336, 40], [50336, 53463, 41], [53463, 53530, 42], [53530, 53695, 43], [53695, 55995, 44], [55995, 56067, 45], [56067, 56129, 46], [56129, 56177, 47], [56177, 56602, 48], [56602, 58016, 49], [58016, 59469, 50], [59469, 60155, 51], [60155, 60223, 52], [60223, 62221, 53], [62221, 64277, 54], [64277, 64329, 55], [64329, 64449, 56], [64449, 64524, 57], [64524, 64646, 58], [64646, 66595, 59], [66595, 66595, 60], [66595, 67940, 61], [67940, 67940, 62], [67940, 69874, 63], [69874, 72369, 64], [72369, 72850, 65], [72850, 72850, 66], [72850, 75392, 67], [75392, 75392, 68], [75392, 75784, 69], [75784, 75784, 70], [75784, 76158, 71], [76158, 76158, 72], [76158, 76377, 73], [76377, 76377, 74], [76377, 76776, 75], [76776, 76776, 76]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 76776, 0.06438]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
0215155045599c3ebe032243cec3d1ce81a47402
|
Sentential logic
Goal: to become familiar with *propositional logic* proofs.
- *Boolean constants*
- *conjunctions*
- *conditionals*
- *disjunctions*
- *negations*
- *biconditionals*
- recursive proof methods
- proof heuristics
Recursive proof methods
Consider an iterative version of double negation: a method \( dn^* \) that takes a premise with an arbitrary number of pairs of negation signs in front of it, and eliminates all such pairs by repeated applications of \( dn \).
- Applying \( dn^* \) to \( \sim \sim A \) gives \( A \), (same as calling \( dn \).)
- Applying \( dn^* \) to \( \sim \sim \sim A \) gives \( \sim A \) (same as calling \( dn \));
- Applying \( dn^* \) to \( \sim \sim \sim \sim A \) gives \( A \);
- Applying \( dn^* \) to \( \sim \sim \sim \sim \sim A \) gives \( \sim A \); and so on.
The method should have no effect on an input that does not have at least two negation signs in front of it. For example, applying \( dn^* \) to \( A \) should result in \( A \).
Recursive proof methods
The following implementation of dn* fits the bill:
```ocaml
define (dn* premise) :=
match premise {
(~ (~ p)) => let { _ := conclude p
(!dn premise) }
(!dn* p)
| _ => (!claim premise)
}
```
- When the given premise has at least two negation signs in front of it, that is, when it is of the form (\(~ \sim p\)), dn* does two things:
- it derives the conclusion \( p \) by applying dn to the premise;
- it recursively calls itself with \( p \) as the input.
- When all double negation signs have been eliminated dn* will simply claim the given premise.
Recursive proof methods
A more succinct way of defining $\text{dn}^*$ is the following:
```plaintext
define (dn* premise) :=
match premise {
(\sim (\sim p)) => (!dn* (!dn premise))
| _ => (!claim premise)
}
```
In general, a deduction of the form
```plaintext
let {_ := conclude p D} (!M p)
```
is equivalent to $(!M D)$.
- Recall the assumption base when evaluating $M$ will include the conclusion of $D$ (by *dynamic assumption scoping*).
- Successive recursive calls of $\text{dn}^*$ are made in increasingly larger assumption bases.
Recursive proof methods
Consider a method that takes a conditional premise of the form
\[(p \implies q \implies r)\]
and derives \((p \land q \implies r)\).
This is traditionally known in logic as *importation*.
```plaintext
define (import premise) :=
match premise {
(p \implies (q \implies r)) => assume (p \land q)
let {q=>r := (!mp premise p)}
(!mp q=>r q)
}
```
Recursive proof methods
Suppose now that we want a more general version of this method, one that can take an arbitrary conditional of the form
\[(p_1 \implies p_2 \implies p_3 \implies \cdots)\]
and repeatedly apply importation. For example, obtaining \([(p_1 \& p_2 \& p_3) \implies p_4]\) from \[(p_1 \implies p_2 \implies p_3 \implies p_4)\].
A recursive method is again the solution:
```plaintext
define (import* premise) :=
match premise {
(p1 => (p2 => p3)) => (!import* (!import premise))
| _ => (!claim premise)
}
```
A “bidirectional” double-negation method
- \( \text{dn} \) works only in one direction: It goes from a doubly negated premise \( (\sim \sim p) \) to \( p \).
- It is often useful to be able to go in the other direction whereby we insert two negation signs in front of an arbitrary premise.
- The method \( \text{idn} \) below implements that direction:
```lisp
define (idn premise) :=
(by-contradiction (\sim \sim premise))
assume \neg\neg premise := (\sim premise)
(absurd premise \neg\neg premise))
```
A “bidirectional” double-negation method
It is also useful to have a “bidirectional” double-negation method, bdn, which
• inserts two negation signs in front of the given premise $p$ only when $p$ is not already doubly negated;
• if it is, then it applies $dn$ to it to remove the two leading negation signs:
```plaintext
define (bdn premise) :=
match premise {
(~ (~ _)) => (!dn premise)
| _ => (!idn premise)
}
```
A “bidirectional” double-negation method
Sample use:
> assume h := (~ ~ A)
(!bdn h)
Theorem: (if (not (not A)) A)
> assume A
(!bdn A)
Theorem: (if A (not (not A)))
The replacement rule
The replacement rule lets us replace an arbitrary part \( q \) of a premise \( p \) by any equivalent sentence \( q' \).
For example, suppose we have
\[
p = (A \land \neg \neg B)
\]
in the assumption base. Since \((\neg \neg B)\) is equivalent to \(B\), and specifically since we know how to derive each from the other, via the bdn method, we should be able to conclude
\[
(A \land B).
\]
The conclusion is obtained from \( p \) by replacing the double negation \((\neg \neg B)\) with the equivalent \(B\).
The replacement rule
- Our reasoning can be roughly expressed as follows: (2) follows from (1) by virtue of the bdn method.
- More precisely, this inference will be captured by the method call
\[ \text{(!transform } (A \& \neg \neg B) (A \& B) [\text{bdn}]) \].
- This should be read as: “Transform the first argument (the premise) into the second one by replacement, using the method bdn.”
The replacement rule
As another example, suppose the following conditional is in the assumption base:
\((\neg \neg A \implies \neg (B \& C))\). \hspace{1cm} (3)
From De Morgan’s laws, we know that the consequent is equivalent to \((\neg B \mid \neg C)\), while from double negation we know that the antecedent is equivalent to \(A\). The transform method will allow us to derive
\((A \implies \neg B \mid \neg C)\)
simply by citing these two methods, \(\text{dm} \) (De Morgan) and \(\text{bdn} \) (double negation):
\((!\text{transform} (\neg \neg A \implies \neg (B \& C)) \ (A \implies \neg B \mid \neg C) \ [\text{bdn dm}]).\)
The replacement rule
In general, then, calls to transform will be of the form
\[(!\text{transform } p \ q \ [M_1 \cdots M_n])\]
and should be read as: “Transform \( p \) into \( q \) by replacement, using the methods \( M_1 \cdots M_n \).”
- The desired conclusion \( q \) should be obtainable from \( p \) by replacing \( k \geq 0 \) subsentences of it, \( p_1, \ldots, p_k \), by sentences \( q_1, \ldots, q_k \), where each equivalence \( (p_i \iff q_i) \), \( i = 1, \ldots, k \), is provable by some method \( M_j \), \( j \in \{1, \ldots, n\} \).
- The starting sentence \( p \) must be in the assumption base, and each \( M_i \) will (usually) be a bidirectional unary method, such that if \( (!M_i \ p) = q \) then \( (!M_i \ q) = p \), in all appropriate assumption bases.
Implementing the replacement rule
We will use a ternary method prove-equiv, which
- takes two sentences $p$ and $q$ as inputs and a list of two-way methods $[M_1 \cdots M_n]$ and
- derives the biconditional $(p \iff q)$, provided that $q$ is obtainable from $p$ by replacing $k \geq 0$ subsentences of it, $p_1, \ldots, p_k$, by sentences $q_1, \ldots, q_k$, where each equivalence $(p_i \iff q_i)$ is provable by some $M_j, j \in \{1, \ldots, n\}$.
With prove-equiv, we can readily implement transform:
```plaintext
#define (transform p q methods) :=
let {E := conclude (p \iff q)
(!prove-equiv p q methods)}
conclude q
(!mp (!left-iff E) p)
```
Implementing prove-equiv
- If there is some method $M_j$ that can derive $q$ from $p$ and vice versa, we prove the equivalence of $p$ and $q$ by applying that method.
- If not, then we check if $p$ and $q$ are syntactically identical, and if so, we can readily prove $(p \iff p)$ for any $p$ by:
```
define (ref-equiv p) :=
(!equiv assume p (!claim p)
assume p (!claim p))
```
- Finally, if $p$ and $q$ are neither $M_j$-interconvertible nor syntactically identical, they must be nonatomic sentences obtained by applying the same sentential constructor, i.e., they must both be negations, or both conjunctions, etc.
Implementing prove-equiv
Say $p$ and $q$ are both negations of the form $(\neg p_1)$ and $(\neg q_1)$, respectively.
- We then recursively apply prove-equiv to $p_1$ and $q_1$ (and the same list of methods $[M_1 \cdots M_n]$), which will presumably result in the biconditional $(p_1 \iff q_1)$.
- But then it is a simple matter to derive $(p \iff q)$, since for any $p_1$ and $q_1$, $(\neg p_1 \iff \neg q_1)$ is derivable from $(p_1 \iff q_1)$.
Implementing prove-equiv
The method not-cong to derive \((\sim p_1 \iff \sim p_2)\) from \((p_1 \iff p_2)\):
```plaintext
define (not-cong premise) :=
match premise {
(p1 \iff p2) =>
let {-p1=>-p2 := assume -p1 := (\sim p1)
(!by-contradiction (\sim p2)
assume p2
(!absurd (!mp (!right-iff premise) p2)
-p1));
-p2=>-p1 := assume -p2 := (\sim p2)
(!by-contradiction (\sim p1)
assume p1
(!absurd (!mp (!left-iff premise) p1)
-p2))}
(!equiv -p1=>-p2 -p2=>-p1)
}
```
CSCI.6962/4962 Software Verification—Fundamental Proof Methods in Computer Science (Arkoudas and Musser)—Chapter 4.10, 4.14 – p. 18/60
Implementing \texttt{prove-equiv}
The reasoning for conjunctions is similar. Say $p$ and $q$ are respectively of the form $(p_1 \ \& \ p_2)$ and $(q_1 \ \& \ q_2)$.
- We place two recursive calls to \texttt{prove-equiv},
- one applied to $p_1$ and $q_1$ (and the given list of methods);
- and the other applied to $p_2$ and $q_2$ (and said list).
- These will presumably result in the biconditionals $(p_1 \iff q_1)$ and $(p_2 \iff q_2)$, and
- From these two, the biconditional $(p \iff q)$ is deduced by the \texttt{and-cong} method.
Implementing \texttt{prove-equiv} and-cong method to derive \((p_1 \land p_2 \iff q_1 \land q_2)\) from \((p_1 \iff q_1)\) and \((p_2 \iff q_2)\)
define (and-cong premise1 premise2) :=
match [premise1 premise2] {
[(p1 \iff q1) (p2 \iff q2)] =>
let {p1&p2=>q1&q2 := assume (p1 & p2)
(!both (!mp (!left-iff premise1) p1)
(!mp (!left-iff premise2) p2));
q1&q2=>p1&p2 := assume (q1 & q2)
(!both (!mp (!right-iff premise1) q1)
(!mp (!right-iff premise2) q2));
(!equiv p1&p2=>q1&q2 q1&q2=>p1&p2)
} }
The treatment of the remaining cases is analogous, and requires corresponding congruence methods for disjunctions, conditionals, and biconditionals.
Implementing \texttt{prove-equiv}
We introduce an auxiliary method \texttt{find-first-element} that
- takes a unary method $M$ and an arbitrary list $L = [V_1 \cdots V_m]$ (of values of any type), and
- repeatedly applies $M$ to each $V_i$ in turn, $i = 1, \ldots, m$, until one such application succeeds, in which case the conclusion returned will be whatever result is produced by $(\neg M \; V_i)$.
- If $(\neg M \; V_i)$ fails for every $i = 1, \ldots, m$, then the entire call to \texttt{find-first-element} fails.
\begin{verbatim}
define (find-first-element M list) :=
match list {
(list-of first rest) =>
try { (!M first) | (!find-first-element M rest) }
}
\end{verbatim}
Implementing `prove-equiv`
Finally, we introduce an auxiliary selection procedure `choose-cong-method` that takes an arbitrary sentential constructor and chooses the appropriate congruence method:
```scheme
(define (choose-cong-method pc) :=
(match pc {
& => and-cong
| | => or-cong
| ==> => if-cong
| <=> => iff-cong
})
)```
Implementing `prove-equiv`
We can now define `prove-equiv` as follows:
```plaintext
define (prove-equiv p q methods) :=
try {
(!find-first-element method (M)
try {
(!equiv assume p (!M p)
assume q (!M q))
| (!equiv assume p (!M p q)
assume q (!M q p)) }
methods)
| check {
(p equals? q) => (!ref-equiv p)
| else => match [p q] {
| else => match [p q] {
[(~ p1) (~ q1)] =>
(!not-cong (!prove-equiv p1 q1 methods))
| [[(some-sent-con pc) p1 p2] (pc q1 q2)] =>
(!choose-cong-method pc)
(!prove-equiv p1 q1 methods)
(!!prove-equiv p2 q2 methods)) }
}
```
Proof heuristics for sentential logic
Recall the proof of the conditional
\((\sim B \implies A \implies \sim E)\)
from two premises. What process led us to this proof?
\begin{verbatim}
assert premise-1 := (A & B | (A ==> C))
assert premise-2 := (C <=> ~ E)
assume ~B := (~ B)
assume A
conclude ~E := (~ E)
(! cases premise-1
assume (A & B)
(! from-complements ~E B ~B)
assume A=>C := (A ==> C)
assume A=C := (A => C)
let {C=->E := (!left-iff premise-2);
C := (!mp A=>C A)}
(!mp C=->E C))
\end{verbatim}
Proof heuristics for sentential logic—Goal tree
Derive \( (\neg B \implies A \implies \neg E) \) from \( \beta = \{ (A \land B \lor A \implies C), (C \iff \neg E) \} \)
assume \( \neg B \)
\((\negforce A \implies \neg E)\)
Derive \( A \implies \neg E \) from \( \{ \neg B, (A \land B \lor A \implies C), (C \iff \neg E) \} \)
assume \( A \)
\((\negforce \neg E)\)
Derive \( \neg E \) from \( \{ A, \neg B, (A \land B \lor A \implies C), (C \iff \neg E) \} \)
\((\negforce \neg E))\)
# Sub-goal 1
assume \( A \implies C \)
\((\negforce \neg E))\)
# Sub-goal 2
Each \( \textbf{force} \) creates a new sub-goal. Both sub-goals must be proven.
Sub-goal 1 tree
Derive \((\neg E)\) from \\{(A \& B), A, (\neg B), (A \& B \mid A \implies C), (C \iff \neg E)\}\n
let \\{\_ := (!\text{force} B)\}
(!\text{from-complements} (\neg E) B (\neg B))
Derive B from \\{(A \& B), A, (\neg B), (A \& B \mid A \implies C), (C \iff \neg E)\}\n
let \\{\text{conj} := (!\text{force} (A \& B))\}
(!\text{right-and conj})
Derive \((A \& B)\) from\\{(A \& B), A, (\neg B), (A \& B \mid A \implies C), (C \iff \neg E)\}\n
(!\text{claim} (A \& B)) √
No \textbf{force} means that we are finished with the sub-goal proof.
Derive ($\neg E$) from $\{(A \implies C), A, (\neg B), (A \land B \mid A \implies C), (C \iff \neg E)\}$
\[
\text{let } \{\text{imp} := (!\text{left-iff } (C \iff \neg E));
\quad _ := (!\text{force } C)\}
\]
($!\text{mp imp C}$)
Derive $C$ from $\{(A \implies C), A, (\neg B), (A \land B \mid A \implies C), (C \iff \neg E)\}$
\[
\text{let } \{\text{imp} := (!\text{force } (A \implies C));
\quad _ := (!\text{force } A)\}
\]
($!\text{mp imp A}$)
Derive $(A \implies C)$ from $\{(A \land B), A, (\neg B), (A \implies C), (C \iff \neg E)\}$
($!\text{claim } (A \implies C)$) \checkmark
Derive $A$ from $\{(A \land B), A, (\neg B), (A \implies C), (C \iff \neg E)\}$
($!\text{claim } A$) \checkmark
Goal trees
*Goal trees* abstract over the process to construct a proof.
- Every node in such a tree contains a goal, which in the present context is a specification for a proof, or a *proof spec* for short.
- A proof spec is of the form “Derive $p$ from $\beta$” where
- $\beta$ is some assumption base, that is, a finite set of available assumptions, and
- $p$ is the desired conclusion that must be derived from $\beta$.
- We use the letter $\tau$ as a variable ranging over proof specs (goals), which by convention, are enclosed inside a box.
- Occasionally we also refer to the target conclusion $p$ in a proof spec as a “goal.”
Tactics
Applying a tactic to a proof spec $\tau$ produces two things:
1. A partial deduction $D$—partial in that it may contain $n \geq 0$ applications of force.
- This partial deduction $D$ is capable of deriving the target sentence $p$ from the corresponding assumption base $\beta$, provided that the $n$ applications of force have been successfully replaced by proper deductions.
2. A list of proof specs $\tau_1, \ldots, \tau_n$ that capture the proof obligations corresponding to the $n$ applications of force inside $D$.
- We refer to these new proof specs as the subgoals generated by the tactic.
**Tactics**
We tackle sub-goals $\tau_1, \ldots, \tau_n$ by applying new tactics to each $\tau_i$, thereby expanding the goal tree to deeper levels.
- The process ends when the deductions at the leaves of the tree contain no occurrences of **force**.
- This typically happens when the deductions are single applications of **claim**.
- We visually mark such leaves by placing the sign $\sqrt{}$ right next to the corresponding deductions.
When the process is complete, we can scan the tree bottom up completing partial deductions at every internal node, by incrementally eliminating applications of **force**, culminating with the top-level deduction at the root of the tree.
Tactics
In general, every time we are faced with a proof spec, there are two ways to proceed:
- **goal-driven**, or **backward**, or **analytic** approach
- it tries to move from the target conclusion toward the premises—it “analyzes” or decomposes the target sentence, usually breaking it up into smaller components.
- **information-driven** or **forward** or **synthetic** approach
- it moves from the premises toward the target conclusion—it tries to “synthesize” the conclusion by utilizing the premises.
**Backward tactics**
- In the goal-driven approach, we ignore the set of available assumptions $\beta$ (i.e., we ignore the available *information*), focusing instead on the syntactic form of the target sentence.
- In particular, we look at the main logical connective of that sentence, and we let that dictate the overall form that the desired deduction will take, by using the corresponding introduction mechanism or some closely related method.
- Since there are five logical connectives in sentential logic, there are five corresponding backward tactics, depending on the logical structure of the target conclusion.
Backward tactics—conjunctive goals
Conjunctive goals:
Derive \((p \& q)\) from \(\beta\)
let \{left := (!force \(p\));
right := (!force \(q\))\}
(!both left right)
The choice of deriving the left conjunct \((p)\) first is arbitrary. We could just as well choose to derive \(q\) first and \(p\) afterward. \([\text{and<->}]\) is a mnemonic name for the tactic (backward tactic applicable to conjunction.)
Backward tactics—disjunctive goals
Disjunctive goals:
Derive \((p \mid q)\) from \(\beta\)
\[
\begin{align*}
\text{let } \{ \_ & := (!\text{force } p) \} \quad \text{[lor<-]} \\
(!\text{left-either } p & \ q) \\
\end{align*}
\]
[lor<-] is a similar pattern that derives \(q\) first and then introduces \((p \mid q)\) via right-either.
An alternative—and often more effective—tactic for deriving a disjunction \((p \mid q)\) is to treat it as the conditional \((\neg p \Rightarrow q)\):
Derive \((p \mid q)\) from \(\beta\)
\[
\begin{align*}
\text{let } \{ \text{cond } := (!\text{force } (\neg p \Rightarrow q)) \} \quad \text{[or-if<-]} \\
(!\text{cond-def } \text{cond}) \\
\end{align*}
\]
Backward tactics—conditional goals
Derive \((p \implies q)\) from \(\beta\)
**assume** \(p\)
\((!\text{force } q)\) \[\text{[if<=]}\]
**Derive** \(q\) from \(\beta \cup \{p\}\)
Note the augmented assumption base in the child proof spec.
Backward tactics—negated goals
**Derive (∼ p) from β**
(!by-contradiction (∼ p)
assume p [not<->]
(!force false))
false is usually derived by absurd, so the task of the new proof spec will usually consist in the derivation of two contradictory sentences q and (∼ q), followed by an application of absurd. Later we will give a more specific tactic for deriving false.
Backward tactics—biconditional goals
Derive \((p \iff q)\) from \(\beta\)
\[
\text{let } \{ \text{left} := (! \text{force} (p \Rightarrow q)); \\
\text{right} := (! \text{force} (q \Rightarrow p)) \} \\
\text{(!equiv left right)}
\]
\([\text{iff<->}]\)
As with conjunctions, the ordering of the two subgoals is immaterial.
Forward tactics
In the information-driven approach,
• we focus on the set of available assumptions \( \beta \) and
• try to find one or more sentences in \( \beta \) that we can use to derive the goal.
Typically, the resulting proof will consist of a sequence of inference steps assembled together in a single proof block (or a \texttt{let} if we choose to use naming).
Forward tactics—claim
The ideal situation in forward proof search occurs when the assumption base contains the target sentence, in which case we can simply claim it:
\[
\text{Derive } p \text{ from } \{\ldots, p, \ldots\}
\]
\[(!\text{claim } p) \quad \checkmark \quad [\text{claim->}]\]
- Note that this tactic does not generate any subgoals, as there are no applications of force in the given deduction.
- Goals of this form (that generate no subgoals) will be called primitive.
- Thus, primitive goals become leaf nodes of goal trees.
Forward tactics—conjunctions
The next best-case scenario occurs when the assumption base contains a sentence from which the goal can be detached in one step, by a single application of an elimination method.
For instance, if our goal is $q$ and the assumption base contains a conjunction $(p \& q)$, then clearly we can derive $q$ in one step by applying right-and to $(p \& q)$.
We can depict this forward proof tactic as follows:
Derive $q$ from $\{\ldots, (p \& q), \ldots\}$
$(!\text{right-and } (p \& q)) \quad \checkmark$
Forward tactics—conjunctions
We generalize the preceding proof tactic for conjunctions as follows:
Derive \( q \) from \( \beta = \{\ldots, (\cdots (p \& q)^+ \cdots), \ldots\} \)
let \( \{\text{conj} := (!\text{force} (p \& q))\} \) \[\text{rand->}\]
\(!\text{right-and conj}\)
- We indicate that an occurrence of a sentence \( q \) inside a sentence \( p \) is positive by attaching a \( ^+ \) superscript to it. For example,
\[ p = (\cdots (A ==> B)^+ \cdots) \]
signifies that the superscripted occurrence of the conditional \((A ==> B)\) in the surrounding sentence \( p \) is positive.
- It suffices to consider only sentences with positive subsentences.
There is an obvious analogue for left conjuncts: \[\text{land->}\]
Forward tactics—conditionals
Suppose that the goal is to find a derivation of $q$ from some assumption base $\beta$.
- If the assumption base contains a positive occurrence of a conditional of the form $(p \implies q)$,
- then we can try to derive that conditional from $\beta$,
- then derive the antecedent $p$,
- and finally obtain $q$ via modus ponens:
\[
\text{Derive } q \text{ from } \beta = \{\ldots, (\cdots (p \implies q)^+ \cdots), \ldots\}
\]
let \{cond := (!\text{force} (p \implies q));
\text{ant} := (!\text{force} p)}\] [if-\implies]
(!mp cond ant)
Forward tactics—disjunctions
Suppose that the parent of the goal $q$ is a disjunction, say $(q \mid p)$. Then once we derive that disjunction from the assumption base, we can perform a case analysis. Specifically, we have to show that $q$ follows no matter which disjunct obtains, so we have to show that
- (a) $q$ follows from the first disjunct, $q$; and
- (b) $q$ follows from the second disjunct, $p$.
Part (a) is trivial, so (b) will usually be more challenging:
```
Derive $q$ from \{..., (\cdots (q \mid p)^+ \cdots), \ldots\}
let \{disj := (!\textbf{force} (q \mid p));
cnd1 := assume $q$ (!claim $q$);
cnd2 := (!\textbf{force} ($p \Rightarrow q$))\}
(!cases disj cnd1 cnd2)
```
**Forward tactics—biconditionals**
Finally, we have similar forward tactics involving biconditionals:
Derive $q$ from $\beta = \{\ldots, (\cdots (p \iff q)^+ \cdots), \ldots\}$
```plaintext
let \{bcond := (!force (p \iff q));
cond := (!left-iff bcond);
_ := (!force p)
} (!mp cond p)
```
As should be expected, there are corresponding $[\text{lor->}]$ and $[\text{riff->}]$ tactics.
Forward extraction tactics
The seven forward tactics are collectively called the *extraction tactics*. Given the goal of deriving some \( q \) from some \( \beta \), these tactics:
1. Find some element of \( \beta \) with a positive occurrence of a parent of the goal \( q \), specifically, a positive occurrence of a sentence of the following forms:
- \((p \land q)\) or \((q \land p)\);
- \((p \implies q)\);
- \((p \lor q)\) or \((q \lor p)\);
- \((p \iff q)\) or \((q \iff p)\).
2. Derive that parent, and possibly other additional subgoals.
3. Detach the goal \( q \) from the parent via the proper elimination method.
Forward tactics example goal tree
Derive \( C \) from \( \beta = \{ (A \implies (B \land C)^+), (A \land E) \} \)
let \{ \text{conj} := (!\text{force} (B \land C)) \}
(!\text{right-and conj})
Derive \( B \land C \) from \( \beta = \{ (A \implies (B \land C)^+), (A \land E) \} \)
let \{ \text{cond} := (!\text{force} (A \implies B \land C)); \text{ant} := (!\text{force} A) \}
(!\text{mp cond ant})
Derive \( A \implies B \land C \) from \( \{ (A \implies (B \land C)), (A \land E) \} \)
(!\text{claim} (A \implies B \land C)) √
Derive \( A \) from \( \{ (A \implies (B \land C)), (A \land E)^+ \} \)
let \{ \text{conj} := (!\text{force} (A \land E)) \}
(!\text{left-and conj})
Derive \( A \land E \) from \( \{ (A \implies (B \land C)), (A \land E) \} \)
(!\text{claim} (A \land E)) √
## Forward tactics example proof
The following is the final assembled proof:
```plaintext
let {conj := let {cond := (!claim (A ==> B & C)));
ant := let {conj := (!claim (A & E))}
(!left-and conj)}
(!mp cond ant)}
(!right-and conj)
```
or, if we remove the extraneous claims:
```plaintext
let {conj := (!mp (A ==> B & C)
(!left-and (A & E)))}
(!right-and conj)
```
Forward tactics—general disjunction
A more general forward tactic involving disjunctions is the following:
Derive $q$ from \{$\ldots, (\cdots (p_1 \mid p_2)^+ \cdots), \ldots$\}
let \{disj := (!force (p_1 \mid p_2));
cnd1 := (!force (p_1 ==> q));
cnd2 := (!force (p_2 ==> q))\}
(!cases disj cnd1 cnd2)
This tactic subsumes ![lor->] and ![ror->], both of which can be viewed as instances of ![or->].
It can be used with arbitrary disjunctions in (positive positions of) the assumption base.
Forward tactics—contradictions
Indirect proof, or proof by contradiction (we write $\overline{p}$ for the complement of $p$):
Derive $p$ from $\beta$
(!by-contradiction $p$
assume $\overline{p}$ [ift]
(!force false))
When the goal $p$ is a negation, this tactic reduces to the backward tactic [not<-].
But, unlike [not<-], this tactic can be used even when the goal is not a negation.
Forward tactics—contradictions
Both [if] and [not<-] seek to derive false from an assumption base.
Are there any heuristics offering guidance on how to derive false?
- Clearly, if the assumption base contains two complementary sentences then a single application of absurd will suffice, but what should be done in other cases?
- A simple heuristic is this: look for a negation ($\neg p$) in a positive position in the assumption base, derive it, and then try to derive $p$:
\[
\text{Derive false from } \beta = \{\ldots, (\cdots (\neg p)^+ \cdots), \ldots\}
\]
let \{neg := (!\textbf{force} (\neg p));
pos := (!\textbf{force} p);
(!\textbf{absurd} pos neg)\}
Forward tactics—contradictions
If we already have $\overline{p}$ in the assumption base and we can also derive the positively embedded $p$, then clearly the assumption base is inconsistent and any goal whatsoever can be derived from it:
\[
\text{Derive } q \text{ from } \beta = \{\ldots, \overline{p}, \ldots, (\cdots p^+ \cdots), \ldots\}
\]
\[
\text{let } \{_ := (!\text{force } p)\}\quad[\text{cft}]
\]
\[
(!\text{from-complements } q \ p \ \overline{p})
\]
This tactic is particularly apt when the assumption base directly contains $p$ as well as its complement $\overline{p}$, in which case the tactic takes the following form:
\[
\text{Derive } q \text{ from } \beta = \{\ldots, p, \ldots, (~p), \ldots\}
\]
\[
(!\text{from-complements } q \ p \ (~p))
\]
Replacement tactics
Recall that we are allowed to replace any part of a sentence by an equivalent part.
- We can take advantage of such replacements both in a forward and in a backward direction.
- First, in a backward direction, we can transform the goal $q$ to an equivalent goal $q'$ that may be easier to tackle.
- If and when we succeed in deriving $q'$, and assuming that $q'$ and $q$ are indeed equivalent in that each can be derived from the other by certain bidirectional methods $M_1, \ldots, M_n$, we can then transform $q'$ to the desired $q$.
Replacement tactics
Derive \( q \) from \( \beta \)
\[
\text{let } \{ \_ := (!\text{force } q') \} \quad \text{[replace<->]}
\]
\[
(!\text{transform } q' \quad q \quad [M_1 \cdots M_n])
\]
Likewise, in a forward direction, we can convert any element of the assumption base into an equivalent form and then proceed to tackle the goal anew:
Derive \( q \) from \( \beta = \{\ldots, p, \ldots\} \)
\[
\text{let } \{ \_ := (!\text{transform } p \quad p' \quad [M_1 \cdots M_n]) \} \quad \text{[replace->]}
\]
\[
(!\text{force } q)
\]
Heuristic for ranking tactics
Tactics should be considered for application in the following order:
- reiteration ([claim->]) and constant tactics ([true<-] and [false<-]);
- the complement tactic ([cft]);
- extraction tactics;
- replacement tactics;
- backward tactics, with the exception of [not<-];
- generalized disjunction tactic;
- indirect tactic and [not<-].
Heuristic for ranking tactics
- Replacement tactics should be used so as to make other tactics applicable.
- A particularly useful backward replacement is the transformation of a disjunctive goal into a conditional, via \texttt{cond-def}.
- Multiple extraction tactics might be applicable, so a selection algorithm is necessary for such cases.
- If a cycle is encountered, backtrack to the first occurrence of the duplicate subgoal and try another tactic.
Heuristic for ranking tactics
To select among multiple extraction tactics:
- When the assumption base has two or more parents of the goal in positive positions, choose the parent that is embedded in the least complex (smallest) sentence, unless there is a parent embedded in a pure conjunction, in which case that should be the selection.
- If two or more parents are positively embedded in sentences of the same complexity, break ties by choosing conjunctions over conditionals, conditionals over biconditionals, and any of these over disjunctions.
Applying the heuristic for ranking tactics
Consider the problem of finding a proof $D$ that derives the following goal from the given premises:
| assert premise-1 := (A | (B ==> C)) |
| assert premise-2 := (C <=> D & E) |
| assert premise-3 := (B & ~ A) |
| define goal := (B & D) |
Applying the heuristic for ranking tactics
let {left := (!left-and (B & ~ A));
right :=
let {conj :=
let {bcond := (!claim (C <==> D & E));
_ := let {disj := (!claim (A | (B ==> C)));
cnd1 := assume A
(!from-complements
(B ==> C)
A
(!right-and premise-3));
cnd2 := assume (B ==> C)
(!claim (B ==> C));
cond := (!cases disj cnd1 cnd2})
(!mp cond B})
(!mp (!left-iff bcond) C})
(!left-and conj)}
(!both B D)
Applying the heuristic for ranking tactics
Or, after a few simplifications and some general cleaning up:
```plaintext
let {left := (!left-and (B & ~ A));
right := let {B=>C := (!cases (A | (B ==> C))
assume A
(!from-complements
(B ==> C)
A
(!right-and premise-3))
assume h := (B ==> C)
(!claim h));
_ := (!mp B=>C B);
D&E := (!mp conclude (C ==> D & E)
(!left-iff premise-2)
C})
(!left-and D&E})
(!both B D)
```
CSCI.6962/4962 Software Verification—Fundamental Proof Methods in Computer Science (Arkoudas and Musser)—Chapter 4.10, 4.14 – p. 59/60
Proof heuristics summary
• Given that we typically have a choice of several tactics that we can apply to a given goal, we need some guidance on how to select a tactic judiciously.
• An inauspicious choice might result in a kludgy proof, or it might lead us to a dead end or get us stuck in a cycle. Then we have to backtrack and try another tactic.
• Choosing cleverly which tactics to apply can avoid such pitfalls and lead to success quickly and elegantly.
• Heuristics provide some guidance on this selection task. They are not guaranteed to always work (which is why they are only heuristics after all), but they are generally helpful.
|
{"Source-Url": "http://www.cs.rpi.edu/academics/courses/spring22/csci4962/chapter04b.pdf", "len_cl100k_base": 9680, "olmocr-version": "0.1.53", "pdf-total-pages": 60, "total-fallback-pages": 0, "total-input-tokens": 101755, "total-output-tokens": 12562, "length": "2e13", "weborganizer": {"__label__adult": 0.000507354736328125, "__label__art_design": 0.0007538795471191406, "__label__crime_law": 0.0009508132934570312, "__label__education_jobs": 0.004718780517578125, "__label__entertainment": 0.0002579689025878906, "__label__fashion_beauty": 0.00026297569274902344, "__label__finance_business": 0.0003826618194580078, "__label__food_dining": 0.0007786750793457031, "__label__games": 0.0021114349365234375, "__label__hardware": 0.0010576248168945312, "__label__health": 0.0007576942443847656, "__label__history": 0.0004935264587402344, "__label__home_hobbies": 0.0002388954162597656, "__label__industrial": 0.001041412353515625, "__label__literature": 0.0025310516357421875, "__label__politics": 0.0006003379821777344, "__label__religion": 0.0009670257568359376, "__label__science_tech": 0.221923828125, "__label__social_life": 0.0002486705780029297, "__label__software": 0.0127410888671875, "__label__software_dev": 0.7451171875, "__label__sports_fitness": 0.0004968643188476562, "__label__transportation": 0.0008993148803710938, "__label__travel": 0.000247955322265625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32384, 0.00671]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32384, 0.53903]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32384, 0.79532]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 230, false], [230, 1000, null], [1000, 1620, null], [1620, 2173, null], [2173, 2561, null], [2561, 3116, null], [3116, 3625, null], [3625, 4066, null], [4066, 4237, null], [4237, 4771, null], [4771, 5165, null], [5165, 5802, null], [5802, 6589, null], [6589, 7252, null], [7252, 7882, null], [7882, 8332, null], [8332, 9040, null], [9040, 9584, null], [9584, 10247, null], [10247, 10945, null], [10945, 11295, null], [11295, 11948, null], [11948, 12482, null], [12482, 13135, null], [13135, 13691, null], [13691, 14397, null], [14397, 15036, null], [15036, 15650, null], [15650, 16331, null], [16331, 16847, null], [16847, 17470, null], [17470, 17884, null], [17884, 18583, null], [18583, 18826, null], [18826, 19200, null], [19200, 19527, null], [19527, 19901, null], [19901, 20443, null], [20443, 20976, null], [20976, 21717, null], [21717, 22287, null], [22287, 22988, null], [22988, 23379, null], [23379, 24019, null], [24019, 24818, null], [24818, 25198, null], [25198, 25708, null], [25708, 26097, null], [26097, 26762, null], [26762, 27531, null], [27531, 28090, null], [28090, 28625, null], [28625, 28993, null], [28993, 29454, null], [29454, 30007, null], [30007, 30308, null], [30308, 30978, null], [30978, 31741, null], [31741, 32384, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 230, true], [230, 1000, null], [1000, 1620, null], [1620, 2173, null], [2173, 2561, null], [2561, 3116, null], [3116, 3625, null], [3625, 4066, null], [4066, 4237, null], [4237, 4771, null], [4771, 5165, null], [5165, 5802, null], [5802, 6589, null], [6589, 7252, null], [7252, 7882, null], [7882, 8332, null], [8332, 9040, null], [9040, 9584, null], [9584, 10247, null], [10247, 10945, null], [10945, 11295, null], [11295, 11948, null], [11948, 12482, null], [12482, 13135, null], [13135, 13691, null], [13691, 14397, null], [14397, 15036, null], [15036, 15650, null], [15650, 16331, null], [16331, 16847, null], [16847, 17470, null], [17470, 17884, null], [17884, 18583, null], [18583, 18826, null], [18826, 19200, null], [19200, 19527, null], [19527, 19901, null], [19901, 20443, null], [20443, 20976, null], [20976, 21717, null], [21717, 22287, null], [22287, 22988, null], [22988, 23379, null], [23379, 24019, null], [24019, 24818, null], [24818, 25198, null], [25198, 25708, null], [25708, 26097, null], [26097, 26762, null], [26762, 27531, null], [27531, 28090, null], [28090, 28625, null], [28625, 28993, null], [28993, 29454, null], [29454, 30007, null], [30007, 30308, null], [30308, 30978, null], [30978, 31741, null], [31741, 32384, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32384, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 32384, null]], "pdf_page_numbers": [[0, 0, 1], [0, 230, 2], [230, 1000, 3], [1000, 1620, 4], [1620, 2173, 5], [2173, 2561, 6], [2561, 3116, 7], [3116, 3625, 8], [3625, 4066, 9], [4066, 4237, 10], [4237, 4771, 11], [4771, 5165, 12], [5165, 5802, 13], [5802, 6589, 14], [6589, 7252, 15], [7252, 7882, 16], [7882, 8332, 17], [8332, 9040, 18], [9040, 9584, 19], [9584, 10247, 20], [10247, 10945, 21], [10945, 11295, 22], [11295, 11948, 23], [11948, 12482, 24], [12482, 13135, 25], [13135, 13691, 26], [13691, 14397, 27], [14397, 15036, 28], [15036, 15650, 29], [15650, 16331, 30], [16331, 16847, 31], [16847, 17470, 32], [17470, 17884, 33], [17884, 18583, 34], [18583, 18826, 35], [18826, 19200, 36], [19200, 19527, 37], [19527, 19901, 38], [19901, 20443, 39], [20443, 20976, 40], [20976, 21717, 41], [21717, 22287, 42], [22287, 22988, 43], [22988, 23379, 44], [23379, 24019, 45], [24019, 24818, 46], [24818, 25198, 47], [25198, 25708, 48], [25708, 26097, 49], [26097, 26762, 50], [26762, 27531, 51], [27531, 28090, 52], [28090, 28625, 53], [28625, 28993, 54], [28993, 29454, 55], [29454, 30007, 56], [30007, 30308, 57], [30308, 30978, 58], [30978, 31741, 59], [31741, 32384, 60]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32384, 0.00651]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
fafa428bcb34224068f7fb4ef5cd28f1dd68c814
|
Trade-off Analysis for Selective versus Brute-Force Regression Testing in FSMWeb
Anneliese Andrews
Department of Computer Science
University of Denver
Denver, CO 80208
andrews@cs.du.edu
Hyunsook Do
Department of Computer Science
North Dakota State University
Fargo, ND 58102
hyunsook.do@ndsu.edu
Abstract—This paper provides a tradeoff framework to determine whether selective regression testing or brute force regression testing is preferable. The framework is based on classifying tests as reusable, retestable, and obsolete. To illustrate how our tradeoff framework works for evaluating and choosing regression testing approaches for FSMWeb models, we use an example that has different modification scenarios in the FSMWeb model and analyze cost-benefit tradeoffs for the techniques that vary with the amount of changes and the impact of model changes. Further, we discuss practical issues to be considered when we choose regression testing techniques so that the employed technique meets the organization's business values.
Index Terms—regression testing, web applications, trade-off analysis
I. INTRODUCTION
Over the past decades, web applications have been widely used because web applications offer easy access for users and diverse services. Typically, web applications go through more frequent updates compared to traditional desktop applications due to various reasons, such as continual feature upgrade demands from users or security problems. This necessitates more frequent regression testing to ensure the quality of the modified applications. However, regression testing is costly, and in particular for large web applications, applying regression testing to the entire application with all existing test cases can be prohibitively expensive [1]. Further, organizations could lose their business opportunities or customers if they fail to supply new releases in a timely manner due to a lengthy regression testing process. (Note that a recent study [2] reports that small/medium-sized organizations lost, on average, $70,000 per downtime hour.)
To resolve this issue, we can employ different regression testing approaches, such as selective regression testing, or prioritizing test cases that are more important to run early. However, it is difficult to know in advance which techniques would be more cost-effective than others. To date, many empirical studies on regression testing [3], [4], [5] have evaluated various regression testing techniques in terms of their effectiveness and efficiency, but often, the studies used simple measures of testing effort, such as the number of test cases or the time required for testing. Some studies have evaluated the cost-benefit tradeoffs for techniques using explicit cost models [6], [7], [8]. Although these models provide more proper ways to evaluate the techniques, they allow evaluation only after applying the techniques to the applications rather than choosing the proper techniques beforehand.
In this paper, we propose a tradeoff analysis framework to determine a proper regression testing technique by considering various cost factors that are associated with software artifact analysis and technique application. The framework is based on classifying tests as reusable, retestable, and obsolete. It uses the FSMWeb model as the behavioral model upon which test generation is based. The FSMWeb model is used to model and generate tests for web applications. We apply the proposed tradeoff framework to an example that contains different modification scenarios in the FSMWeb model and analyze the cost-benefit tradeoffs for the two regression testing techniques (brute force and selective techniques), which vary with the amount of change and the impact of model changes. Further, we discuss the practical issues for choosing a regression testing technique considering various factors that can be affected by an organization’s business values.
The next section describes the FSMWeb method. Sections III, IV, and V present details about the tradeoff framework, including practical considerations of cost-benefit tradeoffs for selecting regression testing techniques. Section VI describes the related work and Section VII presents conclusions and future work.
II. FSMWEB
A. FSMWeb Approach
Functional testing for web application follows the approach in [9]:
1) Build a hierarchical model $HFSM$:
a) Partition the web application into clusters ($Cs$).
b) Define Logical Web Pages ($LWPs$) and Input-Action constraints for each.
c) Build FSMs for clusters as a multi-level hierarchy.
d) Build an Aggregate FSM ($AFSM$) to represent the top level of the application.
2) Generate tests from the $HFSM$.
a) Generate paths through each FSM that meet the coverage criteria.
The final step of test generation is selecting inputs to replace paths in a set of aggregate paths. We call them abstract tests or all combinations edge coverage such as through each FSM based on some graph coverage criterion.
Many web pages contain HTML forms, each of which can be connected to a different back-end software module. To facilitate testing for these modules, web pages are modeled as multiple Logical Web Pages (LWPs). A LWP is either a physical web page or the portion of a web page that accepts data from the user through an HTML form and then sends the data to a specific software module. LWPs are abstracted from the presentation defined by the HTML and are described in terms of their sets of inputs and actions. All inputs in a LWP are considered atomic: data entered into a text field is considered to be only one user input symbol, regardless of how many characters are entered into the field.
The lowest level cluster FSMs are generated with only LWPs and navigation between them. Input-action constraints annotate each edge [9]. Higher level FSMs represent FSMs from a lower level cluster by a single node and may contain LWP nodes as well. Ultimately, a top level Aggregate Finite State Machine (AFSM) is formed and represents a finite state model of the application at the highest level of abstraction.
Test sequences are generated during phase 2 of the FSMWeb method. A test sequence is a sequence of transitions through the application FSM and through each lower level FSM. FSMWeb’s test generation method first generates paths through each FSM based on some graph coverage criterion such as edge coverage. These paths are then aggregated based on an aggregation criterion for each FSM’s paths, such as all combinations or each path at least once [9]. This process results in a set of aggregate paths. We call them abstract tests. The final step of test generation is selecting inputs to replace the input constraints for the transitions of the aggregate paths.
Hence, an $HFSM = \{FSM_i\}_{i=0}^n$ with a top level $FSM_0 = AFSM$. Each FSM has nodes that represent LWPs or clusters. Edges are internal or external to an FSM. External nodes span cluster boundaries. Figure 1 shows how an FSM model that represents a selection with only three choices is reduced to two nodes and one transition in FSMWeb.
### III. Approach
#### A. Classification of Tests after Model Changes
In [10], rules classifying of obsolete, retestable, and reusable test cases are defined. Together with the existing regression testing framework [11], [12] Andrews et al. [10] form the basis for selective regression testing for FSMWeb. We summarize the approach briefly because it is the basis upon which we built the tradeoff analysis:
- $T_0$ is the original test suite; $T_{ru}$ is the retestable test set; $T_{ob}$ is the obsolete test set; $T_{ru}$ is the reusable test set.
In FSMWeb, test cases are generated in stages. We have to determine the level of abstraction at which $HFSM$ changes are mapped to regression test case classification. Section II introduced an abstract test case, $t_a$, as a test path through the $HFSM$ that represents an aggregated path.
There is a one to many relationship between abstract test case $t_a$ and test case $t$. (The input conditions may be satisfied with more than one set of values.) Hence, a path change (either due to changes in a node or an edge) may affect one or more test cases. If a change in the $HFSM$ FSMWeb model affects an abstract test case, $t_a$, it also affects the set of executable test cases, $T_a$, associated with it.
Changes to nodes and edges are classified as obsolete, retestable, or reusable:
1) Classify types of changes:
a) node change: delete or modify (i.e., change the node type from LWP to cluster or vice versa). Node addition is covered by edge changes.
b) edge change: modify in/out edge (i.e., modify the edge’s input-action constraint$^1$), delete in/out edge, add in/out edge with or without a new node
c) classify model changes as path affecting (PC) or non-path affecting (NC).
2) Classify abstract test cases as obsolete, retestable, or retestable. Map this classification to the associated tests.
Table I shows the notations and conventions used in [10]. We also assume that any changes to the $HFSM$ transformed it into a valid $HFSM'$ (e.g., no unreachable nodes or dangling edges). For details, see [9]. The test classification rules are as follows.
### Obsolete Test Cases
They are caused by node or edge deletions and modifications. Let $N_o = \{n | n \in N; n$ is deleted or modified$\}$; then, the set
1$^1$Modifying the source or target node of an edge, that is, redirecting the edge, is covered by edge deletion and subsequent edge addition.

of obsolete, abstract test cases due to node changes is given by $O_N = \{ t_o | \exists n \in N_o : t_o \text{ visits } n \}$.
Let $E_o = \{ e | e \in E ; e \text{ is deleted or modified} \}$; then, the set of obsolete abstract test cases due to edge changes is given by $O_E = \{ t_o | t_o \text{ tours } e \in E_o \}$. Hence, the set of obsolete, abstract test cases is given by $O_{AT} = O_N \cup O_E$.
Further, let the set of abstract test cases be $AT = \{ t_a | t_a \text{ is the set of executable tests associated with } t_o (i = 1, \ldots, k) \}$. Consequently, the obsolete test cases are given by $O_T = \{ t | \exists t_o \in O_{AT} : t \in T_o \}$.
### Retestable Test Cases
[10] defines retestable tests as those that are still valid and test portions of the application that may tour portions of the FSMWeb model that are close to the changes. As an example, assuming edge coverage, they consider how any node $n$ that is one edge away from a modified or deleted node must be retested, except for the source and sink nodes of the AFSEM:
$$N_{r_{node}} = \{ n | \exists e : (n, \hat{n}) \text{ or } (\hat{n}, n) ; \hat{n} \in N_o ; n \neq n_{source} ; n \neq n_{sink} \}$$
When edges are changed, the set of retestable edges depends on the type of change. When edges are deleted or modified, it is assumed that the starting and ending nodes of the changed edges are potentially affected, hence non-obsolete tests that visit these nodes are retestable (except for the AFSEM’s source and sink nodes):
$$N_{r_{edm}} = \{ n | \exists e : e = (n, \hat{n}) \text{ or } e = (\hat{n}, n) ; n \neq n_{source} ; n \neq n_{sink} \}$$
Similarly, when edges (and possibly nodes) are added, the existing nodes at which these new edges start or end are considered potentially affected by the change, hence non-obsolete tests that visit these nodes are retestable (except for the AFSEM’s source and sink nodes):
$$N_{r_{a}} = \{ n | \exists e' : e' = (n, n') \text{ or } e' = (n', n) ; n \neq n_{source} ; n \neq n_{sink} \}$$
In other words, $n$ appears in both $HFSM$ and $HFSM'$ related to edge changes. The set of retestable nodes is then given by $N_r = N_{r_{node}} \cup N_{r_{edm}} \cup N_{r_{a}}$, and the set of retestable abstract test cases is $R_{AT} = \{ t_o | t_o \text{ visits } n \in N_r \} \setminus O_{AT}$.
The corresponding executable retestable tests are determined as a function of $R_{AT}$ as before.
### Reusable Tests
Reusable tests are neither obsolete nor retestable.
$$U_{AT} = AT \setminus (O_{AT} \cup R_{AT})$$
### B. Selective versus Brute Force Regression Testing
Intuitively speaking, selective regression testing is preferable if model changes are isolated, if few tests are obsolete, and/or if additions have few overlaps with existing parts of the model. Conversely, when model changes impact many of the abstract test paths, rendering them obsolete, or when additions to the model connect with many parts of the existing model, brute force or systematic regeneration of tests may be better. Likewise, using a brute force approach when we have many obsolete tests, may be a waste of time and it would be better to regenerate the test suite from scratch. In order to quantify the tradeoff properly, both testing processes must be defined so that costs can be associated with the steps of each process. Note that brute force regression testing determines whether a test is obsolete based on validating results of its execution while selective regression testing determine a tests obsoleteness based on classification rules for changes to the FSMWeb model (i.e., without execution).
### Brute Force Regression Testing
1. Execute the original test suite, $T_0$, with cost $c_v(T_0)$.
2. Validate $T_0$ ($c_v(T_0)$): This process involves determining whether a test passed or failed and whether failure is due to obsolescence or a defect ($c_v(T_0) = c_v(T_p) + c_v(T_f)$). Also note that $T_p$ is comprised of retestable and reusable tests (although they have not been classified as such) and $T_f$ is comprised of failing tests and obsolete tests (again, brute force regression testing does not classify them ahead of execution).
3. Generate new tests to replace $T_{ob}$, and obtain coverage of uncovered parts of the model ($T''$).
4. Execute and validate $T''$. Let the cost of generating, executing, and validating $T''$ be $c_n(T'')$.
Hence, the cost of brute force testing is $B = c_v(T_0) + c_v(T_0) + c_n(T'')$.
### Selective Regression Testing
1. Classify $T_{ob}$, $T_{rt}$, and $T_{ru}$ at a cost, $c_{class}(T_0)$.
2. Execute $T_{rt}$ at cost $c_e(T_{rt})$.
3. Validate $T_{rt}$ at cost $c_v(T_{rt})$.
4. Generate new tests, $T''$, to replace $T_{ob}$ and missing coverage.
5. Execute and validate $T''$. Let the cost of generating, executing, and validating $T''$ be $c_n(T'')$.
Hence, the cost of selective regression testing is $S = c_{class}(T_0) + c_e(T_{rt}) + c_v(T_{rt}) + c_n(T'')$.
Selective regression testing is preferable when $S < B$. Substituting the formulas for both types of regression testing and simplifying by eliminating the identical terms on both sides of the inequality produces:
$$c_{class}(T_0) + c_e(T_{rt}) + c_v(T_{rt}) < c_v(T_0) + c_e(T_0)$$
Simplifying further shows that selective regression testing is better when
\[ c_{\text{class}}(T_0) < c_e(T_0 \setminus T_{rt}) + c_v(T_0 \setminus T_{rt}) \]
Note that we were able to simplify the formula by using the following rules of thumb when generating new tests:
- The cost of generating new tests for missing coverage due to obsolete tests is comparable for brute force and selective regression Testing.
- The cost of generating new tests due to uncovered test requirements (because none exist in the prior version) is comparable as well.
C. Tradeoff Computations for Decision Making
Having a tradeoff inequality such as the one we derived above is only the first step to make good decisions. The costs actually have to be measured, and parameters in the cost functions have to be estimated. We can streamline this by making simplified assumptions. (These assumptions will be evaluated and adjusted through empirical studies.) These will have to be checked when using the formulas. If they do not hold, the estimate may be off. We can simplify the tradeoff formula further by making assumptions about the cost of executing and validating a test. Let \( t \in T \) be a test in test suite \( T \).
Assumption 1 (option 1): The cost of executing \( t \), \( c_e(t) \), and the cost of validating \( t \), \( c_v(t) \), are proportional to the length of test case \( t \).
\[
c_e(t) = a \ast \text{len}(t) = a \ast \sum_{e \in t} e \quad \text{and} \quad c_v(t) = b \ast \text{len}(t) = b \ast \sum_{e \in t} e
\]
where \( e \) is an edge in the model, and \( a \) and \( b \) are positive calibration parameters.
Alternatively, length could be measured by the number of nodes in test \( t \). Each abstract test path contains edge predicates that specify the input parameter(s) that must be selected for the transition to occur. Option 1 assumes that differences for input number and size average out, hence an average cost for executing and validating edges can be used. If this assumption does not hold, it becomes necessary to consider the inputs instead of edges.
Assumption 1 (option 2): The cost of executing and validating test \( t \) is proportional to the number of inputs on each edge annotation. Let \( I_e \) be the set of input parameters for edge \( e \) and \( \text{card}(I_e) \) be the number of such inputs. Then,
\[
c_e(t) = d \ast \sum_{e \in t} \text{card}(I_e) \quad \text{and} \quad c_v(t) = f \ast \sum_{e \in t} \text{card}(I_e)
\]
As before, \( e \) is an edge in \( t \) while \( d \) and \( f \) are positive calibration parameters. Similarly, we can make a simplifying assumption about the classification cost.
Assumption 2: The cost of classification, \( c_{\text{class}} \), is proportional to the size of the existing test suite, \( T_0 \). Hence,
\[
c_{\text{class}} = x \ast \text{card}(T_0)
\]
for some positive \( x \).
This formula assumes that differences in classification cost due to the length of a test suite average out. As before, when this assumption does not work well, we can use the length of the test case instead:
\[
c_{\text{class}} = y \ast \sum_{t \in T_0} \text{len}(t)
\]
for some positive \( y \).
Some implementations can classify tests in a fixed number of operations if they create a bit mask during test creation that identifies which nodes/edges are visited in a path, rendering the classification cost independent from the test case length.
D. Determining Calibration Parameters
Because the calibration parameters are not known a priori, we suggest to use a simple threshold of the change amount in the model, to accept that the first decision may not be optimal, and then to record the actual cost and determine the first estimators for the calibration parameters, improving them each round.
Whether calibration parameters for one project can be reused on another should be determined by project characteristics. If the projects are similar, one may start reusing parameters, improving them along the way. Otherwise, it may be better to start fresh. If the costs for selective and brute force approaches are close, making an incorrect decision involves minor cost differences, hence the cost penalty is small. What needs to be avoided are incorrect decisions that carry a sizable cost difference.
Most of our assumptions and tradeoff formulas are either independent from FSMWeb specifics or can easily be generalized to other graph models such as EFSMs or UML behavioral models.\(^2\) It stands to reason that this tradeoff approach could be adapted to other types of models. However, there is one FSMWeb characteristic that offers unique opportunities, its hierarchical nature and the opportunity for partial test path regeneration in the face of changes. This issue is discussed in the next subsection.
E. Partial Regeneration
Because of the hierarchical nature of the FSMWeb models and the associated three stage test generation, it is possible to use partial regeneration to replace obsolete test cases and, thus, potentially save costs. Also, note that FSMWeb generates a flattened version of concrete tests and avoids having to flatten the model from which the tests are generated. The flattened version is necessary to make them executable.
Recall that \( HFSM = \{FSM_i\}_{i=0}^2 \). If changes are isolated to a few \( FSM_i \), i.e., \( \forall FSM'_i : FSM'_i \neq FSM_i \) (\( FSM_i \) changed):
- classify abstract tests.
- regenerate paths through \( FSM'_i \) to cover uncovered edges.
- reaggregate abstract tests that contain the cluster node that stands for \( FSM_i \) with the new paths.
When there are changes in many \( FSM_i \) and/or at high levels of the hierarchy, this will approach full regeneration. Thresholds that determine whether partial or full regeneration is warranted could be defined. We need one threshold, \( B_1 \), for the proportion of \( FSM_i \) that changed and another for the degree of change, \( B_2 \), in \( FSM_i \).
\(^2\)The classification rules for types of model changes have to be restated in terms of these other models.
Then, as long as \( \frac{\text{No.of } FSM_{\text{changed}}}{n+1} = P\text{C}_{HFSM} < B_1 \), we will use partial regeneration. For partial regeneration to be better, its savings must be greater than the classification cost.
To assess the degree of change within an FSM, we can set the threshold for change based on the proportion of changed nodes or edges. In an HFSM with edges outnumbering nodes, a fair amount (navigation bars and links in web applications tend to lead to such a type of graph), using degree of edge change, is probably more fruitful, and we use it here. Further, note that only two types of node changes exist: An LWP becomes a cluster node or a cluster node becomes an LWP. Any global impact would have to show itself in terms of modifications of inputs along the way and be then reflected in edge changes.
Then, as long as \( B_2 > \frac{\text{No.of edges (deleted, added, modified)}}{\text{card}(E'_i)} = P\text{C}_{FSM_i} \), (where \( \text{card}(E'_i) \) is the number of edges in \( FSM'_i \)), we will use selective regression testing.
Setting these thresholds is initially a matter of how conservative the estimate should be. A low threshold will lead to more regeneration, a higher one to more partial reconstruction.
### IV. Example
In this section, we will illustrate our tradeoff framework using a simple example, Figure 2, which has five FSMs and three levels of hierarchy. Table II shows paths through each FSM that achieve edge coverage.
These test paths now have to be aggregated to form abstract tests through the HFSM. As aggregation coverage criterion we use the all-paths substitution. We illustrate this on \( t_{01} = n_1c_2n_2 \). Substituting \( t_{21} \) and \( t_{22} \) for \( c_2 \) results in two paths:
\[
\begin{align*}
p_1 &= n_1n_6n_7n_2, & p_2 &= n_1n_6c_3c_7n_2.
\end{align*}
\]
The first path consists of all LWP nodes and does not have to be refined. The second path uses cluster nodes \( c_4 \) and \( c_3 \), each of which resolved by substituting two paths each, resulting in four test paths. Hence, \( t_{01} \) results in five test paths when fully aggregated.
<table>
<thead>
<tr>
<th>FSM</th>
<th>Testpaths</th>
</tr>
</thead>
<tbody>
<tr>
<td>AFSM</td>
<td>( t_{01} = n_1c_2n_2 ), ( t_{02} = n_1c_1n_2 )</td>
</tr>
<tr>
<td>FSM_1</td>
<td>( t_{11} = n_1n_4c_2n_5n_4n_3 ), ( t_{12} = n_1n_4c_2n_5c_3n_3 )</td>
</tr>
<tr>
<td>FSM_2</td>
<td>( t_{21} = n_6n_7, t_{22} = n_6c_3c_7n_7 )</td>
</tr>
<tr>
<td>FSM_3</td>
<td>( t_{31} = n_8n_13n_14, t_{32} = n_8n_9n_10n_12n_9n_10n_11n_14 )</td>
</tr>
<tr>
<td>FSM_4</td>
<td>( t_{41} = n_15n_16n_17n_18, t_{42} = n_15n_16n_19n_17n_18 )</td>
</tr>
</tbody>
</table>
Aggregation of \( t_{02} \) is more involved, because it visits cluster node \( c_1 \) requiring aggregation of two test paths through \( FSM_1 \) which both use \( c_2 \) (2 paths), one of which uses \( c_4 \) and \( c_3 \) (the latter twice) with 2 paths each. This results in 20 paths when FSMs are fully aggregated. Table III shows these paths, including derivation rules and the test path lengths. The first five test paths are obtained by applying \( t_{01} \), and the rest of them are obtained by applying \( t_{02} \).
Next, consider each change. Change 1 is a change at the lowest level; \( t_{41} \) is obsolete; \( t_{42} \) is still valid. To achieve coverage, we can add \( t'_4 = n_15n_18 \). All paths that contain substitutions for \( t_{41} \) need to be reaggregated. This affects 8 paths, 2 based on \( t_{01} \) and 6 based on \( t_{02} \). Change 2 is also a change at the lowest level, because all nodes in \( FSM_3 \) are LWP nodes. The test path \( t_{32} \) in \( FSM_3 \) is obsolete. Two new test paths need to be generated. They replace \( t_{32} \) in the 11 obsolete tests, resulting in 22 new tests. Change 3 renders \( t_{22} \) through \( FSM_2 \) obsolete. Two new test paths are needed: \( t'_{21} = n_6c_4n_7 \) and \( t'_{22} = n_6c_3n_7 \).
All paths where cluster node \( c_2 \) was resolved with the obsolete path must be reaggregated, resulting in all new test paths, because both \( t_{01} \) and \( t_{02} \) include cluster node \( c_2 \) at some point in the aggregation. In addition, since the number of paths through \( FSM_2 \) increased from 2 to 3, the resulting number of aggregated test paths multiplies.
### Practical Thoughts on Combining Partial Regeneration with Selective Regression Testing
Test generation in FSMWeb naturally lends itself to partial regeneration, because it is based on three stages:
1. Generate paths through FSMs.
2. Aggregate paths into abstract tests.
3. Select inputs along paths.
In the example, when considering each change individually, only branches in a single FSM are uncovered after changes, hence it would be a waste of time to regenerate paths through FSMs that have not changed in step 1. Rather, it is a matter of how much reappragregation needs to occur. If the derivation history of each \( t \in T_0 \) was kept, this can mean that, in all \( t \in T_0 \) that contain an obsolete path through some \( FSM_i \), a valid new path through \( FSM_i \) is substituted. If more than one new path is generated, the number of new tests multiplies. Similarly, because the derivation history would indicate the point of first breakage for an obsolete test (i.e., where the
an additional path is needed, so there are two new paths:
\[ t_41 \] with the deleted edge \((n_{12}, n_{17})\). Substituting the new path, \( t_{42}' = n_{15}n_{18} \) for all occurrences of \( t_{42} \) together with the eight retestable paths provides the required coverage. Note that, because all nodes in \( FSM_4 \) are LWPs, no lower level substitutions need to take place. Value generation from the point of substitution will complete the test suite. Of course, for regression testing purposes, the reusable tests need not be run.
**Change 1:** There are eight tests that use \( t_{41} \) with the deleted edge \((n_{12}, n_{17})\). To cover the new edge \((n_{12}, n_{14})\), an additional path is needed, so there are two new paths: \( t_{42}' = n_{15}n_{17}n_{14} \) and \( t_{43}' = n_{16}n_{17}n_{12}n_{14} \).
Similar to change 1, we substitute each path for the obsolete \( t_{42} \), resulting in 26 new abstract tests. There are a total of 11 such paths. Two of them have double occurrences, resulting in four new paths each due to our aggregation coverage criterion. As in change 1, all nodes in \( FSM_5 \) are LWPs, so no lower level substitutions need to take place. Value generation from the first point of substitution completes the test suite. (Note that, because of possible dependencies of inputs selected between two substitutions in a test path, it is not possible to keep these old values.) There are no retestable tests, so the regression test suite consists of 26 tests.
**Change 3:** This change requires modifications through several substitution levels. This change makes \( t_{42} \) obsolete. Because a large portion of the tests is derived from \( t_0 = n_1c_2n_2 \), 16 of the 20 tests are obsolete, suggesting that a great deal more reaggregation is necessary. Because \( c_2 \) occurs at the highest level of aggregation, this really means that we have to reaggregate from \( t_{01} \) on down. At the same time, only \( FSM_2 \) needs path changes, namely two new paths: \( t_{22} = n_6c_3n_7 \) and \( t_{23} = n_6c_4n_7 \).
Because the new paths only refer to one lower level cluster each, there are only 4 new abstract tests to substitute for the obsolete ones, two for \( c_3 \) and 2 for \( c_4 \). Value generation has to be done almost from the beginning. There are no retestable tests, so the regression test suite consists of 32 tests.
Changes 2 and 3 affect more paths at more levels in the hierarchy than change 1, because cluster nodes associated with the changes occur in more of the \( FSMs \) or at higher levels.
So far, we have assumed single changes. What if all three changes occur at the same time? There are 17 obsolete test cases and 3 retestable ones. In this case, reaggregation needs to start with \( t_{01} \) and \( t_{02} \) at the top level, and value generation also must start almost from the beginning. However, we can still reuse paths through \( AFSM \) and \( FSM_1 \) as well as the ones in the modified \( FSMs \) that have not become obsolete.
Depending on the character of the changes, these can be found in retestable or reusable tests. In total, the modified \( FSMs \) require 30 test cases: six for \( t_{01} \) and 24 for \( t_{02} \).
In a small pilot study, we had 4 Ph.D. students and 1 M.S. student manually generate tests for the example. All students kept the derivation history so that they could check their work, compare results with their peers, and more easily identify discrepancies. Hence, it appears reasonable to assume that derivation history is available.
**Change 2:** There are 11 tests which use obsolete path \( t_{42} \) (edge \((n_{12}, n_9)\) is missing). To cover the new edge \((n_{12}, n_{14})\), an additional path is needed, so there are two new paths: \( t_{42}' = n_{15}n_{17}n_{14} \) and \( t_{43}' = n_{15}n_{17}n_{12}n_{14} \).
In a small pilot study, we had 4 Ph.D. students and 1 M.S. student manually generate tests for the example. All students kept the derivation history so that they could check their work, compare results with their peers, and more easily identify discrepancies. Hence, it appears reasonable to assume that derivation history is available.
**Change 3:** This change requires modifications through several substitution levels. This change makes \( t_{42} \) obsolete. Because a large portion of the tests is derived from \( t_0 = n_1c_2n_2 \), 16 of the 20 tests are obsolete, suggesting that a great deal more reaggregation is necessary. Because \( c_2 \) occurs at the highest level of aggregation, this really means that we have to reaggregate from \( t_{01} \) on down. At the same time, only \( FSM_2 \) needs path changes, namely two new paths: \( t_{22} = n_6c_3n_7 \) and \( t_{23} = n_6c_4n_7 \).
Because the new paths only refer to one lower level cluster each, there are only 4 new abstract tests to substitute for the obsolete ones, two for \( c_3 \) and 2 for \( c_4 \). Value generation has to be done almost from the beginning. There are no retestable tests, so the regression test suite consists of 32 tests.
Changes 2 and 3 affect more paths at more levels in the hierarchy than change 1, because cluster nodes associated with the changes occur in more of the \( FSMs \) or at higher levels.
So far, we have assumed single changes. What if all three changes occur at the same time? There are 17 obsolete test cases and 3 retestable ones. In this case, reaggregation needs to start with \( t_{01} \) and \( t_{02} \) at the top level, and value generation also must start almost from the beginning. However, we can still reuse paths through \( AFSM \) and \( FSM_1 \) as well as the ones in the modified \( FSMs \) that have not become obsolete.
Depending on the character of the changes, these can be found in retestable or reusable tests. In total, the modified \( FSMs \) require 30 test cases: six for \( t_{01} \) and 24 for \( t_{02} \).
In a small pilot study as part of an advanced graduate class in software testing, five graduate students derived test paths, and performed selective regression test generation using partial reregeneration for the example. The task was done manually with a pen and paper. The same coverage and aggregation criteria were used as in the previous example. The original test path generation time ranged between 1.5 and 3 hours. Change 1 took 10-20 minutes; change 2 took 20-30 minutes; and change 3 took 20-42 minutes.
This data roughly reflects the progressively higher impact of the changes on the paths. Even though the third change was more involved and required much more regeneration, the time spent was still much lower than the original abstract test generation times. We speculated that learning effects might account for some of this discrepancy; the students had become familiar with the model and its tests. We plan on investigating this phenomenon further.
**Cost Tradeoffs Between Brute Force and Selective Approaches**
Now, we analyze the cost tradeoffs between the brute force and selective approaches for each change in the example.

TABLE III
TEST PATHS FOR AFSM
<table>
<thead>
<tr>
<th>Test</th>
<th>Test Paths</th>
<th>Derivation Rules</th>
<th>Length</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>n₁n₂n₃n₄</td>
<td>c₂ → t₂₁</td>
<td>4</td>
</tr>
<tr>
<td>2</td>
<td>n₁n₂n₄n₃n₄</td>
<td>c₂ → t₂₂, t₂₃ → n₆c₄c₃n₇n₄, c₄ → t₄₁, and c₅ → t₅₁</td>
<td>11 = 4 + 4 + 3</td>
</tr>
<tr>
<td>3</td>
<td>n₁n₂n₄n₃n₄</td>
<td>c₂ → t₂₂, t₂₃ → n₆c₄c₃n₇n₄, c₄ → t₄₂, and c₅ → t₅₁</td>
<td>12 = 4 + 5 + 3</td>
</tr>
<tr>
<td>4</td>
<td>n₁n₂n₄n₃n₄</td>
<td>c₂ → t₂₂, t₂₃ → n₆c₄c₃n₇n₄, c₄ → t₄₁, and c₅ → t₅₂</td>
<td>16 = 4 + 4 + 8</td>
</tr>
<tr>
<td>5</td>
<td>n₁n₂n₄n₃n₄</td>
<td>c₂ → t₂₂, t₂₃ → n₆c₄c₃n₇n₄, c₄ → t₄₂, and c₅ → t₅₂</td>
<td>17 = 4 + 5 + 8</td>
</tr>
</tbody>
</table>
V. COST-BENEFIT TRADEOFFS IN PRACTICE
As we observed from the previous section, the amount of changes and their impact on other model parts can affect the choice of regression testing techniques. In this paper, we only considered safe regression testing techniques, but depending on the organization’s situations, they might not be the best option to use. For instance, some organizations might prefer a technique that does not guarantee to retest all changed components but tests the important components to release the product earlier. Thus, to consider the practicality of regression testing, we need to project the comparative costs between techniques in light of their business value to organizations by considering several factors, such as the type of applications that organizations build, the product’s market share, revenue associated with the product, the product’s release time sensitivity, and revision/testing frequency for the product.
These factors are interrelated to each other, and a certain factor can greatly impact others. For instance, if a software game company is targeting Christmas shoppers who would purchase the new game product, then the product’s release time greatly affects revenue and the product’s market share. Thus, delaying the product release would be a great loss for the company. In particular, the type of applications and the organization’s goal would be the major influential factors for others. In general, we can consider two types of regression testing approaches: safe regression testing and economy-sensitive regression testing.
Safe Regression Testing
If the organization’s goal is to build dependable software, then we need to consider safe regression test selection techniques. (e.g., Organizations that build web applications handle financial issues or deal with sensitive data.) In this case, the choice is very obvious. The organizations can choose a brute force approach or a safe, selective testing approach, and calculating the tradeoffs between techniques is straightforward. We just need to compare costs for the two techniques as shown in earlier sections.
However, this simple cost difference should be projected by considering the economic impact of the savings. For example, if the relationship between the product release time and revenue gains is insignificant or ignorable, then a rough threshold estimation would be acceptable when the organization chooses a regression testing technique. If the product release time affects revenue gains greatly, then small cost savings from one technique over the other could bring significant revenue gains. In that case, a more accurate threshold should be estimated.
Economy-Sensitive Regression Testing
If the organization’s goal is to make a profit, then testing the product thoroughly and, as a consequence, delaying the product release might not be a good strategy. Actually, the majority of profit-pursuing organizations have time to market pressures due to the constraint budgetary problem and a competitive software market. To resolve this situation, companies might release the buggy product early and patch it later. Many companies are using this strategy to achieve an early market share because delay is costly [13].
As we can speculate, this approach has tradeoffs. It leads to a fast delivery, thus it is competitive in the market. However, some faults might escape, thus the product could have low reliability. The field failure can be very expensive depending on types of faults. Further, a bad reputation for quality could lead to losing customers in the long term.
Thus, when we apply non-safe regression testing techniques that are more sensible for the majority of software companies,
we need to consider their cost-benefit tradeoffs so that organizations can choose techniques that are more beneficial for their circumstances. To test a new software version, we can consider the following tasks:
1) Create and run new tests that are associated with new or modified components.
2) Select existing tests that are associated with more important components or risky (critical) components.
3) Prioritize existing tests based on certain criteria (e.g., code coverage, risk factor, and criticality), and run important tests early until time runs out.
To offer the best strategy for the company, these three tasks can be used together, considering the cost of fixing defects (detected after release) and potential revenue gains from early product release.
Consider the example we illustrated in Section IV. Suppose that the component for $FSM_4'$ has been developed by a third party; the others are in-house components; and all three FSMs are modified as shown in Figure 2 due to feature updates. Assume that the modified FSMs are ready to retest, but the testing team does not have enough time to retest all of them because the product release deadline has already been delayed and because the company wants to ship the product as soon as possible so that it can minimize the profit loss. Because safe regression testing is not a good choice for this situation, the testing team could decide to run more important or risky test cases before releasing the product, and then run the rest of the tests later. Assuming that third party components are riskier and take more time when defects occur due to the longer communication required with an outside party, the testing team can run tests that use paths through $FSM_4'$ first.
VI. RELATED WORK
The simplest regression testing technique is to rerun all existing test cases, but it can be very expensive in practice [14]. Thus, various regression testing techniques have been proposed and empirically evaluated to improve the cost-effectiveness of regression testing, such as regression test selection techniques (e.g., [4], [12]), test suite minimization (or reduction) techniques (e.g., [5], [15]), and test case prioritization technique (e.g., [3], [16]). The majority of this research focused on regression testing for desktop applications such as C or Java, but more recent research targeted web applications because the use of web applications has grown rapidly over the past decade (e.g., [17], [10]). Two recent surveys [18], [19] provide an overview of the regression testing techniques and approaches and the current state of research on them.
Most early work on regression testing utilized simple measures, such as the number of test cases reduced, time savings from regression test selection, or the rate of fault detection to evaluate the effectiveness of regression testing techniques. With such simple metrics, however, we cannot properly assess the costs and benefits of regression testing techniques in practical settings.
To address this problem, a few models of regression testing have been proposed. Leung and White [7] present a cost model that considers some factors (analysis cost, testing time, and technique execution time) that affect the cost for regression testing a software system. While they provide the cost relationship between the retest-all and selective strategies, no empirical work has been presented. Malishevsky et al. [20] extend this work with cost models for regression test selection and test case prioritization that incorporate benefits related to fault omission and the rate of fault detection, and the authors assess the cost-benefits of regression testing techniques through empirical results. Do and Rothermel [21], [6] present an economic model (EVOMO) and evaluate the costs and benefits of regression testing processes that capture both cost and benefit factors relevant to those processes and facilitate their evaluation across system lifecycles. However, these models allow evaluation only after applying the techniques to the applications. Unlike these, in this work, we propose a tradeoff framework that can choose the proper techniques before applying the techniques.
VII. CONCLUSIONS AND FUTURE WORK
In this paper, we proposed a cost-benefit tradeoff framework for FSMWeb models that helps choose between selective and brute force regression testing. With an example, we illustrated how the tradeoff framework can be applied when analyzing the cost-benefit tradeoffs of the brute force and selective regression testing techniques when models change, and we established the relationship among effort parameters for cost estimation. We also discussed the practical issues to consider when choosing regression testing techniques that can support the organization’s business goals. In this work, we applied our framework to the FSMWeb model. We plan to adapt the framework to other graph-based behavioral models, such as UML behavioral models.
The proposed tradeoff framework provides a quick and simple way to choose a cost-effective regression testing technique by simplifying the assumptions for cost parameters, but these parameters should be adjusted through calibration and empirical evaluation efforts. Toward this direction, we plan to conduct case studies using industrial web applications through collaboration with graduate students at the University of Denver who work for software companies and to calibrate cost parameters based on empirical results. Further, we plan to evaluate our framework considering its efficiency, effectiveness, and user experiences through such case studies.
ACKNOWLEDGMENT
This work was supported, in part, by NSF IUCRC grant #0934413 to the University of Denver and NSF CAREER Award CCF-1149389 to North Dakota State University.
REFERENCES
|
{"Source-Url": "http://www.cse.unt.edu/~hdo/pdf_files/hase14.pdf", "len_cl100k_base": 10592, "olmocr-version": "0.1.53", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 38590, "total-output-tokens": 12573, "length": "2e13", "weborganizer": {"__label__adult": 0.00031447410583496094, "__label__art_design": 0.00034618377685546875, "__label__crime_law": 0.0002987384796142578, "__label__education_jobs": 0.0018482208251953125, "__label__entertainment": 6.538629531860352e-05, "__label__fashion_beauty": 0.00015497207641601562, "__label__finance_business": 0.0005006790161132812, "__label__food_dining": 0.0002734661102294922, "__label__games": 0.0005855560302734375, "__label__hardware": 0.0006031990051269531, "__label__health": 0.0004436969757080078, "__label__history": 0.00020778179168701172, "__label__home_hobbies": 8.237361907958984e-05, "__label__industrial": 0.00028061866760253906, "__label__literature": 0.0003287792205810547, "__label__politics": 0.00020766258239746096, "__label__religion": 0.00028777122497558594, "__label__science_tech": 0.018768310546875, "__label__social_life": 9.429454803466796e-05, "__label__software": 0.008880615234375, "__label__software_dev": 0.96484375, "__label__sports_fitness": 0.00021958351135253904, "__label__transportation": 0.00034737586975097656, "__label__travel": 0.00017201900482177734}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47312, 0.02775]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47312, 0.5466]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47312, 0.89936]], "google_gemma-3-12b-it_contains_pii": [[0, 4779, false], [4779, 9609, null], [9609, 14851, null], [14851, 20918, null], [20918, 26115, null], [26115, 33267, null], [33267, 37535, null], [37535, 43668, null], [43668, 47312, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4779, true], [4779, 9609, null], [9609, 14851, null], [14851, 20918, null], [20918, 26115, null], [26115, 33267, null], [33267, 37535, null], [37535, 43668, null], [43668, 47312, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47312, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47312, null]], "pdf_page_numbers": [[0, 4779, 1], [4779, 9609, 2], [9609, 14851, 3], [14851, 20918, 4], [20918, 26115, 5], [26115, 33267, 6], [33267, 37535, 7], [37535, 43668, 8], [43668, 47312, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47312, 0.06087]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
05d6c3d7755dbf9812c00c198d5897327ae3382c
|
[REMOVED]
|
{"len_cl100k_base": 11948, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 35379, "total-output-tokens": 14386, "length": "2e13", "weborganizer": {"__label__adult": 0.0003597736358642578, "__label__art_design": 0.0005035400390625, "__label__crime_law": 0.0004756450653076172, "__label__education_jobs": 0.0023097991943359375, "__label__entertainment": 9.202957153320312e-05, "__label__fashion_beauty": 0.00020039081573486328, "__label__finance_business": 0.0004825592041015625, "__label__food_dining": 0.0004715919494628906, "__label__games": 0.0007047653198242188, "__label__hardware": 0.0007982254028320312, "__label__health": 0.0008273124694824219, "__label__history": 0.0004115104675292969, "__label__home_hobbies": 0.0001538991928100586, "__label__industrial": 0.00066375732421875, "__label__literature": 0.0006465911865234375, "__label__politics": 0.00032711029052734375, "__label__religion": 0.0005974769592285156, "__label__science_tech": 0.13134765625, "__label__social_life": 0.0001423358917236328, "__label__software": 0.01422882080078125, "__label__software_dev": 0.84326171875, "__label__sports_fitness": 0.0002574920654296875, "__label__transportation": 0.0005803108215332031, "__label__travel": 0.0002033710479736328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45065, 0.02897]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45065, 0.63489]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45065, 0.81436]], "google_gemma-3-12b-it_contains_pii": [[0, 2036, false], [2036, 5891, null], [5891, 8770, null], [8770, 11558, null], [11558, 13110, null], [13110, 15689, null], [15689, 18467, null], [18467, 21037, null], [21037, 23832, null], [23832, 26656, null], [26656, 28797, null], [28797, 31956, null], [31956, 35126, null], [35126, 37301, null], [37301, 40773, null], [40773, 43364, null], [43364, 45065, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2036, true], [2036, 5891, null], [5891, 8770, null], [8770, 11558, null], [11558, 13110, null], [13110, 15689, null], [15689, 18467, null], [18467, 21037, null], [21037, 23832, null], [23832, 26656, null], [26656, 28797, null], [28797, 31956, null], [31956, 35126, null], [35126, 37301, null], [37301, 40773, null], [40773, 43364, null], [43364, 45065, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45065, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45065, null]], "pdf_page_numbers": [[0, 2036, 1], [2036, 5891, 2], [5891, 8770, 3], [8770, 11558, 4], [11558, 13110, 5], [13110, 15689, 6], [15689, 18467, 7], [18467, 21037, 8], [21037, 23832, 9], [23832, 26656, 10], [26656, 28797, 11], [28797, 31956, 12], [31956, 35126, 13], [35126, 37301, 14], [37301, 40773, 15], [40773, 43364, 16], [43364, 45065, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45065, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
3a165fc6ae99db91dad98c2278704da59584ee00
|
Abstract Multicore processors represent the de-facto standard architecture for a wide variety of devices, from high performance computers to mobile devices. However, developing concurrent programs to harness the capabilities of multicore architectures using traditional lock-based synchronisation is known to be a complex and error prone task, as the fine-grained locking approach is prone to deadlocks, livelocks and it is difficult to debug, while coarse-grained locking does not provide performance gains. Transactional Memory (TM) has emerged as a powerful paradigm that promises to simplify the life of programmers while still achieving performance similar to fine grained locking, programmers only need to specify which parts of the code have to appear as executed atomically, and not how atomicity should be achieved. This document first overviews the state of the art of TM, analysing some of the main TM implementations based on software (STM), hardware (HTM), or on combination thereof (Hybrid TM). Next, It overviews the state of the art benchmarks that has been created to evaluate Transactional Memory implementations and stress the advantages and disadvantages over the traditional locking mechanisms. In the light of this critical analysis of the state of the art, the document proposes a novel Hybrid TM algorithm that aims to minimise synchronisation overheads between HTM and STM by relying on a novel dynamic memory partitioning scheme.
Keywords: Transactional Memory, Concurrent Programming, Data Partitioning, Efficiency
1 Introduction
Multicore processors have become the standard architecture in today’s computing systems, ranging from high-end servers, to personal computers, as well as smartphones and embedded systems, all have the multicore technology and the trend is to increase the number of cores towards manycore architectures. Unfortunately, the development of parallel applications that can fully exploit the advantages of the multicore technology is far from being a trivial task.
Indeed, when using traditional lock-based synchronisation mechanisms, developers are faced with a major dilemma. They can either opt for using coarse-grained locks, which simplifies significantly reasoning on the correctness of concurrent applications, but can severely hinder parallelism and hamper performance. Or they can opt for a second alternative which is to use fine-grained locking. This approach allows for extracting the most parallelism possible, avoiding the inefficiency of coarse-grained locking, but it is harder to devise and more prone to deadlocks and livelocks, which are notoriously hard to debug [33]. In fact, fine grained locking is considered difficult to use for the average programmer [33], who may not be necessarily well trained for the development of concurrent applications.
Transactional Memory (TM) [25] precisely answers this urge by specifying a new programming paradigm that alleviates the complexity of classical locking mechanisms while ensuring performance similar or even better than complex fine-grained locking schemes. TM borrows the concept of transactions from databases and applies it to parallel programming; with TM, programmers devise code into blocks that will be ensured by the TM system to run atomically. The underlying system is responsible for either committing the transactions, and making it’s modifications globally visible, or to aborting the transactions and ensuring that no modifications are observed out of the context of the transaction. This approach leads to drastically simplifying the development of parallel applications and abate their time to market and costs.
Transactional Memory was initially proposed twenty years ago as an extension to multi-processors’ cache coherence protocols [25]. Due to the difficulty of rapid prototyping in hardware environments, researchers resorted to Software Transactional Memory to advance the state of the art [12,19,20,22]. Simultaneously, hardware-based implementations have also been proposed, whose designs were validated using simulators.
Hardware Transactional Memory (HTM) is currently supported by the mainstream Intel Haswell and the IBM Power8 processors. These implementations are best-effort, which means that they always ensure correctness, but do not provide any progress guarantee. This means that transactions executing in hardware may never commit (even in absence of concurrency) due to inherent limitations of hardware, such as transaction exceeding capacity of hardware or running prohibited instructions. This raises the need for a software fallback path to ensure forward progress [18].
This fallback path can be either as simple as a global lock or as complex as a software transactional memory, which is designated by Hybrid Transactional Memory (HyTM) [8,11,13,29,36]. The goal of HyTM is to fully exploit best-effort HTM as much as possible, and in the case of abort, fall back to the more costly Software Transactional Memory (STM), which provides progress guarantee.
Despite the number of papers published in this area in recent years, HyTM still suffer from large overheads [18]. These overheads are noticed on HyTMs based on early STM implementations [36], which requires dealing with per-location metadata and consequently makes the implementation prone to capacity aborts
due to the handling of metadata by HTM [11]; but also in HyTMs that use a software fallback without per location metadata, as these HyTMs suffer from a scalability bottleneck as every transaction must read a sequence lock. Further, they can induce spurious aborts of HTM transactions if any concurrent, non-conflicting HTM commits [18]. Benchmarks’ tests indicate that the performance of state of the art HyTM can not surpass HTM performance for workloads characterised by short transactions with small read and write-set, and that it can not surpass the scalability of STM for workloads characterised by long transactions with large read and write-set. The results show that HyTM has costs incurred by synchronising both the execution of HTM and STM, as the memory locations accessed by one TM has to be validated with the read and write-set of both TMs. Results also show that the performance of HyTM is highly dependent on the workload.
The goal of this work is to provide a new class of HyTM without the overheads incurred by the synchronisation of HTM and STM. The solution proposed in this document is to dynamically partition the memory into two distinct partitions where both STM and an HTM can execute transactions disjointly, thus avoiding overheads of the synchronisation between both systems. The main challenge is how to ensure safety (i.e. accesses by HTM and STM are actually constrained to their current partitions) without imposing costly instrumentation overheads on HTM and also STM.
The rest of this document is structured as follows: Section 2 overviews the state of the art in the TM field. Section 3 describes the architecture of the proposed solution. Section 4 focuses on how the proposed solution will be evaluated and which metrics are going to be used and Section 5 contains the scheduling for the future work.
2 Related Work
This section overviews the state of the art of Transactional Memory, it first begins with STM and presents three implementations that address different design approaches. Then, it presents the state of the art of HTM and shows the virtues and limitations of each HTM available. Next, it presents the state of the art of HyTM and it presents six different approaches to synchronise both HTM and STM. Finally, is presented an overview of state of the art benchmarks used to evaluate TM.
2.1 Software Transactional Memory
Software Transactional Memory (STM) is a category of systems that implement the Transactional Memory abstraction through a purely software-based runtime library.
During the last decade, STM was object of a thorough research mainly because it is a solution that is not bound to a specific architecture, nor it is restricted by the underlying hardware, making STM a widely portable solution. In STM,
transactional reads and writes are tracked by a software runtime, which has the responsibility of maintaining the read and write set of transactions. Besides maintaining the read and write sets, most STMs keep additional metadata about transactions, such as locking, ownership records and versioning.
Existing literature in the area of STM can be coarsely classified according to the following design choice choices: word-based vs object-based, lock-based vs lock-free, write-through vs write-back, eager vs lazy conflict detection. word-based STMs access the memory directly at the granularity of machine words or larger chunks of memory, yet object-based STMs access the memory at object granularity and it requires the TM to be aware of the object associated in every access. In terms of locking mechanisms, lock-based STMs uses locks to control the concurrency between transactions accessing the same data while lock-free STMs do not use any lock to protect memory from concurrent accesses. STMs can be write-through, writing their updates directly to memory and storing the previous ones on a undo log, or write-back which means that changes are only written to memory at commit-time. Finally, the conflict detection can be eager, which means that conflicts are detected at the moment of occurrence, or it can be lazy if the detection is performed at commit-time.
The best design can vary according to a number of factors like the underlying architecture, the number of cores per CPU and the size of caches. More important to note is that the efficiency that will result from these choices is highly dependent from the type of workload generated by the application.
In comparison with HTM, STM systems incur heavy instrumentation on the code, issuing modification on the atomic code blocks in order to account for transactional operations and other operations performed by the underlying system as log keeping and conflict detection. Despite of the drawbacks, state of the art STM normally provides stronger progress guarantees than HTM: being fully implemented in software, STM does not suffer from the restrictions that affect HTM and can support the execution of arbitrarily long transactions.
TinySTM TinySTM [20] is a STM implementation presented by Felber et al. in 2008.
Authors state that the characteristics of the workload of an STM implementation plays a major role in selecting the right choice and configuration parameters. Some of the characteristics are the ratios to update read-only transactions, the size of read and write-sets and contention on shared memory.
TinySTM is a word-based STM implementation, meaning that it allows for directly mapping of transactional accesses to the underlying memory subsystem.
This STM uses an encounter-time locking mechanism, as authors state that it increases the transactions throughput because transactions do not perform useless work. This mechanism also allows the efficient handling of reads-after-write conflicts without requiring expensive or complex mechanisms, a valuable feature especially when write-sets have non-negligible size.
Along with encounter time locking, two other strategies can be used in TinySTM to access memory: write-through and write-back access. In write-
through access, transactions immediately write to memory and undo updates if aborted. In write-back access, transactions do not update until the commit time.
As most word-based STM designs, TinySTM relies upon a shared array of locks to manage concurrent accesses to memory. Each lock covers a portion of the address space. Addresses are per-stripe mapped to the lock based on a hash function. Each lock represents a size of address in memory, as the least significant bit shows whether lock is owned or not. If the lock is owned, the remaining bits of address store the owner transaction, if not, a version number based on the timestamp of the last owner transaction is stored in the remaining bits.
The locks are used to protect memory, when a transaction issues a read it first checks if the lock protecting the read item is currently being held by other transaction. Then, it reads the value of the item, and finally the lock again. If the lock is not held by other transaction or the value of the lock did not change between both reads, then the value read is consistent.
When a transaction writes to a memory location, it reads the lock entry from selected memory addresses. If it finds that the lock bit is set then it verifies either the current transaction is the owner or not. If current transaction is the owner, then it simply writes the new value to memory location. If it is not owner of the current transaction then the current transaction can wait for some time to get resources free or aborts immediately.
TinySTM guarantees that there is a consistent read-set upon each read for read-only transactions, therefore read-only transactions do not need to validate their read-sets upon commit. Update transaction have to validate their read-set before updating any memory location. The downside of this approach is that the validation of large read-set may be costly, to avoid this overhead the number of locks can be reduced. On the other hand reducing the number of locks can increase abort rate as it increases false sharing.
In order to solve this problem, authors proposed hierarchical locking. In addition to the shared array of locks, it is maintained a smaller array of counters which goal is to hold the number of commits done to locations in that region. An hash function is used to map memory addresses to counters, this function is consistent with the one used to map addresses to lock arrays, i.e. memory locations that are mapped to the same lock are also mapped to the same counter, which implies that a counter covers multiple locks and the associated memory addresses. This scheme allows transactions to determine whether locks have been acquired or not, however it has an overhead associated with it but authors state that it is amortised when transactions have large read sets or when there are few writes from competing transactions.
TinySTM periodically adapts the tuning parameters at runtime and measures the throughput over a period of approximately one second. The system registers the most recent throughput for each tuning configuration. Each tuning configuration is a triple consisting of the number of locks, the number of shifts, and the size of the hierarchical array. The tuning strategy is a hill climbing algorithm with a memory and forbidden areas in order to achieve the best configuration to the given workload.
STM with Data Partitioning Scheme In order to mitigate the concern of different parts of the data having different access patterns, thus requiring specific design optimisations, Riegel et. al [35] proposed the use of a data partitioning scheme integrated with TinySTM [20]. This approach enables STM to divide data structures in partitions and to compose different specialised optimisations for each partition accordingly to the workload or even to use a different STM backend in that partition, hence improving the transactional throughput of each partition. To identify the partitions of an application, it is constructed a Data Structure (DS) graph at compile-time for every function encountered in the program. The DS graph is determined by analysing to which node (partition) does the pointers in a program are permitted to point to, and whenever two pointers stored in the same field point to disjoint nodes, those nodes are unified. Each partition has a type that indicate the concurrency control. The partitions types vary from read-only partitions to partitions with multiple locks, each partition type is determined at runtime accordingly to the number of aborts. The inherent problem of this approach is the usage of pointers in certain languages like C. Pointers allow to access memory directly, thus another partition, without the knowledge of the STM.
SwissTM SwissTM [19] is a STM implementation presented by Dragojevic et al. in 2009. Authors state that state of the art STMs only have good performance for workloads with small scale transactions, but in practice do not work well for large scale applications like business software and video games.
This STM uses four-word lock granularity to protect shared memory, as authors state that this approach outperforms both word-level and cache line-level locking for all benchmarks considered.
It uses a mixed invalidation conflict detection scheme which eagerly detects write/write conflicts. Thus preventing long transactions, that are doomed to abort, to continue their execution and possibly cause more conflicts with other running transactions. On the other hand, read/write conflicts, commonly caused by short transaction with longer ones, are lazily detected. By using invisible reads and allowing transactions to read objects acquired for writing, SwissTM detects read/write conflicts late, thus increasing inter-transaction parallelism. A time-based scheme is used to reduce the cost of transaction validation with invisible reads.
For conflict detection it uses a two-phase contention manager scheme that incurs no overhead on read-only and short read-write transactions. Upon a write, every transaction increments a local counter. If the value of this counter is below 10, then it is considered a short transaction and in case of conflict it will use a timid contention management scheme, aborting on the first encountered conflict. Transactions that are more complex increment the global counter above 10 are then switched dynamically to the Greedy mechanism that involves more overhead but favours these transactions, thus preventing starvation. This means that more complex transactions have higher priority than simpler transactions.
Additionally, transactions that abort due to write/write conflicts back-off for a period proportional to the number of their successive aborts, hence reducing the probability of aborting repeatedly because of the same conflict.
Authors state that SwissTM outperforms all state of the art STM in mixed workloads characterised by non uniform, dynamic data structures and various transaction sizes while also delivering good performance in smaller-scale scenarios.
**NOrec** NOrec is a STM library presented in 2010, by Luke Dalessandro, Michael Spear and Michael Scott [12].
Authors advocate a minimal approach on STM handling of metadata. NOrec does not need fine grained, shared metadata, only requires a single global sequence lock (seqlock) for concurrency control. Transactions buffer writes and log read address/value pairs in thread local structures.
Upon start, transactions poll back seqlock and check if there is any transactions in write-back phase; if there is, transactions waits until there is no transaction in the write-back phase. Committing writers increments the seqlock in order to signal that they have written new values to memory.
When a read is issued, active transactions poll the global seqlock and compare it with the one held locally by the transaction. A new value is evidence of possible inconsistency and triggers validation, which is carried out in a value-based style by comparing the pair address/value in log to the actual values in main memory.
In this protocol, only a single writer can commit and perform writeback at a time. This sequential bottleneck is minimised by validation prior to acquiring the seqlock for commit.
By successfully incrementing the seqlock, a writer transitions to a committed state in which it immediately performs it’s writeback and then releases the lock. Read-only transactions can automatically commit because their reads are proven to be consistent because of the validation mechanism.
NOrec scales well when it’s single-writer commit serialisation does not represent the overall application bottleneck, i.e., writeback does not dominate the runtime, and has been shown to have low latency, although its read set entries are twice as large as the corresponding orec-based implementations, as NOrec stores both the address of the read location and the value that was seen.
NOrec guarantees consistency among transactional and non-transactional accesses to shared data, a characteristic named privatization [30,38], which is required for compatibility with the C++ draft TM standard [4]. Further, it provides support for closed nesting, where inner transactions can abort and restart separately from their parents, which is expected to improve performance in certain applications.
Authors conclude that NOrec have low overhead and high scalability, which is ideal for use in legacy system as well as a fallback mechanism in HyTM due to it’s robust performance.
2.2 Hardware Transactional Memory
Although TM was originally proposed as an micro-architectural feature [25], the absence of hardware support switched a large body of TM research into STM [12,19,20,22]. Unlike Hardware solutions, STM require instrumentation of reads and writes in order to track the read and write-set of active transactions and detect conflicts between them. This instrumentation can introduce, in certain scenarios, large overheads that are non-negligible and can hinder performance with respect to conventional fine-grained locking.
HTM is thus desirable, as it relies on modified cache coherence protocol in order to achieve atomicity and isolation. The main advantage of HTM is that it requires no instrumentation of reads and writes, which degrades the performance of STM solutions, as the read and write-set are stored in L1 cache and conflicts are detected by the cache coherence protocol. A major drawback is that current HTM does not guarantee that a transaction will succeed, even without concurrency, due to its limited nature, which is limited by the fact that read and write-set fits in L1 cache.
The maturing of TM led to a change in the industry of processor manufacturing, as manufacturers revealed the first processors that successfully implemented HTM: Azul [10] and Rock [17] processors. Unfortunately, these systems were not usable, as Azul programming interface was not disclosed, thus making HTM hidden for the programmers and Rock processor was cancelled before reaching the market. IBM Blue Gene/Q was the first processor on the market that provide an HTM implementation [39], followed by zEnterprise EC12 [2], IBM Power8 [3] and Intel Haswell [40]. This represented a significant milestone for TM, as with Intel Haswell processor, TM became available on commodity hardware from high-end servers to mainstream laptops.
Haswell uses the L1 cache for conflict detection and maintaining versions and transactional metadata. However, the details about the conflict detection and transaction capacities have not been disclosed by Intel. The Intel Transactional Synchronization Extensions (TSX), i.e., the code-name for the HTM API in Haswell CPUs, comprises two possible interfaces, Hardware Lock Elision (HLE) and Restricted Transactional Memory (RTM). The former allows to elide locks [6] and execute code speculatively in a backwards-compatible manner. RTM leverages on the same hardware as HLE, but exposes a transaction interface in which the programmers only need to specify which blocks are atomic, leaving to the underlying system the responsibility to ensure the correct execution of transactions.
A very important detail is that the begin instruction requires to specify a software handler to deal with transaction aborts, and thus provide progress guarantee. The software fallback must co-operate with HTM in order to ensure correctness and the mechanism used has a great impact on the performance of TSX. The simplest approach and the one suggested by Intel’s optimisation manual is the use of a single global lock as a fallback mechanism. When a hardware transaction aborts, it has the alternative to check and acquire the global lock if it is free. To ensure correctness, every hardware transaction must subscribe to
the global lock and ensure it is free, as the underlying transactional semantics will guarantee that a transaction only commits when there is no ongoing fallback execution.
IBM Blue Gene/Q uses the L2 cache for conflict detection and updates buffering. It assigns a unique speculation ID to each transaction and uses the L2 cache to store the speculation ID upon a transactional access. IBM Blue Gene/Q has two transactional execution modes: a short-running mode and a long-running mode. In the short-running mode, it uses only the L2 cache to buffer transactional data, and in the long-running mode, it uses the L1 cache to buffer some of the transactional data though it invalidates all of the L1 cache lines at the start of each transaction.
IBM zEC12 uses the L1 cache for both conflict detection and loads buffering, along with a special LRU-extension, which function is to record the evicted cache lines. The transactional stores are buffered in an 8-KB gathering store cache, which is private for each processor and is located between the L1 cache and the L2/L3 caches. IBM zEC12 also provides constrained transactions, which are transactions that are guaranteed to commit.
IBM Power8 uses content addressable memory (CAM) linked with the L2 cache for conflict detection [32]. The L2 TMCAM records the cache-line addresses that are accessed in the transactions with bits to represent read and write. Although the transactional stored data is buffered in the L2 cache, the transaction capacity is bounded by the size of the L2 TMCAM. Power8 support rollback-only transactions, which are transactions that support normal transactional semantics, i.e. store buffering, but not conflict detection. Also, Power8 support the use of suspend/resume operations, which allows to escape from a transactional context and access a variable without risking to incur data conflicts.
Nataike et. al in [32] compared all state of the art processors that provide HTM, by using a modified version of the STAMP’s benchmark suite [31] better suited to accommodate the limited capacity of HTM. The experimental results showed that there is no single HTM system that is more scalable than the others in all of the benchmarks. Each HTM system has it’s own implementations issues that limit the scalability in certain workloads.
Results shows that Intel Core has load and store capacity of 4MB and 22KB respectively. This processor has extra transaction aborts due to hardware prefetching, as it could raise a conflict that would not exist if the hardware did not prefetch other cache lines in advance. L1 and L2 size are respectively 32KB and 256 KB.
IBM Power8 has more capacity-overflow aborts than the other processors because of it’s small transaction capacity, i.e., 8KB for loads and stores, respectively. L1 cache is one of the biggest in the study, with 64 KB is only surpassed by zEC12’s 96KB. L2 cache size is 512 KB. Results show that the suspend and resume instructions are beneficial for avoiding data conflicts on a shared variable to implement ordered transactions.
Diegues et. al [18] and Goel et. al [21] experimentally evaluated Intel TSX implementation on a variety of workloads produced by different benchmarks,
more specifically the workloads produced by STAMP benchmark suite [31], microbenchmark Eigenbench [27] and Memcached [26], as well as workloads produced by concurrent data structures. Authors state that TSX has outstanding performance for workloads characterised by small transactions, such as the ones produced by concurrent data structures and Memcached [26], but only with two of the STAMP benchmarks, namely Kmeans and SSCA.
Goel. et al [21] also compared the performance and energy consumption of TSX with TinySTM [20]. The results shows that TSX performance relies heavily on the access patterns to LI cache, as every memory access performed inside a transaction is tracked, implying that long running transactions can lead to frequent capacity exceptions and spurious aborts. When transaction’s intensity is medium, TSX is only the best choice for a limited degree of parallelism, and it is generally better on the energy side than on the performance side. However as the contention and duration of the workload increases, TinySTM begins to outperform TSX, as TSX deals worse with contention than TinySTM due to the detection of conflicts at granularity of cache cache line (bytes). TSX scales well up to four threads, however at eight threads, the LI cache is shared between two threads running on the same core. This cache sharing degrades performance for the larger working set more than for the smaller working set because hyper-threading effectively halves the write-set capacity of TSX. In contrast, TinySTM scales well up to eight threads. In terms of energy efficiency, TSX proves to be more energy-efficient than either TinySTM or the sequential runs.
Lazy Subscription To ensure that a critical section executed by a hardware transaction does not observe partial effects of a critical section executed by another thread that acquires the lock, the transaction subscribes the lock, by reading it and confirming if it is available. Subscribing to the lock makes hardware transactions vulnerable to abort if another thread acquires the lock. Typically, transactions subscribe to the lock at the beginning of the critical section and are thus vulnerable to such abort during the entire execution of the critical section. Some papers [11,29] proposed the, so called, lazy subscription optimisation, which delays lock subscription, in order to reduce the duration of this vulnerability.
Dice et. al in this study [15], reported a number of issues associated with lazy subscription. Lazy subscription can cause a transaction to deviate from the behaviour allowed by the original program, as it can result in the thread’s registers containing values that could not occur in an execution of the original program. This could result in an access by a transaction to memory that could never be accessed in the original program. If transaction commits, it results in a observably incorrect behaviour.
Compiler support suggested by other publications [9] for avoiding such issues in single global lock-based transaction system is not sufficient to avoid all the pitfalls associated with lazy subscription. Authors argue that the complexity required to address these issues via static analysis is unlikely to be worthwhile, as there are numerous pitfalls associated with lazy subscription, so manual confirmation of it’s safety in specific cases is likely to be error prone.
2.3 Hybrid Transactional Memory
The usage of a single global lock as a fallback mechanism in best-effort HTM motivated the researchers of TM to create Hybrid Transactional Memory (HyTM). The goal of HyTM is to exploit best-effort HTM whenever possible due to its cheaper capabilities, and fallback to the more costly STM when a transaction cannot complete in hardware. This approach promises to scale well and incur low latency, with the worst-case overhead and scalability comparable to the underlying STM.
To perform as a coherent whole, the HyTM system must be able to detect conflicts in hardware and software transactions simultaneously. This requirement is usually achieved by logging additional metadata while executing hardware transactions, so that the conflict detection system has access to both sides information. Certain STM algorithms required interaction with per-location metadata, and hybrid versions of these algorithms wasted limited hardware capacity on these metadata. The interaction of HTM with STM metadata could lead to capacity aborts, or could lead to false sharing of cache lines that hold the metadata, resulting in additional HTM aborts, and increased fallback to the STM path. Table 1 summarises the key characteristics of state of the art STMs and HTMs and compares with 5 state of the art HyTM implementations, Hybrid NOrec [11], Hybrid-LSA [36], Hybrid NOrec-2 [36], Invyswell [8] and RH NOrec [29].
Hybrid NOrec Dalessandro et al. [11] used NOrec STM [12] (see section 2.1) as a fallback STM of their Hybrid NOrec to avoid per-access overheads. In this algorithm, the commits of write transactions are executed sequentially, which means that only one transaction can commit at a time. A shared global clock, seqlock, is used to notify concurrent transactions about the updates to both hardware and software.
The original Hybrid NOrec has each transaction start to execute in hardware, and if repeatedly fails to commit, it falls back to executing the NOrec STM in software. To coordinate the execution of hardware and software transactions, three possible integrations between NOrec and HTM are proposed. In naive integration, the same global clock from NOrec, seqlock, is used by hardware transactions to subscribe to software transactions commits notifications. Upon the beginning of hardware transactions, the global clock is read and if is already owned by a software transaction, the hardware transaction spins until the owner completes the writeback and releases the lock. Upon commit, both software and hardware transactions update the global clock to signal their commits to other transactions, which triggers a validation phase in all concurrent transactions. Unfortunately, each hardware transaction conflicts with every software transaction due to the early subscription of the global clock, and aborts when any software transaction commits, regardless of actual data conflicts. Similarly, each hardware transaction conflicts with every other hardware transaction and aborts when any hardware transaction commits.
The second integration approach is 2-Locatin, in this approach a second shared location is added, counter, which decouples subscribing from signalling. Hardware transactions still subscribe to software transactions by reading the global clock but they use counter to signal their own commits to other hardware transactions. The drawback of having a second shared counter is that software transaction must have a snapshot for both the global counter and the second shared counter and must perform additional validation by reading the second shared counter.
The third approach is P-Location, which differs from 2-Location because hardware transactions no longer conflict with other running hardware transactions, as the counter is now distributed. With this approach, software transactions must poll \( n + 1 \) counters, increasing the overheads. To mitigate that, the number of counters is dynamically determined based on system conditions.
In order to optimise the algorithm, it was proposed the usage of mechanisms such as lazy subscription, sandboxing and communication filters. In lazy subscription, the read of the global clock is delayed prior to commit. This increase the concurrency between hardware and software transactions, however it sacrifices opacity [23], as nothing prevents a hardware transaction from reading inconsistent data during software writeback. Authors re-establishes opacity by adding a hardware read barrier that polls the seqlock nontransactionally and pauses if it is locked. Sandboxing is also proposed as an alternative to opacity, rather than instrumenting all loads for consistency, instructions are only instrumented when it’s effects may expose a transaction inconsistency. With the SW-Exists communication filter, a portion of shared memory is allocated in order to software transactions make their presence visible. When there is no software transaction running, hardware transactions have the possibility of eliding counter updates.
**Hybrid-LSA** Riegel et al. [36] presented two HyTM algorithms that can execute HTM and STM transactions concurrently and can thus provide good performance over a large spectrum of workloads. The algorithms exploit the concept of speculative (transactional) and non-speculative accesses, which are non-transactional accesses to memory, i.e., without adding the memory addresses to the read and write-set. This mechanism avoids conflicts with other running transactions, which decreases the transactions’ runtime overhead, abort rate and hardware capacity requirements compared with the versions that use speculative operations.
The paper assumes the availability of non-speculative operations, which are provided by AMD’s Advanced Synchronization Facility (ASF) specification [5], however they are not available in any current HTM implementation, except for IBM Power8, which supports them at a coarser granularity via the suspend/resume mechanism.
The first algorithm, Hybrid-LSA, extends the lazy snapshot algorithm first presented in [34] (overviewed in Section 2.1). LSA relies on the use of ownership records (orecs) protecting regions of memory and a global time base to check the consistency of transactions. Hybrid-LSA decides at runtime whether to use
Efficient Dynamic Data Partition Scheme in Hybrid Transactional Memory
hardware or software transactions, which both use orecs in order to mediate the access to regions of memory.
The eager variant of the Hybrid-LSA algorithm first performs a load of the ore, this operation starts monitoring the ore for changes and will lead to an abort if the ore is updated. If the ore is not locked, the transaction uses a nonspeculative load operation to read the target value, the usage of nonspeculative operation is an efficient way to get the value without adding the address to the read-set.
The write operation is similar to the load operation, but before writing speculatively to memory, the ore protecting the memory region is checked for concurrent load and stores (via the PREFETCHW operation, provided by the ASF assembly [5]).
Upon commit, hardware transactions nonspeculatively acquire and increment the clock. This operation sends a synchronisation message to software transactions, notifying them that a hardware transaction is on commit phase and thus, they might have to validate. Next, they speculatively write all updated orecs to memory and try to commit. If transactions successfully commit, then is guaranteed that no conflict with other transactions exists.
Hybrid NOrec-2 The second algorithm, Hybrid NOrec-2 [36], is an optimisation of the algorithm informally described in [12]. The main approach of Hybrid NOrec proposed by [12] is to use a word-sized global sequence lock gsl and an extra sequence lock esl. Software transactions acquire both locks and increment their versions upon commit, whereas hardware transactions monitor esl for changes and increment gsl only on commit. Thus, software transactions are notified about data being concurrently modified by gsl, and use esl to abort concurrent transactions and prevent them from executing during software transactions writeback. The two major problems with this approach is that it does not scale well in practice, as an update of esl will make every hardware transaction to abort, even if both transactions have disjoint working sets. Also, every update of gsl done by a hardware transaction cause every other hardware transactions to abort, even if it is made close to the end of a transaction, as suggested by [12].
Authors proposed optimisations to this algorithm using both speculative and nonspeculative operations, which results in a better performance than the original algorithm, with shorter read and write-sets, using simple optimisations.
The first straightforward optimisation consists in having hardware transactions to update gsl only if they will actually update shared state on commit, relieving other hardware transactions from aborting due to the update of gsl. Also, in order to provide more concurrency between hardware transactions that access disjoint data, the write of gsl can be replaced by a nonspeculative atomic fetch-and-increment operation, which allows the algorithm to scale better.
Additionally, hardware transactions do not monitor esl using speculative accesses anymore. The purpose of esl is to prevent hardware transactions from reading inconsistent state such as partial updates by software transactions. To detect such cases and thus still obtain a consistent snapshot, hardware
transactions first read the data speculatively and then wait until they observe with nonspeculative loads that \textit{esl} is not locked. If this succeeds and the transaction reaches the end without being aborted, it is guaranteed that it had a consistent snapshot valid.
**Invyswell** Calciu et al. [8] proposed Invyswell, a HyTM that combines Haswell RTM [18,21] transactions with software transactions from a heavily modified version of InvalSTM [22]. The main goal of this paper is to improve performance of small to medium-sized transactions that are executed in STM, whose instrumentation cost causes them to perform poorly.
InvalSTM [22] is based on commit-time invalidation. The read and write-sets of a transaction are stored in transaction specific Bloom Filters and upon commit the transaction has complete knowledge of the conflicting running transactions. Authors state that for these reasons, InvalSTM works well with Haswell RTM. RTM is used for short transactions and low thread counts, while InvalSTM is used for large transactions and high thread counts. RTM can leverage InvalSTM use of Bloom filters for conflict detection by augmenting Haswell's hardware transactions with Bloom filters to enable many hardware transactions to execute concurrently with many software transactions. This enables RTM to perform without interference when read-only software transactions are executing within InvalSTM, regardless of their size.
To manage the shared-memory between RTM and InvalSTM, Invyswell performs the conflict detection after the hardware transaction commits. This is due to the constraints of Haswell RTM, since every write operation done by a transaction is held until commit-time. RTM does not support escape actions, hence when a hardware transaction conflicts with a software one, it aborts. By combining invalidation and conflict detection after a hardware transaction commits, this scheme minimises the chance to abort a hardware transaction due to an in-flight software one.
In order to adapt to different types of workloads, Invyswell support 5 types of different transactions, each one with different characteristics:
- Speculative Software Transactions (\textit{SpecSW}), which is a type of transactions similar to an InvalSTM transaction, i.e, uses Bloom filters to track the read and write-sets of the memory addresses accessed. The invalidation is done after the commit of hardware transactions.
- Bloom filter Hardware Transaction (\textit{BFHW}), which uses Bloom filters in order to handle conflicts with SpecSW transactions. After the BFHW transactions commit, it invalidates concurrent SpecSW transactions.
- LiteHW transactions, which are lightweight hardware transactions that execute without read or write instrumentation. These transactions can only commit if there are no in-flight software transaction when they begin their commit phase. Because LiteHWs do not maintain read or write-set metadata, if a software transaction is in-flight when a LiteHW enters it’s commit phase, Invyswell must assume a conflict exists between the LiteHW and the software transaction and, therefore, must abort the LiteHW.
Efficient Dynamic Data Partition Scheme in Hybrid Transactional Memory
- **IrrevocSW** transactions, which is a software transaction that by being repeatedly aborted, gets a higher priority and acquire a global lock in the beginning of the execution. IrrevocSWs transactions write directly to memory, thus there is no commit phase.
- **SglSW** transactions, which are small software transactions that execute instructions not supported by Haswell RTM, thus need to be executed in software. This transaction type does not use metadata as it writes directly to memory.
Transactions are scheduled in a performance descending order: first the high-risk hardware transactions, then the low-risk software transaction. The transitions between the types of transactions are decided at runtime, based on an application dependent heuristic.
Invyswell has been tested with STAMP benchmark [31] and results show that it performs better in a range of benchmarks than state of the art NOrec [12].
**Reduced Hardware NOrec** The most recent approach in HyTM is the reduced hardware (RH) proposed by Matveev et. al [28]. The authors applied it to the Hybrid NOrec algorithm, resulting in a new HyTM that overcomes the scalability limitations of Hybrid NOrec [11].
In order to eliminate Hybrid NOrec’s scalability problems, two hardware transactions are added to the software transactions resulting in a *mixed-slow path*. Both of these bottlenecks are caused by reading of the shared clock too early by software and hardware transactions. The first hardware transaction added to the *mixed-slow path*, called *HTM postfix*, encapsulates all the slow path writes at commit point and executes them all together. This change to the *mixed-slow path* enables the hardware transactions to delay the read of the clock to just before committing, avoiding the frequent false-aborts of the original Hybrid NOrec. The other hardware transaction added to the *mixed-slow path*, called *HTM prefix*, executes the largest possible prefix of slow-path reads in a hardware transaction, this is done by starting the *mixed-slow path* as a hardware transaction and executing within it as much reads as possible, or until the first write is encountered. This hardware prefix allows deferring the read of the global clock to after the reads, which significantly reduces the chances of aborting.
Authors state that the algorithm preserves opacity and privatization, as the original Hybrid NOrec. Finally if the *mixed-slow path* fails to commit, the algorithm reverts to the original Hybrid NOrec.
The results of Reduced Hardware NOrec with STAMP benchmark suite [31] indicate that RH NOrec is able to reduce the number of HTM conflicts comparing to Hybrid NOrec [11].
Table 1 summarises all TM implementations presented on the document. First, it is characterised the type of TM as STM, HTM or HyTM. Second, it is described the existence of metadata and their usage by the TM implementation. Next, it overviews the existence of spurious aborts, i.e. transactions that were aborted unnecessarily, even when they did not threaten correctness. Then, it overviews the usage of hardware capacity, which is only available on HTM and
HyTM. Finally, it overviews if the TM implementation has privatisation safety, and also the existence of invisible reads, i.e. reads made by one transaction that are not visible to the other active transactions.
<table>
<thead>
<tr>
<th>TM implementation</th>
<th>Type</th>
<th>Metadata</th>
<th>Spurious Aborts</th>
<th>HW capacity used for</th>
<th>Invisible Reads</th>
<th>Privatisation Safety</th>
</tr>
</thead>
<tbody>
<tr>
<td>TinySTM [20]</td>
<td>STM</td>
<td>Yes, oreCs</td>
<td>No</td>
<td>-</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>SwissTM [19]</td>
<td>STM</td>
<td>Yes, four-word lock granularity</td>
<td>No</td>
<td>-</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>NOrec [12]</td>
<td>STM</td>
<td>No</td>
<td>No</td>
<td>-</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>TSX HLE</td>
<td>HTM</td>
<td>No</td>
<td>Yes</td>
<td>Read and write-set</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>TSX RTM with Global lock</td>
<td>HTM</td>
<td>No</td>
<td>Yes</td>
<td>Read and write-set</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>IBM Power8</td>
<td>HTM</td>
<td>No</td>
<td>Yes</td>
<td>Read and write-set</td>
<td>No, because of pause/resume instructions</td>
<td>Yes</td>
</tr>
<tr>
<td>Hybrid NOrec [11]</td>
<td>HyTM</td>
<td>lock counters</td>
<td>Less frequent</td>
<td>Data and lock counters</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Hybrid-LSA [36]</td>
<td>HyTM</td>
<td>Yes, OreCs</td>
<td>Yes</td>
<td>OreCs and Data updates</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Hybrid NOrec-2 [36]</td>
<td>HyTM</td>
<td>Yes, OreCs</td>
<td>Yes</td>
<td>OreCs and Data updates</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Invyswell [8]</td>
<td>HyTM</td>
<td>Read and Write Bloom-Filters</td>
<td>Yes</td>
<td>Depends on the state of the system</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>RH NOrec [29]</td>
<td>HyTM</td>
<td>Yes, Lock counters</td>
<td>Yes</td>
<td>Data and locks</td>
<td>Yes</td>
<td>Yes</td>
</tr>
</tbody>
</table>
Table 1: Comparison of various TM state of the art implementations: TinySTM, SwissTM, NOrec, TSX HLE, TSX RTM with global lock, IBM Power8, Hybrid NOrec, Hybrid-LSA, Hybrid NOrec-2, Invyswell and Reduced Hardware NOrec.
2.4 Benchmarks for TM
While several TM systems have been proposed in the literature, there was an urge to develop benchmarks that can correctly analyse and compare the proposals. Most TM systems have been evaluated using microbenchmarks, such as linked lists or red-black trees, which may not be representative of any real-world behaviour, or individual applications, which do not stress a wide range of execution scenarios. Consequently, it has been argued that non-trivial, or realistic, benchmarks are needed to further TM research and to present the "real" benefits of TM.
Some desirable features of non-trivial TM benchmarks are the existence of large amounts of parallelism, executed by code difficult to parallelize using locks,
which makes TM more attractive than fine-grain locking. The existence of real-world applications are also desirable because it gives confidence to programmers to use it. Several types of workloads can stress the TM implementations, from long to short transactions, high to low level of contention and different sizes of read and write-set.
**STMBench** Guerraoui et. al proposed STMBench7 [24], a benchmark for evaluating STM implementations. The underlying data structure of STMBench7 consists of a set of graphs and indexes intended to be suggestive of more complex applications like CAD, CAM and CASE. A collection of operations is supported to model a wide range of workloads and concurrency patterns. There are *long traversals*, which go through all the assemblies and/or all atomic parts and update some of them. Second, there are *short traversal* that traverse via a randomly chosen path. Third, there are *short operations*, which randomly chose some object (or a few objects) in the structure and perform an operation on the object or it’s local neighbourhood. Finally, there are *structure modification operations*, which are operations that create or delete elements of the structure or links between elements randomly.
STMBench7 is likely to benefit STM over HTM and HyTM, as transactions will likely have larger read and write-sets to keep track of objects visited, thus causing capacity aborts on HTM. STM is expected to perform better as the size of read and write-set does not degrade the performance of it.
**Lee-TM** Ansari et al. proposed Lee-TM [7], a benchmark based on Lee’s routing algorithm, which consists in circuit routing, the process of automatically producing an interconnection between electronic components. This is achieved based on two phases of the algorithm, *expansion* and *backtracking*. Lee-TM has five implementations of Lee’s routing algorithm, which generates a very heterogeneous workload encompassing a wide range of transactions’ duration and length. The benchmark starts by routing the shortest junction in the circuit, generating transactions whose local processing lasts just a few milliseconds. HTM is highly probable to have better performance in this first phase than STM as transactions are shorter, and so the read and write-set, which lead to overheads due to instrumentation in STM that are avoided by the pure hardware execution of HTM. The benchmark progressively lays junctions of increasing length, generating workloads whose local processing lasts up to a few seconds, which in turn is likely benefit STM over HTM, due to the capacity aborts of HTM incurred by the size of the read and write-set.
**STAMP** Minh et al. proposed STAMP [31], a benchmark suite, which enable the analysis of a wide range of TM systems through the use of a wide range of transactional characteristics such as transaction lengths and sizes of read and write-sets.
STAMP consists in eight applications with 30 different sets of configurations and input data that recreate applications from diverse domains, such as e-
commerce, Delaunay triangulation, graph processing and circuit routing. The workloads produced by the benchmarks variate from short to long transactions, small to large read and write-set, low to high time spent on the transaction and different levels of contention.
STAMP is portable across different TM implementations, i.e. HTM, STM and HyTM. However, STAMP generally does not work as expected on existing HTM, as it causes nonessential transaction aborts in some of the programs, which motivated researchers to propose a modified version that can fairly compare the intrinsic performance of HTM systems [32].
**Memcached** Memcached [37] is a distributed in-memory software cache, where multiple clients place key-value pairs on multiple servers. Memcached uses an in-memory hash table that stores key-value pairs. It provides operations such as get, replace, delete and compare-and-swap on these keys. Clients can also request the current status cache, and related statistics.
Tests made by Holla et al. [26] indicate that cache locks and stats have high contention but not the data, and propose the use of lock elision [16,26]. Authors find that lock elision can provide non-trivial benefits to both power and performance, although not all hardware configurations were beneficial due to the existence of false conflicts.
Memcached workload is characterised by small transactions, which should benefit HyTM and HTM, as normally transactions read and write-set fit in cache.
**Kyoto Cabinet** Kyoto Cabinet [1] is a benchmark suite of Data Base Management data stores written in C++ and produced by Fal Labs. The in-memory component of the suite, Kyoto CacheDB, splits the database into slots, where each slot is a hash table of binary search trees. Each key is hashed into a slot and then hashed again into a hash table of the slot. Kyoto CacheDB first fills the database to a fixed initial size, and then executes operations, e.g. gets, puts or deletes, with random keys. This benchmark will be likely to benefit STM and HyTM, as with the available operations (gets, puts and deletes) it will search through the index and increase the length of the transaction, and also the size of read and write-set, which consequently cause HTM to abort.
3 Solution architecture
The analysis of the state of the art conducted in the previous section highlights that in the literature there are no solutions that can efficiently handle various types of workloads. HTM has good performance for short transactions with small read and write-set, however it’s performance degrades when transaction size increase. STM has good performance for workloads characterised by long transactions with various types of read and write-set yet, in presence of transactions with small length it’s performance is inferior than HTM. HyTM has non-negligible costs incurred by synchronising HTM and STM in order to work as a coherent
whole. Consequently, the performance of HyTM is not as good as HTM for short transactions and not as good as STM for long transactions.
This dissertation aims to fill this relevant gap by proposing a dynamic memory partitioning mechanism that will allow HTM and STM to execute concurrently on disjoint memory partitions without incurring any instrumentation overhead.
Preliminary tests were made in order to study the execution of HyTM on disjoint data with no synchronisation over HTM and STM. The HyTM implementation used is composed by Intel TSX (see section 2.2) and TinySTM (see section 2.1) with no synchronisation done between the two backends. A synthetic benchmark was generated, composed of two disjoint linked lists, one shorter (prone to benefit HTM) and one larger (prone to benefit STM). Whenever an operation is issued to the shorter linkedlist, it is used the HTM implementation to handle the execution of the operation. And similarly, whenever an operation is issued to the larger linkedlist, STM executes the operation. The same experiment was made with state of the art Hybrid NOrec and Intel Haswell using a single global lock as the fallback path, TinySTM and NOrec.
The results of all experiments are shown on Figure 1 and on Figure 2, on the throughput side the prototype scaled better than the other TMs, as longer transactions are handled by the STM fallback (TinySTM), and the shorter by HTM. TinySTM had the second best performance, due to it’s scalability and the design approach of reducing instrumentation. NOrec had better performance than both HTM-SGL and Hybrid-NOrec, as HTM-SGL has overheads due to capacity aborts incurred. Hybrid-NOrec had worse performance due to the read of the global clock by transactions, which causes transactions to abort upon commit of any transaction. The results of the energy spent on the execution of the workload show that the prototype consume less energy on the execution of the workload than the other TM implementations. HTM had similar energy consumption to the prototype until 2 threads, however with the increase of the number of threads, the energy consumption increases. TinySTM has the second lowest energy consumption at both four threads and eight followed by NOrec. Hybrid-NOrec had the highest consumption of energy because of high abort-rate, mainly due to the read of the global clock.
As discussed in Section 2.1, the idea of partitioning memory and to use different TM algorithms has first been introduced by Riegel et al. [35]. This work has showed that for several STAMP benchmarks, memory can be statically partitioned in an effective way, i.e., so to use in each partition different software TM algorithms tailored for different workload characteristics.
However, this work has also highlighted that static memory partitioning can often be inadequate, in particular with applications that use pointers extensively (as it is often the case in practice). Further, this work considered, as alternative TM mechanism, only software-based implementations. This leaves open the question of whether approaches based on memory partitions remain practically viable also when considering hybrid TM systems encompassing both hardware and software implementations.
In my dissertation, I plan to address these shortcomings by proposing a dynamic memory partitioning mechanism specifically targeted to tackle the challenges raised by the need of supporting concurrent execution of hardware and software TM implementations.
The idea is to exploit the output of an initial static code analysis to determine an initial set of disjoint memory partitions, analogously to what is proposed by Riegel et al. [35]. Unlike in this solution, though, the assignment of data partitions to different TM algorithms does not require to be perfect. Conversely, accesses to memory partitions not assigned to a given TM mechanism shall be detected at run-time and trigger either: a) the reassignment of the transaction to a different TM implementation (in case one exists given the current memory partitioning scheme), or b) the alteration of the memory partitioning scheme and the remapping of the accessed memory region (in case this is deemed as beneficial for the system as a whole), or c) the switch to a state of the art, conventional HyTM implementation, which can support concurrent execution of both HTM and STM, although with additional overheads/instrumentation.
One key challenge that shall be addressed in order to make the proposed solution viable in practice is how to detect illegal accesses to shared memory regions in an efficient way, i.e., without requiring checking additional metadata. This could be very problematic in particular for HTM, which would consume valuable cache capacity just to load these additional metadata (as discussed in Section 2.3).
The key idea that I plan to exploit to tackle this issue is to exploit conventional virtual memory protection mechanisms in an innovative way. The idea is to partition threads into two classes, one allowed solely to use HTM and one STM. In order to enforce access of each class of threads to their assigned memory regions, the mprotect system call will be used: this system call can be used to assign different access rights to different threads (within the same process) at the page granularity. This way, any violation of the intended memory partitioning scheme will be detected at the operating system level, by exploiting the dedicated
Efficient Dynamic Data Partition Scheme in Hybrid Transactional Memory
hardware mechanisms for memory protection, without requiring any additional application level checks. The runtime library will be notified of possible violations of the memory partitioning via a SIGSEV signal, and will be able to react implementing the different reconfiguration strategies sketched above.
Clearly, there are a set of challenges and of potential pitfalls involved with this design that shall be assessed and evaluated during the following phases of my work.
The first challenge is associated with the costs associated with the usage of system calls to dynamically redefine the memory mapping, as well as of signal handlers to react to violations of the expected memory partitioning.
Another relevant issue that deserves further study is how to avoid the risk of frequent "ping-ponging" memory pages between different partitions. In fact, reconfiguring the memory partitions has a non-negligible cost, given that it entails the execution of one or more system calls. The dynamic partitioning scheme should therefore minimise the frequency of relocation of a given memory page. Conversely, when such problematic situations are detected, the system should fallback to using a conventional hybrid TM. The challenge here lies in detecting such scenarios in an timely, yet efficient way, as well as to support the fast switch to the fallback synchronisation mechanism.
4 Evaluation
The proposed system will be evaluated and compared to state of the art TM implementations, namely Intel TSX, TinySTM [20], SwissTM [19], NOrec [12], Hybrid NOrec [11], Hybrid-LSA [36], Reduced Hardware NOrec [29] and coarse/fine-grained locking solutions. The key metrics that will be used to evaluate the solutions are the following:
- Throughput
- Abort Rate
- Response Time
- Energy Consumption
- Energy Delay Product
- Exponential Energy Delay Product
- Reconfiguration Latency
Throughput and Abort Rate are used to measure respectively the number of transactions committed and aborted per second, this metrics are indicators of the TM’s performance, as less aborted transactions and more committed transactions represent a primary goal of this work. Response Time represents the time spent by a transaction since the beginning until the commit. Energy Consumption is measured via Intel’s RAPL [14] interface and represents the Joules consumed by the execution of the solution; Energy Delay Product, as the name suggests, is the product of energy by time expended in execution; Exponential Energy Delay Product, or ExpEDP is instead given by the product of the energy spent times the square of the execution time, and, hence, gives more emphasis to time.
The system will be tested in a wide variety of workloads, from short to long transactions, high to low contention, and various types of read and write-sets sizes. Different number of threads will be used and different hardware, namely Intel Haswell and IBM Power, to stress the solution and highlight the advantage of running different TMs on disjoint data partitions.
In the evaluation of the implementation it will be used the redblack tree and linkedlist microbenchmarks, as well as the following benchmarks: STMBench7 [24], Lee-TM [7], STAMP [31], Memcached [26] and Kyoto Cabinet [1].
5 Scheduling of Future Work
− 15 January - 15 February: Implementation of a preliminary prototype that uses a simple initial static partitioning, and exploits the mprotect system call to detect violations of the expected partitioning. Also, porting of the microbenchmarks to use the APIs exposed by current prototype.
− 15 February - 15 April: Extension of the preliminary prototype to support dynamic remapping of the memory regions between HTM and STM depending on the applications access pattern. Also, benchmarking and profiling of the costs associated with the use of system calls to dynamically re-map the memory regions to different threads.
− 15 April - 15 June: Porting of STAMP benchmarks and of Kyoto Cabinet to use the APIs exposed by the current prototype. Also, analysis of the effectiveness of the partitioning, via either static and dynamic methods, of the STAMP benchmarks and investigation and experimentation of various dynamic memory partitioning schemes.
− 15 June - 15 August: Integration with fallback path based on a conventional Hybrid TM. Also Profiling, benchmarking and performance optimisations of the solution.
− 1 September - 1 October: Thesis and paper preparation.
6 Conclusions
In this document I conducted a study on state of the art of Transactional Memory, focusing on the problem of enhancing efficiency of HyTM. The analysis of the state of the art highlighted different approaches on implementing TM: software (STM), Hardware (HTM) and a hybrid of hardware and software (HyTM). My analysis highlighted that none of these approaches successfully delivers a constant performance for all types of workloads, i.e. HTM has high performance for workloads characterised by short transactions with read and write-sets that can fit in cache, yet STM has high performance for long transactions with various types of read and write-sets, while HyTM has a performance in between of HTM and STM but with the incurring costs of synchronising HTM and STM.
During the next phase of my dissertation I aim at addressing precisely this issue as in this document I have already identified some of the key design choices and challenges that I will have in implementing a hybrid solution that can
partition data and execute HTM and STM without any instrumentation cost. Further, I have described a detailed roadmap of my future research activities.
References
2. z/Architecture Principle of Operations. SA22-7832-09
Efficient Dynamic Data Partition Scheme in Hybrid Transactional Memory
|
{"Source-Url": "http://www.gsd.inesc-id.pt/~romanop/files/students/PR/report.pdf", "len_cl100k_base": 13360, "olmocr-version": "0.1.50", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 63612, "total-output-tokens": 16862, "length": "2e13", "weborganizer": {"__label__adult": 0.0004220008850097656, "__label__art_design": 0.0004591941833496094, "__label__crime_law": 0.00036215782165527344, "__label__education_jobs": 0.0005927085876464844, "__label__entertainment": 0.00010269880294799803, "__label__fashion_beauty": 0.00020885467529296875, "__label__finance_business": 0.0003533363342285156, "__label__food_dining": 0.00037384033203125, "__label__games": 0.0009455680847167968, "__label__hardware": 0.00485992431640625, "__label__health": 0.00048828125, "__label__history": 0.00042724609375, "__label__home_hobbies": 0.00012922286987304688, "__label__industrial": 0.0006909370422363281, "__label__literature": 0.00028634071350097656, "__label__politics": 0.0003643035888671875, "__label__religion": 0.0005941390991210938, "__label__science_tech": 0.098388671875, "__label__social_life": 6.824731826782227e-05, "__label__software": 0.0078887939453125, "__label__software_dev": 0.88037109375, "__label__sports_fitness": 0.0003275871276855469, "__label__transportation": 0.0008559226989746094, "__label__travel": 0.0002397298812866211}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75143, 0.02001]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75143, 0.44999]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75143, 0.913]], "google_gemma-3-12b-it_contains_pii": [[0, 2019, false], [2019, 5335, null], [5335, 8113, null], [8113, 11367, null], [11367, 14735, null], [14735, 17951, null], [17951, 20886, null], [20886, 24159, null], [24159, 27381, null], [27381, 30762, null], [30762, 33826, null], [33826, 37066, null], [37066, 40365, null], [40365, 43521, null], [43521, 46722, null], [46722, 49345, null], [49345, 52408, null], [52408, 55320, null], [55320, 58566, null], [58566, 60799, null], [60799, 63529, null], [63529, 66340, null], [66340, 69410, null], [69410, 72862, null], [72862, 75143, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2019, true], [2019, 5335, null], [5335, 8113, null], [8113, 11367, null], [11367, 14735, null], [14735, 17951, null], [17951, 20886, null], [20886, 24159, null], [24159, 27381, null], [27381, 30762, null], [30762, 33826, null], [33826, 37066, null], [37066, 40365, null], [40365, 43521, null], [43521, 46722, null], [46722, 49345, null], [49345, 52408, null], [52408, 55320, null], [55320, 58566, null], [58566, 60799, null], [60799, 63529, null], [63529, 66340, null], [66340, 69410, null], [69410, 72862, null], [72862, 75143, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75143, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75143, null]], "pdf_page_numbers": [[0, 2019, 1], [2019, 5335, 2], [5335, 8113, 3], [8113, 11367, 4], [11367, 14735, 5], [14735, 17951, 6], [17951, 20886, 7], [20886, 24159, 8], [24159, 27381, 9], [27381, 30762, 10], [30762, 33826, 11], [33826, 37066, 12], [37066, 40365, 13], [40365, 43521, 14], [43521, 46722, 15], [46722, 49345, 16], [49345, 52408, 17], [52408, 55320, 18], [55320, 58566, 19], [58566, 60799, 20], [60799, 63529, 21], [63529, 66340, 22], [66340, 69410, 23], [69410, 72862, 24], [72862, 75143, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75143, 0.05936]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
992cbc67b0175ddd15300e7fb80f02efa1491c16
|
[REMOVED]
|
{"Source-Url": "http://www.di.unipi.it/~basile/papers/pact2013full.pdf", "len_cl100k_base": 13256, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 61492, "total-output-tokens": 15488, "length": "2e13", "weborganizer": {"__label__adult": 0.0004270076751708984, "__label__art_design": 0.0006756782531738281, "__label__crime_law": 0.0007691383361816406, "__label__education_jobs": 0.0013895034790039062, "__label__entertainment": 0.00011926889419555664, "__label__fashion_beauty": 0.00020265579223632812, "__label__finance_business": 0.001064300537109375, "__label__food_dining": 0.0005164146423339844, "__label__games": 0.000919818878173828, "__label__hardware": 0.0013341903686523438, "__label__health": 0.0011281967163085938, "__label__history": 0.0004549026489257813, "__label__home_hobbies": 0.0001823902130126953, "__label__industrial": 0.0006732940673828125, "__label__literature": 0.0005478858947753906, "__label__politics": 0.0004243850708007813, "__label__religion": 0.0005097389221191406, "__label__science_tech": 0.185546875, "__label__social_life": 0.00012302398681640625, "__label__software": 0.01419830322265625, "__label__software_dev": 0.787109375, "__label__sports_fitness": 0.0002918243408203125, "__label__transportation": 0.0009083747863769532, "__label__travel": 0.00032806396484375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50636, 0.01666]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50636, 0.17671]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50636, 0.84054]], "google_gemma-3-12b-it_contains_pii": [[0, 2815, false], [2815, 6258, null], [6258, 8732, null], [8732, 12543, null], [12543, 15439, null], [15439, 19011, null], [19011, 21959, null], [21959, 24653, null], [24653, 28065, null], [28065, 32034, null], [32034, 35090, null], [35090, 38271, null], [38271, 42217, null], [42217, 46554, null], [46554, 49830, null], [49830, 50636, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2815, true], [2815, 6258, null], [6258, 8732, null], [8732, 12543, null], [12543, 15439, null], [15439, 19011, null], [19011, 21959, null], [21959, 24653, null], [24653, 28065, null], [28065, 32034, null], [32034, 35090, null], [35090, 38271, null], [38271, 42217, null], [42217, 46554, null], [46554, 49830, null], [49830, 50636, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50636, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50636, null]], "pdf_page_numbers": [[0, 2815, 1], [2815, 6258, 2], [6258, 8732, 3], [8732, 12543, 4], [12543, 15439, 5], [15439, 19011, 6], [19011, 21959, 7], [21959, 24653, 8], [24653, 28065, 9], [28065, 32034, 10], [32034, 35090, 11], [35090, 38271, 12], [38271, 42217, 13], [42217, 46554, 14], [46554, 49830, 15], [49830, 50636, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50636, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
a10f2754f629eb15a3a47b14b76018299db8ce96
|
FRESCOR network contracts
In this section, we describe the specification of the FNA (FRESCOR Network Adaptation) layer, aimed at integrating network protocols in the FRESCOR framework, and the implementation of FRESCOR network contracts using the Real-Time Ethernet Protocol (RT-EP). [5]
1. Introduction
One of the main keys in FRESCOR is the concept of an integrated view of the different resources involved in a transaction, like the processor, network, memory or disk resources, that eases the deployment of complex distributed applications with a variety of real-time requirements, including hard real-time behaviour as well as soft requirements. For doing that, the framework is based on the notion of contracts that are negotiated between the application and the system. The most important FRESCOR modules concerning to networks are the Core, Spare capacity and Distributed modules:

1.1 Core services
Similar to the core FRESCOR module, the contracts on the network allow the application to specify its minimum utilization (bandwidth) requirements, so that the implementation can make guarantees or reservations for that minimum utilization. We reuse the contract structure that is used for processing nodes, where the main core attributes that apply for distribution are shown in the Fig. 2.
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>label</td>
<td>Global ID</td>
</tr>
<tr>
<td>resource type</td>
<td>Processor, network, memory, ...</td>
</tr>
<tr>
<td>resource id</td>
<td>An identifier of the resource</td>
</tr>
<tr>
<td>min budget</td>
<td>Min execution capacity per vres period</td>
</tr>
<tr>
<td>max period</td>
<td>Maximum virtual resource period</td>
</tr>
<tr>
<td>deadline</td>
<td>The deadline of the virtual resource</td>
</tr>
</tbody>
</table>

In addition to the core attributes, a new protocol-dependent attribute is created, that identifies extra information that might be required by a particular network protocol. In the case of RT-EP, although multicast packets could be treated slightly differently in the schedulability analysis, we finally decided not to specify any protocol-dependent attribute and treat them as normal messages.
1.2 Distributed model
Once the application negotiates a contract specifying that it is for a network resource, the FRESCOR implementation will create a network virtual resource for that contract, in a way similar to the creation of processor virtual resources for processor-related contracts. This network virtual resource is an implementation object that contains a copy of the relevant contract parameters, keeps track of the consumed resources, guarantee the allocation of the minimum resources, and prevent the application from using more resources than those declared in the contract.

Fig 3.- Communication elements in FRESCOR
To keep track of consumed network resources and to enforce budget guarantees, it is necessary that the information is sent and received through specific FRESCOR services. Therefore, we need to create objects similar to the sockets that we call communication endpoints (see Fig 3).
A send endpoint contains information about the network to use, the destination node, and the network-wide message stream identifier that is used to establish the link between the send endpoints and the associated receive endpoints. The send endpoint is bound to a network virtual resource that specifies the scheduling parameters of the messages sent through that endpoint, keeps track of the resources consumed, and limits the bandwidth to the amount reserved for it by the system.
A receive endpoint contains information about the network and message stream id to use. It may get messages sent from different send endpoints, possibly located in different processing nodes.

Fig 4.- Example of distributed transaction
The following example illustrates the use of the distributed FRSH module through a very simple distributed transaction in a system containing a task that is triggered by the periodic arrival of a message from a remote sensor. Figure 4 shows the architecture of this transaction. Figure 5 shows the pseudocode of each of the two tasks in the transaction.
1.3 Spare Capacity services
In the distributed FRESCOR we want to provide the same level of support for spare capacity sharing that is provided for processing nodes. This is a difficult task in the case of a distributed system, because the decisions made in one node may affect another one, requiring distributed consensus in the whole transaction. We do not want to embed all that complexity into the underlying scheduling framework implementation. Therefore, we have chosen to give a minimum support for spare capacity distribution inside the scheduling framework, and leave the consensus problem to some higher-level transaction manager that would make the negotiations for the application.
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>max budget</td>
<td>maximum usable budget</td>
</tr>
<tr>
<td>min period</td>
<td>minimum useful period</td>
</tr>
<tr>
<td>granularity</td>
<td>discrete or continuous</td>
</tr>
<tr>
<td>discrete gran set</td>
<td>pairs (budget,period) discrete gran</td>
</tr>
<tr>
<td>importance</td>
<td>priority to distribute extra cap.</td>
</tr>
<tr>
<td>weight</td>
<td>for vres with the same importance</td>
</tr>
<tr>
<td>stability time</td>
<td>minimum time vres must not change</td>
</tr>
</tbody>
</table>
For this minimum support there is a stability attribute in the service contract, which has the implication that during the stability period the period or budget of the virtual resource can only change if a renegotiation is requested for it; it may not change automatically, for instance because of negotiations for other virtual resources. This provides a stable framework while performing the distributed negotiation.
The following example illustrates the use of the FRESCOR framework and the Spare Capacity services through a very simple distributed transaction and is modeled after a welding system that the University of Cantabria is developing. We have an FTT-SE [4] networked system with several nodes and a specific load and we want to negotiate a new transaction in which one of the nodes will
capture an array of points from a laser profiler representing the depth of the welding area and then send it to another node where a controller will activate an actuator, for moving the welding torch.
As shown in Fig. 7, three contracts must be negotiated:
- **Network contract**: this is the contract needed to send the array of points to the controller. We specify a range of budgets so that if the network has enough capacity we can send all the points, but if the network already has a big workload or, later, new contracts are negotiated, a lower capacity would be granted by the system, although always over the minimum required. This is the functionality provided by the Spare Capacity module. Note that for the receiving endpoint it is not needed to negotiate any contract.
- **Laser thread CPU contract**: this is the thread in charge of capturing, processing and sending the points obtained from the laser profiler. In each period it will read the current budget assigned to the network contract to see how many points can be sent. Depending on this information it will process and send more or less points.
- **Controller thread CPU contract**: this is the thread in charge of receiving the data from the network and actuating on the motors controlling the movement of the welding torch. Its budget must be prepared for processing the maximum size of the array.
On the other hand, CPU budgets are fixed and must cover the requirements for processing the whole set of points of the laser. When only a subset of the points is needed to be used in the transaction, threads will use less capacity and the FRESCOR dynamic reclamation module will give that capacity to other threads.
The pseudocode of the threads involved in the transaction would look like this:
**Main threads**
vres := negotiate cpu contract
create thread & bind to vres
**Laser thread**
n_vres := negotiate network contract
create send_endpoint & bind to n_vres
loop
c := get budget (n_vres)
read laser profiler
process points (c)
send points (c)
frsh_timed_wait
end loop
**Controller thread**
create receive_endpoint
loop
read points
process points
send command to actuator
end loop
In this simple example, where FRESCOR is used at a low level of abstraction, all the contracts involved in the transaction have a fixed period. If renegotiations in the transaction were necessary to switch to different periods, they should be made through the FRESCOR highlevel transaction manager which will provide the necessary distributed coordination for a global negotiation of the diverse resources involved in the transaction (including CPU, networks, memory or even bus accesses), and whose description is outside the scope of this deliverable.
1.4 RT-EP (Real-Time Ethernet Protocol)
RT-EP is a software based fault tolerant token-passing Ethernet protocol for multipoint communications in real-time applications, that does not require any modification to existing Ethernet hardware. This protocol allows the designer to model and analyze the real-time application using it, because it is based on fixed priorities and well-known schedulability analysis techniques can be applied.
Fig 8.- RT-EP architecture
The Figure 8 shows the architecture of RT-EP. Each station (processing node or CPU) has a transmission queue, which is a priority queue where all the packets to be transmitted are stored in priority order. Packet information size is limited to 1492 bytes and fragmentation of messages is not allow at this layer. Each station also has a set of reception queues that are also priority queues. Packets with the same priority are stored in FIFO order. The number of reception queues can be configured depending on the number of application threads (or tasks) running in the system and requiring reception of messages.
Fig 9.- RT-EP stations conform a logical ring
Each application thread should have its own reception queue attached. The application has to assign a number, the channel ID, to each application thread that requires communication through the protocol. The network is logically organized as a ring. Each station knows which other station is its predecessor and its successor, so the logical ring can be built. The protocol works by rotating a token in this logical ring to avoid collisions in the Ethernet media.
The token holds information about the station having the highest priority packet to be transmitted and its priority value. The network operates in two phases. The first phase corresponds to the priority arbitration, and the second phase to the transmission of an application message. During the priority-arbitration phase the token travels through the whole ring, visiting all the nodes. Each station checks the information in the token to determine if one of its own packets has a priority
higher than the priority carried by the token. In that case, it changes the highest priority station and associated priority in the token information; otherwise the token is left unchanged. Then, the token is sent to the successor station. This process is followed until the token arrives at the token_master station, finishing the arbitration phase. In the message-transmission phase the token_master station sends a message to the station with the highest priority message, which then sends the message. The receiving station becomes the new token_master station.
![RT-EP State machine diagram]
The recovery method is based on simultaneous listening to the media by all the stations. Each station, after sending a packet, listens to the media for an acknowledge, which is the transmission of the next frame by the receiving station. If no acknowledge is received after some specified timeout, the station assumes that the packet is lost and retransmits it. The station repeats this process until an acknowledge is received or a specified number or retransmissions is produced. In the latter case the receiving station is considered as a failing station and will be excluded from the logical ring. Because retransmission opens the door to duplicate packets if a station does not respond in time, a sequence number is used to discard duplicates at the receiving end.
1.5 DFSF (Distributed First Scheduling Framework)
DFSF is the previous proof-of-concept implementation of contract-based reservations on a network, and it is described in an annex of the deliverable D-OS.1v3 of the previous European project FIRST. For simplicity reasons it focused only on the core module, and made some restrictions. The scenario was a single ethernet network using a modified version of the RTEP protocol that we was called DFSF_RTEP.
Figure 11 depicts the architecture of DFSF_RTEP and it contains the following modules:
- **DFSF.Shared_Info**: This package contains a protected object called Table, with the information about the contracts that is shared among all the nodes. The information allows a node to negotiate a new contract, or renegotiate a previous one.
- **DFSF.Servers**: This package contains a protected object called Table that stores the information relative to a server that is local to the node where it is created, and therefore needs not be shared among the different nodes. The most important piece of this information is the current budget of each server.
- **DFSF.Negotiation**: This package contains a protected object called Engine that implements the state machine associated with the contract negotiations, and all the associated information. To negotiate a contract there is a negotiation token that must be acquired to ensure mutual exclusion. Once the negotiation is finished the information must be propagated to all the other nodes. The information associated with these operations is circulated in the token ring, and this package manages it as a function of the current negotiation state of each node.
- **DFSF_RTEP.Protocol**: This package implements the interface offered to the user, which in this case is the FSF layer.
Two example sequences are shown in the figure 11:
- In the numbered sequence (in yellow) we see the flow of a negotiation. Negotiation.Engine implements the State Machine shown in Fig. 10, Shared_Info stores the network contracts of all the stations in the ring so we can make a utilization test, and the Servers module contains our server's information including the shared info and the track of the consumed resources and budget available.
- In the Lettered sequence, we see the flow for the delivery of a packet.

In order to implement FSF with RTEP a new fixed field of 29 bytes had to be included in every packet of the protocol and the Main Task algorithm was changed to introduce the State Machine shown in figure 12. The node starting the negotiation successively switches from the Idle state to Acquiring_Negotiation_Token, Negotiating and Waiting_To_Release_Token. Meanwhile, the rest of the nodes, switch to the Waiting state, where they await the information with the negotiation result.
Although the previous implementation of DFSF was quite successful the architecture had the several problems:
- It was too specific to the protocol, because it was embedded in it, and severe difficulties in its maintainability and extendability.
- There was a 29 bytes overhead in each packet even when no negotiation was in process.
- DFSF was implemented in Ada. As the FRSH framework is supposed to be written in C, we need to offer a C interface.
- Also, negotiation times were not bounded in case of contention.
Therefore, a new architecture in which the negotiation process takes place only on top of the real-time protocol and negotiation times can be bounded is needed.
2. FNA (FRESCOR Network Adaptation) layer
The architecture of FRESCOR in a distributed system is divided into independent processor modules that handle negotiations in each processor, and independent network modules that handle negotiations for each network in the system.

A uniform interface called FNA (FRSH Network Adaptation layer) has been designed to allow easily plugging in network modules for the same or different networks. Figure 13 shows a high-level view of this modular architecture, for an example of a system with two nodes and two different networks.
The full description of FNA is provided in the Annex A of this deliverable and its most important functionality is to handle negotiations of contracts, send-receive operations and maintain virtual network resources. FNA functions are called internally from the FRSH implementation. We need to register them as hooks and associate them to a specific value of resource id. This can be done with a static configuration file or by using a register function. In the figure 14, we can see the main functions from the FRSH API that concerns to distribution and the corresponding FNA hooks.
Similar to the FOSA operating system adaptation layer, there are some functions in the FNA module that are completely dependent on the protocol and therefore must be released as public functions from the application point of view. These set of functions are prefixed with 'frsh' instead of 'fna' to make clear that they are public, and are placed in a different header file.
In order to be integrated into the framework, each network must implement this FNA layer. To be able to negotiate contracts and handle virtual network resources, some services must be provided by the underlying protocol:
- A way to control and analyze the network traffic
- A way to reliably spread the results of a negotiation
- A way to negotiate in mutual exclusion
How to provide these services to support FNA negotiations depends on the protocol. For example, in a centralized approach using the master-slave FTT-SE protocol [4] the control and analysis of the traffic is done by the master using a table and mutual exclusion can be provided through ordinary
mutexes. As the master is the only node performing negotiations, the results of the negotiation could be maintained in its own memory, but for performance reasons a copy should be propagated to the slaves.
In the case of RT-EP we propose a decentralized approach, where FNA implementation will be a distributed module that has parts in all the processors connected through the network. Compared to the DFSF approach we will use a multi-layered architecture in order to facilitate maintainability. RT-EP will be enhanced to support the previous requirements, as we will see in the next section, by adding network scheduling servers, a reliable multicast mechanism and distributed mutexes to the protocol. After that we will see how to build a new layer on top of those requirements to support the FNA negotiation services.
---
**FNA: Frescor Network Adaptation layer to plug-in underlying protocols to the FRESCOR Distributed module**
**Core**
- +frsh_init()
- +frsh_contract_init()
- +frsh_contract_set/get_resource_type_and_id() +frsh_contract_set/get_contract_id()
- +frsh_vres_negotiate() +frsh_vres_negotiate_sync() +frsh_vres_negotiate_async()
- +frsh_vres_get_negotiation_status()
- +frsh_vres_get_resource_available()
- +frsh_vres_get_total_weight()
- +frsh_vres_decrease_capacity()
**Sendrecvpoint**
- +frsh_send_endpoint_create() +frsh_send_endpoint_destroy()
- +frsh_send_endpoint_set_get_params() +frsh_send_endpoint_set_get_id()
- +frsh_send_endpoint_set_get_status()
- +frsh_send_endpoint_set_get_vres_id()
- +frsh_send_endpoint_set_get_sync()
- +frsh_send_endpoint_set_get_status()
**Distributed core**
- +frsh_contract_set/get_protocol_info()
- +frsh_netinfo_get_msg_to_time()
- +frsh_netinfo_get_max_message_size()
- +frsh_negotiation_messages_set/get_period()
- +frsh_contract_set/get_reclamation_params()
- +frsh_vres_get_remaining_stability_time()
- +frsh_vres_get_resource_available()
- +frsh_vres_get_total_weight()
- +frsh_vres_decrease_capacity()
**FNA**
- -frsh_init()
- -frsh_vres_xxxxx()
- -frsh_send(sync)
- -frsh_send_endpoint_set/get_status()
- -frsh_send_endpoint_set/get_resource_id()
- -frsh_send_endpoint_set/get_data()
- -frsh_send_endpoint_set/get_period()
- -frsh_send_endpoint_set/get_resource_id()
- -frsh_netinfo_get_msg_to_time()
- -frsh_netinfo_get_max_message_size()
- -frsh_negotiation_messages_set/get_period()
- -frsh_contract_set/get_reclamation_params()
- -frsh_vres_get_remaining_stability_time()
- -frsh_vres_get_resource_available()
- -frsh_vres_get_total_weight()
- -frsh_vres_decrease_capacity()
**Receivendpoint**
- +frsh_receive_endpoint_create()
- +frsh_receive_endpoint_set_get_params()
- +frsh_receive_endpoint_set_get_status()
- +frsh_receive()
- +frsh_receive_endpoint_set/get_status()
3. RT-EP Enhancements
In order to clarify ideas, the RT-EP implementation has been cleaned up, and restructured. Figure 15 depicts the new directory structure for the RT-EP code:
- RTEP: this is the root directory, where most of the functionality happens.
- POSIX: the RT-EP implementation uses some posix functions (signals, timers and mutexes). We have created this directory to store the Ada files that import these functions from an OS that is written in C.
- LIB: here we store several data types used widely in the RT-EP implementation. We have written them as generics so they can be reusable.
- RTEP_FNA: this is the place for the new FNA layer will be stored.
- TESTS: a directory with a battery of tests and scripts to try them on a free x86 emulator.
- DOC: a directory with a lot of new documentation about the protocol.
As we see, there are no circular dependencies among the different packages. For example, the RTEP_FNA layer depends on the RT-EP services and the generic data types, but RT-EP does not depend on RTEP_FNA.
3.1 Sporadic servers
Server-based scheduling techniques have been used for a long time, typically associated with processor time scheduling, to limit the bandwidth assigned to a particular computation or set of computations while also guaranteeing some minimum level of service. Servers such as the periodic server [6], the sporadic server [7], or the constant bandwidth server are examples of such scheduling policies. The concept of server is also applicable to other resources and in particular to networks. For example, the leaky bucket concept used in network trac shaping [8] is similar to the sporadic
server; EDF-based servers [9] have been successfully applied to the CAN bus.
In RT-EP, packets are scheduled using fixed-priorities so a natural choice to implement servers for RT-EP is to base them on the sporadic server policy [7]. In a processor, the sporadic server policy works by reserving a given amount of execution-time capacity (called budget) for executing a process or a set of processes. In the beginning, the budget is set to a value called the initial capacity. When one of these processes executes it consumes budget. When it finishes executing, the consumed budget is stored in a queue for it to be replenished at some interval after the process started executing. This interval is called the replenishment period. When the budget is exhausted, the processes under the control of the sporadic server are not allowed to run, or at run at a background priority level below the priorities of any other real-time processes. When a server is used to schedule a network the concept of execution time must be turned into transmission time. In most networks, information is sent in units called packets which are usually non-preemptible and therefore constitute the minimum effective budget. Therefore, in a network the most natural unit for measuring budget is a number of packets. In RT-EP the server's budget will be consumed one packet at a time. The non-preemptability property of a single packet must be taken into account as a bounded blocking effect on higher priority servers.
Fig 16. RT-EP Sporadic Servers
Fig 16 shows the properties and architecture of the implementation of servers in RT-EP. Each server is assigned an initial transmission capacity (measured in network packets), a replenishment period (which is a time interval) and a priority. Internally, servers keep track of the current available budget and the count of packets pending to be sent. All this information is kept in a table at the sending node. The extension that we have made to RT-EP allows messages to be sent through a sporadic server, or with a plain fixed priority. In this way, the introduction of servers in RT-EP is still compatible with the use of fixed priority packets. For the plain fixed priority messages, there is a priority queue, called the FP transmission queue, that stores the packets pending to be sent. Packets sent through a sporadic server are stored in a FIFO queue associated with each server, called the server transmission queue. This architecture allows engineers to design several priority bands by using fixed priorities and servers at the same time. It also eases the maintainability of the protocol by eliminating the need of branching the RTEP implementation in two different versions.
When several servers in the same node have packets to be sent, they compete among themselves using a priority queue, called the servers priority queue, that contains pairs of server id and current priority. In this queue, if the current server budget is zero the priority of the server is set to a background level, and if it is larger than zero the server's priority level is used. When the RT-EP main communication task needs to find out which is the packet with the highest priority, it executes the possible pending replenishment operations and then it checks both priority queues, the servers priority queue and the FP transmission queue, to find out which is the pending packet with the highest priority. If the packet is from a server, it finds it in the corresponding server transmission queue.
Figures 18 and 19 shows the queues involved in the integration of the sporadic servers inside RT-EP. For each packet sent from a server the associated budget is decreased by one unit and a replenishment operation is enqueued to occur one replenishment period later. The replenishment operations are stored inside a time-ordered priority queue, for performance reasons.
When the current budget of a server is zero and a replenishment operation takes place, the priority of the server is raised to the normal priority level in the servers priority queue. In the receiving end, RT-EP stores the received messages in reception queues each associated with an application-specified channel number, to implement logical channels for the messages. For each channel, the messages are stored in a priority queue, so that they can be retrieved in priority order.
3.2 Reliable Multicast
A reliable multicast service must ensure that packets are delivered to receivers from the multicast group in a bounded amount of time, free of errors and in the order they were sent by the source. The most typical approach to reliable multicast is the sender-initiated approach, where the sender maintains the state of all the receivers from whom it has to receive acknowledgments (acks). But this technique has a scalability drawback, commonly known as the acknowledgement implosion problem [10]. A receiver-initiated approach, where receivers request the sender the retransmission of packets that are missing could be more scalable but it requires infinite buffers to prevent deadlocks [10].
In [10] two other solutions to the acknowledgment implosion problem that operate correctly with finite buffers are described. Tree-based protocols organize the receivers in a tree and send acks along the tree. And ring-based protocols where the basic premise is to have only one token site responsible for acknowledging packets back to the source. These solutions apply to generic protocols rather than to specific implementations so a direct implementation on RT-EP would be quite inefficient compared to the approach presented in this paper.
In RT-EP the acknowledgment implosion effect of the sender-initiated approach can be reduced by using the RT-EP token mechanism. A multicast message can be sent like the rest of messages but with a multicast address and then the next token round can be started. While finding out the priority of a new message to be sent, receivers could use a negative acknowledgment (NACK) mechanism to indicate that the previous multicast message received was incorrect. Although in the average case the performance of this multicast approach looks good, in the worst case, when there is an error in the transmission, the worst end-to-end transmission time of messages would be greater than for
normal messages because we would have to wait another token round. Also, new functionality should be added to receivers so that they could discard multicast retransmissions that were already received. These requirements would make the protocol more complex.
<table>
<thead>
<tr>
<th>8</th>
<th>6</th>
<th>6</th>
<th>2</th>
<th>2</th>
<th>1</th>
<th>1</th>
<th>2</th>
<th>2</th>
<th>2</th>
<th>1</th>
<th>33</th>
<th>4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pre</td>
<td>Ether Hdr</td>
<td>RTEP Token Hdr</td>
<td>Spare</td>
<td>FCS</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Fig 20.- Ethernet Frame with a Token and Spare bytes
The approach presented in this paper takes the same premise as in the ring-based protocols proposed in [10] where there is only one token site responsible for acknowledging packets back to the source. But we go one step further by distributing the responsibility of retransmissions among all the nodes in the ring. The key of our approach consists on sending multicast information in the spare bytes of the token packets which, due to Ethernet minimum frame size, see Fig. 20, have some spare transmission capacity. In addition, we can take advantage of the built-in fault handling mechanisms present in the protocol to ensure automatic retransmission of faulty packets.
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>2</th>
<th>1</th>
<th>1</th>
<th>26</th>
</tr>
</thead>
<tbody>
<tr>
<td>MType</td>
<td>MAddr</td>
<td>Chan</td>
<td>Prio</td>
<td>Length</td>
<td>Info</td>
</tr>
</tbody>
</table>
Fig 21.- Multicast Frame
Fig. 21 shows the fields of a multicast frame:
- **MType**: Multicast Type selects the multicast operation (an ordinary multicast message, a mutex lock or a mutex unlock operation)
- **MAddr**: Multicast Address (a static table, similar to the ring configuration table, states which nodes belong to a multicast group)
- **Chan**: the destination channel
- **Prio**: the priority of the packet
- **Length**: the length of Info (in bytes)
- **Info**: the information itself
- Also, the source address is implicit in the Token Master field of the RT-EP header
One of the main drawbacks of this approach is that the room for information in each token is small, 26 bytes (although configurable). If greater capacity for multicast were needed the previously mentioned approach with explicit NACKs would be more efficient.
Summing up the multicast procedure, when a node wants to send a multicast packet it enqueues the message as a normal message with the desired priority, but specifying as the destination address a multicast address. Then it competes in the arbitration phase of the protocol like a normal packet. When it is granted with the right to transmit, instead of sending a normal message, a new arbitration phase is initiated and the multicast message is sent through the token. Thanks to the reliability of the token transmission, which used implicit acknowledgements and a timeout-based fault handling mechanism, the protocol ensures that the multicast message is received by all the nodes and free of errors, up to the same reliability level as the normal packets have.
3.3 Distributed Mutexes
There are several algorithms in the literature [11] [12] describing ways of providing mutual exclusion in a distributed system without shared memory. Most of these algorithms can be divided in two groups: token-based and permission-based algorithms.
In [3], a token-based algorithm for RT-EP was implemented taking advantage of the protocol's token. Some extra fields were introduced in the header of every packet of the protocol to inform about the status of a single distributed mutex. In this approach, when a node receives a packet and wants to lock the mutex, it checks the mutex status field. If the mutex is free, it is locked and a notification is circulated in the ring. The unlock operation is similar.
One of the nice points of this architecture is its ability to notify other nodes about status changes in the mutex. For example, when negotiating, nodes that are notified of a mutex lock operation can execute a change of state to wait for the results of the negotiation. Despite this interesting capacity this architecture has not been reused because it also has some drawbacks:
- It lacks scalability and maintainability because if we want to have another mutex we have to modify the protocol and add new mutex fields to the token header
- In case of contention, when several nodes want to lock the mutex, the locking time is not bounded so higher level synchronization messages would be needed.

In our new architecture a permission-based algorithm is proposed. A mutex operation is, like multicast messages, sent through the spare bytes of the RT-EP token with the format shown in the Fig. 22:
- **MType**: a mutex lock or a mutex unlock operation
- **Mutex**: the mutex id
- **Locked**: is the mutex locked?
- **Holder**: if locked, the current holder
- Also, the multicast address is implicit in the mutex id
This multicast frame visits each node during an arbitration phase, to find out if the mutex is free or locked. Nodes check if they own the mutex or not, and recirculate the token in the ring. When the token returns to the sender, variable Locked indicates if some station owns the mutex or not. If the mutex is not locked the node where the multicast message was generated becomes the owner. To unlock the mutex a new multicast message is sent to each node in the ring. With this behavior it is easy to implement the operations provided by the network protocol to the application, which allow the calling thread to block until the mutex is locked, and to unlock the mutex.
This approach solves the problem of scalability because a high number of mutexes can be used. It also helps in bounding the mutex locking time because locking operations can be prioritized. In the
case in which two nodes compete for the mutex with the same priority, the order is not defined. This has been addressed in several distributed mutual exclusion algorithms to solve fairness, typically by using logical clocks to timestamp the requests. In our case, RT-EP sequence numbers could be used instead. In any case, for hard real-time analysis only the worst case scenario is taken into account so this timestamping has not been implemented in the protocol. As with the reliable multicast, fault-handling is also provided automatically by the protocol's token transmission procedures. In the event that a node holding a mutex fails, the RT-EP built-in fault handling mechanism will notify the other nodes about its exclusion from the ring and tasks waiting for that mutex will be awaken.
3.4 Other enhancements
Other minor enhancements include the improvement of the protocol's initialization, the creation of a new interface in C and optimizations in buffer handling by changing copies of data to copies of pointers where possible. Regarding the former enhancement, there was a case in which the protocol could go into a deadlock at initialization time. At initialization time, the first token Master sends requests to the rest of the nodes who must answer with an ACK packet and go to the Idle state. If those ACK packets get lost, the protocol entered to a deadlock. Now, it has been added the possibility of acknowledging this ACK packets even from the Idle State.
4. RT-EP FNA
Once we have an enhanced RT-EP that supports the requirements shown in section 2, all we need to do is to use them correctly to implement the RT-EP FNA layer. The most important functions are the ones regarding to distributed negotiations, renegotiations (synchronous or asynchronous) and cancel contracts. We base our architecture in two tasks: the negotiation task and the receive negotiation results task.
The Negotiation Task is in charge of serving requests from the application. Figure 23 depicts the behavior of this task through an activity diagram. The task consists on a loop where it waits for the application to send a request (for instance, to negotiate, renegotiate or cancel a certain contract). When a request arrives the task locks the distributed mutex to avoid inconsistencies and executes a
scheduling test to check if the contract can be accepted or not. If the contract is accepted it starts the spare capacity distribution (this part has not been implemented yet. We plan to integrate an algorithm that is being developed by the University of York). After that we have to spread out the results of the negotiation. This includes our contract information and possibly other contracts that have been affected by the new spare capacity distribution. When distributing spare capacity we have to take into account the Stability Time parameter. If this time has not expired we can not change its virtual resource associated spare capacity. In order to avoid using global clocks we add the worst case time of spreading the results to the parameter. After all the nodes have received their results the negotiation mutex is unlocked so other nodes can perform negotiations.
Fig 24.- Negotiation task
The *receive negotiation results task* is a very simple task in charge of waiting negotiation results coming from other nodes. Its priority must be higher than the negotiation task in order to avoid possible inconsistencies (for example, because the results are still in the RT-EP buffer).
Fig 25.- RT-EP FNA Structures
Other functionality that RT-EP FNA must implement is described in the figure 25. One is to keep
the accepted_contracts table where the accepted contracts of all nodes is stored. Finally we need to keep a table with the virtual resources created as a result of local negotiations. A virtual resource in RT-EP FNA is composed of a copy of the contract parameters and the RT-EP Sporadic Server in charge of enforcing its values.
5. Testing, debugging and measurements
A lot of effort has been done in order to be able to look into the protocol as deep as possible in order to find possible bugs. A new module has been added to the protocol with several debugging functions. Some of the functions are aimed at printing warning, errors or debugging information depending on the value configurable booleans. Thank to these booleans we can ask the protocol to show only debugging information regarding to distributed mutexes, for example, and so on.
procedure DEBUG (Str : in String; Enabled : in Boolean);
Other functions are aimed at activating different types of time measurements throughout the protocol. A very simple interface is provided to the protocol:
procedure BEGIN_TIME_MEASURE (Id : in Time_Measure.Measure_ID);
procedure END_TIME_MEASURE (Id : in Time_Measure.Measure_ID);
Internally, there is a task (it can be disabled) in charge of collecting all these measures, calculate statistics of worst, best and average case and send them to a Linux node connected to the network as a passive receiver. We provide also a program for Linux, that waits in a socket and receives this information that is then friendly printed in a file so the user can read it. For example, the following is extracted from one of this measurement reports:
Operation(
Type => Simple,
Name => Recv_Info_master,
Worst_Case_Execution_Time => 1.5562e-05,
Best_Case_Execution_Time => 1.1988e-05,
Avg_Case_Execution_Time => 1.2417e-05,
Shared_Resources_List => (RT-EP_Core_master));
Operation(
Type => Simple,
Name => Token_Passing_Time_master,
Worst_Case_Execution_Time => 0.000417039,
Best_Case_Execution_Time => 0.000405476,
Avg_Case_Execution_Time => 0.000409804,
Shared_Resources_List => (RT-EP_Core_master));
Operation(
Type => Simple,
Name => Go_Return_Time_master,
Worst_Case_Execution_Time => 0.00118243,
Best_Case_Execution_Time => 0.000778442,
Avg_Case_Execution_Time => 0.00086987,
Shared_Resources_List => (Test_Server_Msgs_master));
We have used this library to measure the new RT-EP services timings and the their performance metrics, see figure 26, show that the transmission times are very efficient as compared to the regular message transmission times in the RT-EP protocol. The measurement platform is a ring configured with two AMD Duron 800Mhz stations connected through a 100 Mbps Ethernet switch. Since we lack a global time basis for measuring the amount of time to send a packet we measure the time required to send a packet, execute a handler in the other node and receive an answer.
<table>
<thead>
<tr>
<th>Operation</th>
<th>Worst</th>
<th>Avg</th>
<th>Best</th>
</tr>
</thead>
<tbody>
<tr>
<td>Send Server</td>
<td>1.2</td>
<td>0.9</td>
<td>0.8</td>
</tr>
<tr>
<td>Send Multicast</td>
<td>2</td>
<td>1.8</td>
<td>1.6</td>
</tr>
<tr>
<td>Lock a mutex</td>
<td>1</td>
<td>0.8</td>
<td>0.5</td>
</tr>
<tr>
<td>Unlock a mutex</td>
<td>0.5</td>
<td>0.4</td>
<td>0.2</td>
</tr>
</tbody>
</table>
Note: all measures are in milliseconds
Fig 26.- RT-EP service measurements
In the case of RT-EP FNA services the worst execution times are also expressed in terms of few milliseconds (2 to 5 ms in our tests).
Another effort in order to debug the protocol has been the development of a plug-in for a powerful Ethernet sniffer tool called Wireshark (formerly known as Ethereal) [http://www.wireshark.org/]
Fig 27.- Wireshark plug-in for RT-EP
In the figure 28, we can see a sequence of the RT-EP protocol. First we see the initialization packets and how the new improvement to the initialization process (see 3.4) allows the protocol to overcome an ACK lost. After the protocol is initialized we see the arbitration phase, a permission token, a transmission message and then an answer. Each frame can be analyzed field by field in the window below, or byte by byte in the bottom window.
6. Conclusions
The fixed-priority real-time ethernet protocol called RT-EP has been extended with the addition of three new services: a server-based scheduling policy, reliable multicast and distributed mutexes. These services operate together with the previous fixed-priority message transmission that was already available in RT-EP. The new services have been implemented and tested, and their performance metrics show that the transmission times are very efficient as compared to the regular message transmission times in the RT-EP protocol.
Over these services we have implemented a new layer, called RT-EP FNA, that allows us to support bandwidth reservations and integrate it into the FRESCOR distributed contract-based scheduling framework that is under development (when a FRSH implementation is available we will just need to configure FNA hooks so they are called when the user wants to negotiate in our network). This layer in charge of negotiating contracts and managing virtual network resources that keep track of the network resources consumed, and provide the necessary quality of service guarantees for supporting both hard and soft real-time requirements. The new RT-EP protocol will be one of the implementations of the FNA layer in FRESCOR.
In the following page we can see a BIG Picture of the protocol and the different packages involved in the development of the RT-EP FNA layer.
REFERENCES
|
{"Source-Url": "https://marte.unican.es/documentation/rtep/rt-ep_frescor_contracts.pdf", "len_cl100k_base": 9385, "olmocr-version": "0.1.53", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 49432, "total-output-tokens": 10830, "length": "2e13", "weborganizer": {"__label__adult": 0.0003504753112792969, "__label__art_design": 0.00037217140197753906, "__label__crime_law": 0.00037598609924316406, "__label__education_jobs": 0.0003662109375, "__label__entertainment": 0.00015103816986083984, "__label__fashion_beauty": 0.0001615285873413086, "__label__finance_business": 0.0004794597625732422, "__label__food_dining": 0.0003643035888671875, "__label__games": 0.0008873939514160156, "__label__hardware": 0.0057373046875, "__label__health": 0.0004215240478515625, "__label__history": 0.0004267692565917969, "__label__home_hobbies": 9.608268737792967e-05, "__label__industrial": 0.0010776519775390625, "__label__literature": 0.0002455711364746094, "__label__politics": 0.0003261566162109375, "__label__religion": 0.0005855560302734375, "__label__science_tech": 0.232421875, "__label__social_life": 6.93202018737793e-05, "__label__software": 0.032318115234375, "__label__software_dev": 0.72119140625, "__label__sports_fitness": 0.0003058910369873047, "__label__transportation": 0.0007958412170410156, "__label__travel": 0.00027060508728027344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46677, 0.01992]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46677, 0.62093]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46677, 0.90359]], "google_gemma-3-12b-it_contains_pii": [[0, 2385, false], [2385, 4479, null], [4479, 6879, null], [6879, 8573, null], [8573, 9627, null], [9627, 11712, null], [11712, 13081, null], [13081, 14868, null], [14868, 16579, null], [16579, 18813, null], [18813, 21566, null], [21566, 23218, null], [23218, 25934, null], [25934, 27107, null], [27107, 29536, null], [29536, 32394, null], [32394, 35166, null], [35166, 37471, null], [37471, 38794, null], [38794, 41201, null], [41201, 42441, null], [42441, 44292, null], [44292, 44292, null], [44292, 46677, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2385, true], [2385, 4479, null], [4479, 6879, null], [6879, 8573, null], [8573, 9627, null], [9627, 11712, null], [11712, 13081, null], [13081, 14868, null], [14868, 16579, null], [16579, 18813, null], [18813, 21566, null], [21566, 23218, null], [23218, 25934, null], [25934, 27107, null], [27107, 29536, null], [29536, 32394, null], [32394, 35166, null], [35166, 37471, null], [37471, 38794, null], [38794, 41201, null], [41201, 42441, null], [42441, 44292, null], [44292, 44292, null], [44292, 46677, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46677, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46677, null]], "pdf_page_numbers": [[0, 2385, 1], [2385, 4479, 2], [4479, 6879, 3], [6879, 8573, 4], [8573, 9627, 5], [9627, 11712, 6], [11712, 13081, 7], [13081, 14868, 8], [14868, 16579, 9], [16579, 18813, 10], [18813, 21566, 11], [21566, 23218, 12], [23218, 25934, 13], [25934, 27107, 14], [27107, 29536, 15], [29536, 32394, 16], [32394, 35166, 17], [35166, 37471, 18], [37471, 38794, 19], [38794, 41201, 20], [41201, 42441, 21], [42441, 44292, 22], [44292, 44292, 23], [44292, 46677, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46677, 0.10069]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
07521ee3904953d0ac31fde4b3b76e9933368290
|
Software for Extracting 3D - MSSTs
Somchaipeng, Kerawit; Sporring, Jon; Kreiborg, Sven; Johansen, Peter
Publication date: 2003
Document Version
Early version, also known as pre-print
Citation for published version (APA):
Deep Structure, Singularities, and Computer Vision
DSSCV
IST-2001-35443
Deliverable No.: 8
Title: Software for Extracting 3D MSSTs
Author(s): K. Somchaipeng, J. Sporring, S. Kreiborg, and P. Johansen
Institution: 3DLab, School of Dentistry, University of Copenhagen
Classification: Public
Date: September 15, 2003
Abstract
The deep structure of an image is investigated, and a Multi-Scale Singularity Tree (MSST) is constructed based on the pair-wise annihilations of critical points. This report contains two main contributions. Firstly, we describe a fast, simple, and robust method of extracting feature lines from data sets of up to four dimensions, which we apply in order to extract critical paths from $3^{+1}$D scale-spaces. Secondly, we investigate the extracting of MSSTs using either support regions or extrema partitions. Given an image, both methods produce a binary tree that mathematically represents the topological structures of the image. The software described in this report is available through the EU-project, Deep Structure, Singularities, and Computer Vision.
1 Scales, Deep Structures, and Trees
The concept of scales is applied everywhere, explicitly otherwise implicitly. Images of the same scene might look completely different when measured at different scales. Without relevant prior knowledge, we do not know what scale is better than another and all scales are equally important. We have to take all of them into account resulting in multi-scale schemes. In this report, we use a simple mathematical frame-work for working with multi scales called the Gaussian scale-space[8, 21, 10].
In practice, the finest and the coarsest scales are limited by the inner scale- the resolution of the measurement device and the outer scale- the size of the image, respectively. Between the inner and the outer scale, critical points move, annihilate and possibly are created. The movements and interactions of these critical points at all scales are called the deep structure of the image. It incorporates the structure of an image at all possible scales.
The deep structure depends on the dimensionality of the image[10, 3]. Only annihilations of critical points occur in one-dimensional signal, while creations of critical points are also possible for images of higher dimensionality. For generic images\(^1\), only pair-wise creations and annihilations of critical points of opposite Hessian signatures\(^2\) can occur. These annihilations and creations are called catastrophe events and the points that they occur in scale-spaces are called catastrophe points. The merging of image structures, suggests a hierarchy which can be represented mathematically using trees [11]. We call such a tree a Multi-Scale Singularity Tree(MSST).
The long-term goal of our work is to use the extracted MSSTs as images descriptors. The approach is relatively new in computer-vision literatures. Using trees as image descriptors transforms the computer-vision problems into tree manipulation problems, which are well-studied mathematical problems. We expect that this approach will be useful in applications, such as image matching and recognition, image database indexing, image compression, etc.
2 Introduction to Gaussian Scale-Space
The $N^{+1}$ dimensional Gaussian scale-space $L : \mathbb{R}^{N+1} \rightarrow \mathbb{R}$ of an $N$ dimensional image $I : \mathbb{R}^{N} \rightarrow \mathbb{R}$ is an ordered stack of images, where each image is a blurred version of the former. The blurring is performed according to the diffusion equation,
$$\partial_t L = \nabla^2 L,$$
where $\partial_t L$ is the first partial-derivative of the image in the scale direction $t$, and $\nabla^2$ is the Laplace operator, which in 3 dimensions reads $\partial_x^2 + \partial_y^2 + \partial_z^2$.
\(^1\)Images whose structure is not perturbed by noise.
\(^2\)The sign of the determinant of the matrix of all second-order derivatives.
The Gaussian kernel is the Green’s function of the heat diffusion equation, i.e.
\[ L(\cdot; t) = I(\cdot) \otimes g(\cdot; t), \quad (2) \]
\[ g(x; t) = \frac{1}{(4\pi t)^{N/2}} e^{-x^T x / (4t)}, \quad (3) \]
where \( L(\cdot; t) \) is the image at scale \( t \), \( I(\cdot) \) is the original image, \( \otimes \) is the convolution operator, \( g(\cdot; t) \) is the Gaussian kernel at scale \( t \), \( N \) is the dimensionality of the problem, and \( t = \sigma^2 / 2 \), given \( \sigma \) being the standard deviation of the Gaussian kernel. The Gaussian scale-space is the only scale-space we will consider in this report, it will henceforth be called the scale-space.
Convolution in spatial domain is equivalent to multiplication in Fourier domain,
\[ I(\cdot) \otimes g(\cdot; t) = F^{-1} (F(I(\cdot))F(g(\cdot; t))), \quad (4) \]
with \( F \) as the Fourier transformation operator. Further, since differentiation commutes with convolution and the Gaussian kernel is infinitely differentiable, differentiation of scale-spaces is conveniently computed,
\[ \partial_x^n L(\cdot; t) = \partial_x^n (I(\cdot) \otimes g(\cdot; t)) = I(\cdot) \otimes \partial_x^n g(\cdot; t). \quad (5) \]
Alternative implementations of the scale-space are spatial convolutions, finite differencing schemes for the heat diffusion equation, additive operator splitting[20], and recursive implementation[4, 19]. The Fourier implementation is the most convenient for specifying derivative operators and it is precise and fast for coarse scales.
3 Computing the Deep Structure in Generic Scale-Space Images
Constructing a scale-space of an image adds a scale dimension, e.g. the scale-space of a two-dimensional image has dimensionality of three. We call such scale-space a \( 2^{+1}D \) scale-space. Similarly, constructing the scale-space of a three-dimensional image gives a \( 3^{+1}D \) scale-space. Although the dimensionality of the constructed scale-space depends on the dimensionality of the original image, critical points, namely maxima, minima and saddles, in the image at each scale are always points, and \textit{critical paths}, which are the paths of critical points when the scale is varied, are therefore also always curves embedded in the scale-space. The following sections describe a method used to extract critical paths, the scale-space saddles and the catastrophe points on them.
At each scale in a scale-space, points with vanishing spatial gradients are called \textit{critical points}. The type of a critical point is derived from the configuration of the eigenvalues of the Hessian matrix computed at that position. Critical points with all positive eigenvalues are minima, critical points with all negative eigenvalues are maxima, and critical points with a mixture of both negative and positive eigenvalues are saddles.
As we increase the scale parameter, the critical points move smoothly forming critical paths. At some scales, a pair of critical points with opposite Hessian signatures might meet and annihilate or be created. Such events are called catastrophe events, and the points where they occur are called catastrophe points. Generically\(^3\), there are only two types of generic catastrophe events in scale-space namely \textit{creation events} and \textit{annihilation events}. It is further known that these events only occur between pairs of critical points differing in the sign of one and only one eigenvalue of the Hessian matrix.
\(^3\)The notion of genericity is useful for regarding only the likely catastrophes, i.e. non-generic events disappear with small perturbations such as added random noise, while generic events do not.
3 COMPUTING THE DEEP STRUCTURE IN GENERIC SCALE-SPACE IMAGES
Figure 1: Critical paths in $2^{+1}D$ scale-spaces. The Marching Cubes algorithm implements choices incompatible with the scale-space structure. For this near non-generic event, when the sampling in the scale direction is not sufficiently high, the Marching Cubes algorithm produces the wrong result as shown in (a). The error is not easy to be detected. The correct solution produced by the method described in Section 3.1 is shown in (b).
3.1 Computing Critical Paths in $2^{+1}D$ Scale-space
For $2^{+1}D$ scale-space, the critical paths are found as the intersections between surfaces of vanishing derivatives in the two spatial directions, $x$ and $y$. Since the vanishing derivatives in a spatial direction are surfaces in the $2^{+1}D$ scale-space, the generic intersections are curves.
One algorithm to find the critical paths would be to calculate the surfaces of the two vanishing spatial derivatives, e.g. by using the Marching Cubes algorithm [14]. Quick to program, this is not optimal since the Marching Cubes algorithm is not tailored for the critical curves of scale-space as illustrated in Figure 1. The underlying image is a near symmetric case, where the Gaussian blobs have nearly the same intensity value at their maxima. Figure 1(a) shows the critical paths found by intersecting the surfaces produced by Marching Cubes, where it is seen that a non-generic event is suggested, where two maxima and a saddle is joined to one maximum. Figure 1(b) shows the correct structure produced by our method, where a maximum and a saddle is annihilated, and one maximum remains.
There is no need for explicit intersections between the surfaces of the two vanishing spatial derivatives. A faster, more robust, and scale-space compatible calculation of critical paths is found by linking the critical points across possibly interpolated scales. The $2^{+1}D$ image may be considered as a special kind of three-dimensional images, where the eight neighboring image points form a cube with image values on its eight vertexes. The whole scale-space is then a stack of cubes. For simplicity, we assume that there is no more than one critical path through each cube. The line segment of the critical path, which passes through a cube, is thus defined by a pair of end points on two of the cubes’ six faces, as shown in Figure 2.
Our algorithm is as follows: On each face of a cube we detect the zero crossing of the spatial derivatives along the four edges of the face using inverse linear interpolation. There will be only two such points found for each type of the derivatives. Linking the detected zero crossings of the same type together gives two...
A critical path passing through a cube is defined as the line segment between the two points entering and exiting the cube.
Our indexing of a cube for $2^{+1}D$ scale-spaces.
The faces are indexed as shown in the cube in Figure 3. This indexing is particularly simple, since it may be represented by a three-word binary encoding, each word for the offset on each axis, $x$, $y$ and $t$. The indexes for the four corners of the six faces are summarized in Table 1.
The extracted critical paths are now a collection of unconnected line segments. We then have to link them together forming linked critical paths. With the help of a vector of doubly linked lists, the line segments are easily joined together by comparing the positions of the two ends of a line segment with the positions of the two ends of each doubly linked list stored in the vector. If a connection is found, join the line segment with the corresponding end of the doubly linked list. If no connection can be found, add the line segment to a new doubly linked list and again to the vector as a possibly new critical path. When all line segments are stored in the vector of doubly linked list, we then have to compare the positions of the two ends of each doubly linked list with each others and join them together if possible.
In cases that there are more than one critical curve passing through a cube, we will find more than two
<table>
<thead>
<tr>
<th>Free Axes</th>
<th>Fixed Axis</th>
<th>Indexes</th>
</tr>
</thead>
<tbody>
<tr>
<td>$xy$</td>
<td>$t = 0$</td>
<td>0 2 4 6</td>
</tr>
<tr>
<td>$xy$</td>
<td>$t = 1$</td>
<td>1 3 5 7</td>
</tr>
<tr>
<td>$yt$</td>
<td>$x = 0$</td>
<td>0 1 2 3</td>
</tr>
<tr>
<td>$yt$</td>
<td>$x = 1$</td>
<td>4 5 6 7</td>
</tr>
<tr>
<td>$tx$</td>
<td>$y = 0$</td>
<td>0 4 1 5</td>
</tr>
<tr>
<td>$tx$</td>
<td>$y = 1$</td>
<td>2 6 3 7</td>
</tr>
</tbody>
</table>
Table 1: 3D Magic Table: Summary of the indexes for the six faces of a cube in $2^{+1}D$ scale-spaces.
intersection points on the six faces, possibly more than just one intersection point on each face. We then have to recursively subdivide the cube using tri-linear interpolation. The method is used to produce the critical paths in Figure 1(b). Each cube is sequentially examined, which give the computational complexity of $O(n^2)$, where $n$ is the number of cubes in the $2^{+1}D$ scale-space.
3.2 Computing Critical Paths in $3^{+1}D$ Scale-space
The problem gets much more complicated in $3^{+1}D$ scale-space because human intuition often fails for dimensionality beyond three. Thanks to the reduction of dimensionality discussed in in Section 3.1, we partition a four-dimensional problem into several manageable three-dimensional subproblems.
For a $3^{+1}D$ scale-space, the sixteen neighboring points in four-dimensional space form a four-hypercube. The reader is reminded that two neighboring rectangles in two dimension share a line segment, two neighboring cubes in three dimension share a square, and two neighboring four-hypercubes share a cube. Further, there are four line segments, six squares, and eight cube around the border of a rectangle, a cube, and a four-hypercube respectively.
Similarly to $2^{+1}D$ scale-spaces, the line segment of a critical path that goes through a particular four-hypercube is defined by two points located inside two of the eight border cubes. Intersecting three surfaces of vanishing spatial derivatives in $x$, $y$, and $z$ directions in each border cube give us such a point. For simplicity, let us assume again that there is only one critical path passing through the particular four-hypercube.
Our algorithm is thus as follows: Iteratively, two neighboring scales are calculated, together with their first spatial derivatives. For each of the eight border cubes of a four-hypercube, apply Marching Cube algorithm to extract the zero crossing surfaces of the three spatial first derivatives. Intersecting those three surfaces give a point, if exists. There will be only two such points detected inside two of the eight border cubes. Linking them together gives the line segment of the critical path passing through that four-hypercube.
In the cases that there are more than one critical path passing through the four-hypercube, there will be more than two intersection points detected in the eight border cube of that particular four-hypercube. The hyper-cube is then recursively sub-divided. The sub-dividing is not yet implemented.
As for $2^{+1}D$, we use the simple, binary numbering of the vertexes of a four-hypercube. The faces are indexed as shown in Figure 4. Table 2 summarizes the indexes of the eight vertexes for each cube at the border of a four-hypercube.
Again, the extracted line segments of the critical paths are still unconnected line segments. They have to be connected together with the help of a vector of doubly linked lists as describe in Section 3.1. Each
Table 2: 4D Magic Table: Summary of the indexes for the eight border cubes of a four-hypercube in $3^+1D$ scale-spaces.
four-hypercube is sequentially examined, which give the computational complexity of $O(n)$, where $n$ is the number of four-hypercubes in the $3^+1D$ scale-space. Figure 5 shows critical paths in a $3^+1D$ scale-space of a simple image with four light blobs.
3.3 Detecting Catastrophe Points and Scale-space Saddles on Critical Paths
Critical paths extracted using the method described in Section 3.1 and Section 3.2 are series of connected line segments, which can be traced from one end to the other end. Catastrophe points are the points where two critical points with opposite Hessian signature annihilate or be created. Therefore, the determinant of the Hessian matrix vanishes at catastrophe points. Moreover, locally, the created or annihilating critical points always move perpendicular to the scale direction at catastrophe points.
Considering a parametric representation of an extracted critical path, embedded in an $N^+1D$ scale-space, parameterized with $s \in [0,L]$ where $L$ is the length of the critical path, $S(s)$ specifies the scale and $I(s)$ specified the image intensity at $s$ along the critical path, catastrophe points are then can be detected easily as the points on critical paths where the derivative of $S(s)$ changes its sign, $\frac{d}{ds}S(s) = 0$.
The current implementation assumes that there is no creation event, which implies that there is at maximum one catastrophe point per critical path, and it can be detected as a point on each critical path with highest scale-value. This simplification is not a major issue for our implementation.
Scale-space saddles are defined as points in scale-space with vanishing partial derivatives in both spatial and scale directions. They are indeed critical points with vanishing partial derivative in scale direction. They can be detected as points on critical paths where the derivative of the image intensity $I(s)$ changes its sign, $\frac{d}{ds}I(s) = 0$. The detection of scale-space saddles is not yet implemented.
Figure 5 shows the critical paths in a $3^+1D$ scale-space of a simple 3D image, where the scale axis is projected away. Four snap-shots are shown for four different scales in order to illustrate the forth dimension.
4 3D Multi-Scale Singularity Trees
A few methods of constructing tree structures from the deep structure of 2D images have been proposed in the literatures so far. In [12], the iso-photons of the intensity levels at the annihilation points are used to partition an image into regions called extremal regions. The nesting relations of extremal regions associated with extrema are then use to construct tree. Scale-space saddles are first introduced in [11], where the iso-surfaces kissing at these points provide a scale-space hierarchy which may be used to nest extrema in a tree.
Figure 5: Critical Paths in a $3^{+1} D$ scale-space. Four different scales are shown: $\sigma = 3.00$, $\sigma = 4.17$, $\sigma = 5.80$, and $\sigma = 8.07$ in (a), (b), (c), and (d) respectively. The Blue surfaces are the 2.0 iso-surfaces, the blue lines are the critical paths, the small black spheres are the catastrophe points, the small red and blue spheres show the maxima and the saddles respectively.
We propose two methods of constructing MSSTs. Both methods are purely coarse-to-fine methods. After the extraction of the critical paths and the catastrophe points, the methods only require the calculations of the images at the after-annihilation scales to construct the trees. Although, the methods are capable of extracting MSSTs of scale-spaces of any dimensionality, we will focus on $3^{+1}D$ scale-spaces. With the help of our new tree building scheme, both methods always produce ordered binary trees with catastrophe points as nodes, which are preferable and convenient to be subsequently processed in applications. In 3D some catastrophes are caused by creation or annihilation of saddle-saddle points. This correspond to the catastrophic interaction between a thinning and a thickening of a tube, and we have decided to ignore these catastrophes.
The first method is an extension to $3^{+1}D$ scale-spaces of the method described in [16] based on support regions[13] together with our new tree building scheme. The second method is a new method based on extrema partitions. It is inspired by the edge modeling method called The Extrema Edges described in [1].
4.1 MSSTs based on Support Volumes
In 2D, the border of a support region is given as the iso-phote passing through the first saddle encountered when the value of the isophote is decreased or increased from the maximum or the minimum respectively. The support regions are then never overlapped each others and each of them also contains one and only one extremum inside.
In 3D, support regions become support volumes. They are the volume enclosed by iso-surface passing through saddle or possibly saddles that contains only a single extremum inside. The support volumes then can be used to partition images into segments, where each segment contains exactly one extremum inside. Figure 8 shows the support volumes of the four extrema of the image in Fig 5 at scale $\sigma = 3$.
Using the catastrophe points as nodes, the parent-child relations between nodes are derived from the locations of the annihilation points and the support volumes in the images of after-annihilation scales. Moving down from the highest catastrophe in scale, when a new extremum $E_c$ is emerged inside the support volume of an extrema $E_p$ calculated at the after-annihilation scale, the new extremum $E_c$ is considered as a child of the extremum $E_p$. The MSST is constructed as follows.
Firstly, denote the extrema together with their corresponding critical paths as $E_i$ and the catastrophes on the paths as $C_i$ for $i \in \{1 \ldots n\}$ ordered such that the scale of a catastrophe $C_i$ is higher than $C_j$ when
Deep Structure
Figure 7: A complex deep structure together with its MSST. The labels 'C' denote a catastrophe point, 'M' denotes a maximum, and 'S' denotes a saddle.
For $i < j$, discard the critical paths of saddle-saddle annihilations. Finally, by $E_0$ denote the critical path of an extremum that remains until infinite scale.
Each node in the tree has two ports namely the left- and the right-port, which can be used to connect the left-child and the right-child respectively. A node $C_j$, which has its left-port tagged as $E_m$ can be connected as the left-child or the right-child of a node $C_i$ if and only if the left- or the right-port of $C_i$ is also tagged as $E_m$ and free. Finally, The right-port of node $C_i$ is always set to $E_i$.
The algorithm starts from the highest to the lowest catastrophe in scale. Now, initiate the MSST by:
1. Set $C_1$ as the root.
2. Tag the left- and the right-port as $E_0$ and $E_1$ respectively, and mark them as free.
Then for $i = 2 \ldots n$ repeat the following steps:
3. Calculate the support volume of all extrema at the after-annihilation scale with respect to $C_i$.
4. Denote $E_j$ to be the extremum whose support volume either contains $C_i$ or is closest to $C_i$. Tag the left-port of $C_i$ as $E_j$, tag the right-port of $C_i$ as $E_i$, and mark both as free.
5. Link $C_i$ to a previous node $C_k$, which has a free left- or right-port tagged as $E_j$, as the corresponding left- or right-child, and mark the taken port in $C_k$ as occupied.
In the end, all the critical paths in the image except for those paths that correspond to the saddle-saddle annihilation are included in the constructed tree. The resulting trees corresponding to the deep structures are shown in Figures 6 and 7.
We note that the above linking, for catastrophes not enclosed by any support volume ensures that the resulting structure will be a binary tree, and preserves the coarse to fine nature of the multi-scale singularity-tree. Neither properties are observed by linking these catastrophes to the root as suggested in [16].
Figure 9 shows an extracted MSST of the image in Fig 5. Note that one of the catastrophes is a saddle-saddle annihilation, and this is not included in the tree.
Creations are generic events in $2D$ and $3D$ scale-spaces. The current implementation ignores creations. However, the annihilations following creations are handled as a regular annihilation according to...
Figure 8: Support volumes in a $3^{+1} D$ scale-space. The support volumes are calculated at scale $\sigma = 3$. Blue surfaces are the 2.0 iso-surfaces. The green surfaces show the borders of the support volumes associated with the enclosed extrema $E_0$, $E_1$, $E_2$, and $E_3$ in (a), (b), (c), and (d), respectively.
Figure 9: The MSST of image in Fig. 5 based on support volumes. The blue iso-surface of the image at scale $\sigma = 3$ is shown together with the critical paths, critical points and the extracted MSST in (a), where the scale axis is projected away. The small red and blue spheres are the maxima and saddles points respectively. The blue lines are the critical path, the small black spheres are the catastrophe points. The black line and the red line denote the left-child linking and the right-child linking in the tree. The same deep structure and its MSST are shown in (b), where the $z$ axis is projected away.
Figure 10: Creations are included by their annihilations only.
the algorithm above, see Figure 10 for details. Implication of indicated algorithm implies not all extrema can be traced to zero scale, i.e. dangling ‘leaves’.
While a support volume nicely defines a region belonging to a single extremum, its separation does not necessarily reflect the local image structures. Moreover, there are parts of the image that do not belong to any support volume defined. These undefined parts of the image introduce ambiguities in the linking. The next section describes a new method of constructing MSSTs based on extrema partitions. Extrema partitions separate an image into meaningful regions associated with a single extremum and define all parts of the image totally.
4.2 MSSTs based on Extrema Partitions
Let $\Omega \subset \mathbb{R}^3$ be a compact connected domain and define $I : \Omega \to \mathbb{R}$ to be an image, $s \in \Omega$ as an extremum, and $x \in \Omega$ as a point. Consider the set of continuous functions $\gamma : [0, L] \to \Omega$ for which $\gamma(0) = s$, $\gamma(L) = x$, and $\gamma \in \Gamma_{sx}$, where $\Gamma_{sx}$ is the set of all possible paths from an extremum $s$ to a point $x$. The energy $E_s(x)$ with respect to an extremum $s$ calculated at $x$ is defined as
$$E_s(x) = \inf_{\gamma \in \Gamma_{sx}} \int_0^L \frac{d}{dt} I(\gamma(t))|dt. \quad (6)$$
Let $S \subset \Omega$ be a set of all extrema in the image. The extrema partition, $Z_i$, associated with an extremum $i \in S$ is defined as a set of all points in the images, where the energy $E_i(x)$ is minimal,
$$Z_i = \{x \in \Omega | E_i(x) < E_j(x), \forall j \in S\}. \quad (7)$$
The energy map $M_i : \Omega \to \mathbb{R}^+$, which defines the energy at every point in the image associated with an extremum $i$, can be efficiently calculated using the Fast Marching Methods [17]. Figure 11 shows the extrema partitions of the four extrema of the image in Fig 5 calculated at scale $\sigma = 3$.
Unlike the support volumes used in the Section 4.1, which divides an image into segments using only global information by means of iso-surface, the extrema partitions divide the image into segments using both the local information derived from the derivative of the image intensity and the global information derived from the minimal path originated from the extrema. The extrema partitions and their borders include the whole image. Moreover their borders define meaningful separations, because they coincide with parts of the image, where the derivative of the intensity is high.
Using the notations of critical paths, extrema, and catastrophe points defined in the Section 4.1, the proposed algorithm starts from the highest to the lowest catastrophe in scale with the initialization of the root by:
1. Set $C_1$ as the root.
2. Tag the left- and the right-port as $E_0$ and $E_1$ respectively, and mark them as free.
Then for $i = 2 \ldots n$ repeat the following steps:
3. Calculate the energy map $M_j$ of all extrema at the after-annihilation scale with respect to $C_i$.
4. Denote $E_j$ to be the extremum whose the value of the energy map $M_j$ evaluated at $C_i$ is minimum among all calculated energy map. Tag the left-port of $C_i$ as $E_{j_l}$, tag the right-port of $C_i$ as $E_{j_r}$, and mark both as free.
5. Link $C_i$ to a previous node $C_k$, which has a free left- or right-port tagged as $E_{jk}$, as the corresponding left- or right-child, and mark the taken port in $C_k$ as occupied.
In the end, all the critical paths in the image, except for those paths that correspond to the saddle-saddle annihilation, are included in the constructed tree. The resulting MSST of the image in Fig. 5 extracted using the method based on extrema partition is shown in Figures 12.
5 Implementation
The software is written in the C/C++ programming language[18] using the GNU g++ compiler[7] and the KDevelop developing tool [9] under the GNU/Linux operating system (Redhat 9.0). The code is documented using Doxygen[5], please see Appendix A for information about the documentation. OpenGL[22] is used to visualizing the scale-spaces, detected critical points, computed critical paths, catastrophe points, as well as the extracted MSSTs. The code is published using CVS[2] on dsscv@bellis.lab3d.odont.ku.dk under the project DSSCV, and can be obtained using Secure Shell[15] with proper access rights. Please contact the authors for information about obtaining the code and its documentation.
The software constructs scale-spaces using the Fourier implementation. Since we focus mainly on applications of medical images, we assume that all images are surrounded by a zero background. Hence prior to the transformation, images are padded with a band of zeroes that is $4\sigma$ wide. We use a highly optimized Fourier transform implementation called Fastest Fourier Transform In the West(FFTW)[6], which also supports machines equipped with multi processors.
The following point list contains known limitations and possible improvements to our implementation:
- A more sophisticated command line parser will provide more flexibility and allow user to supply a series of commands written in a script file. The use of Graphical user interface will be kept at minimum.
- The implementation of the scale-space saddle detection as described in Section 3.3 will provide more visual information of the extracted critical paths.
- The support volume is computed using recursive implementation which limits the size of the images to be processed.
- Several optimizations could be applied in order to reduce the computational time in the calculation of the energy maps. For example, the calculation may be stopped as soon as the values of the required points are certain.
5.1 Mini-tutorial
The software is a single binary file, which can be started from a shell prompt with the command:
```bash
./ext3dmsst.
```
At start a new graphic window is opened, and release information is printed on the console. The user-interface of the software is a text-mode output console together with an input-output graphic window. The graphic window is used to draw lines, points, and surfaces in three-dimensional space. By default, the positive $x$-, $y$-, and $z$-axis are pointing to the right of the user, into the screen, and to the top of the screen respectively. Note that the program only takes input via the graphic window, therefore the graphic window has to be activated when the user wishes to supply input.
An image, supplied with the software located at `./images/data20-4.txt`, will be used in the tutorial. It is the image that is used to produce images in Figure 5. The file format is very simple. It is a text file starting with three numbers specifying the dimensions of the image followed by data separated with spaces. The images are restricted to having sizes $x \times y \times z$, were $x$, $y$, and $z$ are even numbers.
Figure 11: Extrema partitions in a $3^{+1}D$ scale-space. The extrema partitions are calculated at scale $\sigma = 3$. Blue surfaces are the 2.0 iso-surfaces. The green surfaces show the borders of the extrema partitions associated with the enclosed extrema $E0$, $E1$, $E2$, and $E3$ in (a), (b), (c), and (d), respectively.
Figure 12: The MSST of the image in Fig. 5 based on extrema partitions. The 2.0 iso-surface of the image at scale $\sigma = 3$ is shown in blue in (a), where the scale axis is projected away. The small red and blue spheres are the maxima and saddles points respectively. The blue lines are the critical path, the small black spheres are the catastrophe points. The black line and the red line denote the left-child linking and the right-child linking in the tree. The same critical paths and catastrophe points are shown in (b), where the $z$ axis is projected away.
To open an image, use the command key “R”, and specify the path and the filename relatively to the current directory. For the example image type the command as follows.
> R
Filename [string] :./images/data20-3.txt
For the complete list of the commands, press “?” Table 3 summarizes the command keys and their definitions. After having loaded an image into the memory, activate the detection of critical points with the command “C”. The graphic window can be forced to redraw with the command “Ctrl+l”. The graphic window should be showing the critical points in the image. Red, green, and blue spheres denote maxima, minima, and saddles respectively.
Use the command keys “+” and “-” to go from the current scale to the next and previous scale. Observe the movements of the critical points, some critical points might meet and annihilate. The standard deviation $\sigma$ of the Gaussian kernel for scale $T$ is calculated as follows.
$$
\sigma = \sigma_0 e^T.
$$
The $\sigma_0$, as well as the scale step $dT$ can be changed with command “s” and “d” respectively. The default values are $\sigma_0 = 3$ and $dT = 0.05$. Jumping to any scale is made possible with the command “t” followed by the value of $T$.
For a better insight of the image structure and its changes with respect to scales, activate the iso-surface extraction using the command “C”, and set the value of the iso-surface with command “i”. The value of 2.0 is recommended for the example image. Number keys “4”, “6”, “8” and “2” can be used to rotate the view point. Navigate the view point around to see the image from different positions. Press “5” to move back to the default view point.
To extract the critical paths press “Ctrl+e” and give the number of scales to be calculated between $T = 0$ and $T = dT * (N - 1)$. The value of 20 is suggested for the given images. When finished, press “Ctrl-l” to redraw the image. The critical path together with the catastrophe points and the critical points at current scale should be drawn on the graphic window. Press “!” to toggle between $xyz$, $xyt$, $xtz$ and $tzx$ coordinate systems.
Extracting MSSTs is totally automatic. To extract the MSST using the method based on support volume, press “Ctrl+s”. The software will print internal calculation details and finally draw the extracted tree on the graphic window. Extracting the MSST based on extrema partitions is done using the command “Ctrl+t”. Finally, the extracted MSST can be exported using the command “W”, followed by the relative path and the filename.
6 Conclusion
Scale-spaces of three-dimensional images are necessarily huge, e.g. 32 levels of a $256^3$ image in 64 bits precision (C double) requires 4 Gigabytes of memory. Further, in order to compute the multi-scale singularity-tree, we need to examine the first and second order derivatives, which results in the total need of 40 Gigabytes of memory in this example. Needless to say, today there are only few computers that can handle such large amounts of memory within reasonable time. Luckily, we do not need to store the full scale-space simultaneously, our implementation sequentially examines two neighboring scales at a time, reducing the memory requirement by a factor of 16 in the above example. The memory can be further reduced for the exchange of processor speed, but such a compromise has not yet been needed, since we have chosen to work with smaller images.
The current implementation ignores two generic events: creations and annihilations of saddle pairs in $3^{+1}D$ scale-spaces. Creations are ignored since their inclusion would result in graphs instead of binary
<table>
<thead>
<tr>
<th>Command Key</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td>?</td>
<td>Help</td>
</tr>
<tr>
<td>1</td>
<td>List the Parameters</td>
</tr>
<tr>
<td>8,4,6,2</td>
<td>Change the View Point</td>
</tr>
<tr>
<td>5</td>
<td>Reset the View Point</td>
</tr>
<tr>
<td>Ctrl+l</td>
<td>Redraw the Graphic Window</td>
</tr>
<tr>
<td>Ctrl+x</td>
<td>Cancel Input</td>
</tr>
<tr>
<td>ESC</td>
<td>Exit</td>
</tr>
<tr>
<td>R</td>
<td>Read an Image</td>
</tr>
<tr>
<td>W</td>
<td>Export the extracted MSST</td>
</tr>
<tr>
<td>i</td>
<td>Set the Iso-Surface Value</td>
</tr>
<tr>
<td>S</td>
<td>Toggle the Iso-Surfaces</td>
</tr>
<tr>
<td>X</td>
<td>Toggle the $\partial_x I = 0$ Surfaces</td>
</tr>
<tr>
<td>Y</td>
<td>Toggle the $\partial_y I = 0$ Surfaces</td>
</tr>
<tr>
<td>Z</td>
<td>Toggle the $\partial_z I = 0$ Surfaces</td>
</tr>
<tr>
<td>A</td>
<td>Toggle the Support Volume/Extremal Partition Surfaces</td>
</tr>
<tr>
<td>s</td>
<td>Set the $\sigma_0$</td>
</tr>
<tr>
<td>t</td>
<td>Set the $T$</td>
</tr>
<tr>
<td>d</td>
<td>Set the $dT$</td>
</tr>
<tr>
<td>C</td>
<td>Toggle the Critical Point Detection</td>
</tr>
<tr>
<td>c</td>
<td>List the Extracted Critical Points</td>
</tr>
<tr>
<td>v</td>
<td>Get the Value of a Point</td>
</tr>
<tr>
<td>+</td>
<td>Increase the $T$</td>
</tr>
<tr>
<td>-</td>
<td>Decrease the $T$</td>
</tr>
<tr>
<td>Ctrl+e</td>
<td>Extract the Critical Paths</td>
</tr>
<tr>
<td>x</td>
<td>List the Catastrophe Points</td>
</tr>
<tr>
<td>!</td>
<td>Toggle the Coordinate Systems</td>
</tr>
<tr>
<td>Ctrl+v</td>
<td>Calculate the Support Volume</td>
</tr>
<tr>
<td>Ctrl+p</td>
<td>Calculate the Extrema Partition</td>
</tr>
<tr>
<td>Ctrl+t</td>
<td>Extract the MSST based on Extrema Partitions</td>
</tr>
<tr>
<td>Ctrl+s</td>
<td>Extract the MSST based on Support Volumes</td>
</tr>
</tbody>
</table>
Table 3: Summary of the important command keys and their definitions.
trees, and it is expected that binary trees are especially simple as object representations. The saddle pair
annihilation events likewise poses problems for our algorithm, since we only use extrema to define image
segments. It is our expectation that these events do not represent important medical image structures.
On a computer with double Intel Xeon 2.4GHz with 4 Gigabytes Ram the current implementation con-
structs a $3^1 D$ scale-space with 20 scales sampled exponentially from $\sigma = 3$ to $\sigma = 7.75$ and extracts the
critical paths and catastrophe points of a $20^3$ image with four extremum and four catastrophe points in 25
seconds. With the extracted critical paths and catastrophe points, an MSST based on support volumes and
an MSST based on extrema partitions can be constructed within four seconds and 15 seconds, respectively.
7 Acknowledgment
We would like to thank Frans Kanters and the Biomedical Image Analysis group at the Department of
Biomedical Engineering, Technical University of Eindhoven for allowing Kerawit Somchaipeng to visit and
share in fruitful discussions.
A Sourcecode documentation by Doxygen
The documentation is generated using the documentation system called Doxygen[5]. The program is ex-
pected to be continually edited to improve the performance and to add more functionalities. In order to keep
the documentation of the implementation code up to date, we decided not to include the documentation as
an appendix of this report but rather as a separated report of its own and delivered as a part of the source code
package.
References
REFERENCES
|
{"Source-Url": "https://static-curis.ku.dk/portal/files/122546718/deliverable8.pdf", "len_cl100k_base": 9580, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 47371, "total-output-tokens": 11315, "length": "2e13", "weborganizer": {"__label__adult": 0.00036716461181640625, "__label__art_design": 0.001514434814453125, "__label__crime_law": 0.000476837158203125, "__label__education_jobs": 0.0010118484497070312, "__label__entertainment": 0.00015747547149658203, "__label__fashion_beauty": 0.0002624988555908203, "__label__finance_business": 0.0003390312194824219, "__label__food_dining": 0.0004725456237792969, "__label__games": 0.0007834434509277344, "__label__hardware": 0.0020904541015625, "__label__health": 0.001262664794921875, "__label__history": 0.0005750656127929688, "__label__home_hobbies": 0.0001786947250366211, "__label__industrial": 0.0007781982421875, "__label__literature": 0.00032782554626464844, "__label__politics": 0.00033974647521972656, "__label__religion": 0.0007371902465820312, "__label__science_tech": 0.439208984375, "__label__social_life": 0.00014734268188476562, "__label__software": 0.0300750732421875, "__label__software_dev": 0.517578125, "__label__sports_fitness": 0.00037789344787597656, "__label__transportation": 0.0004940032958984375, "__label__travel": 0.00027441978454589844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42552, 0.0277]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42552, 0.67172]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42552, 0.88999]], "google_gemma-3-12b-it_contains_pii": [[0, 328, false], [328, 645, null], [645, 4271, null], [4271, 7952, null], [7952, 10677, null], [10677, 12480, null], [12480, 15422, null], [15422, 18346, null], [18346, 18756, null], [18756, 21434, null], [21434, 23891, null], [23891, 24212, null], [24212, 24891, null], [24891, 28349, null], [28349, 31778, null], [31778, 32104, null], [32104, 32671, null], [32671, 36302, null], [36302, 37763, null], [37763, 39345, null], [39345, 41653, null], [41653, 42552, null]], "google_gemma-3-12b-it_is_public_document": [[0, 328, true], [328, 645, null], [645, 4271, null], [4271, 7952, null], [7952, 10677, null], [10677, 12480, null], [12480, 15422, null], [15422, 18346, null], [18346, 18756, null], [18756, 21434, null], [21434, 23891, null], [23891, 24212, null], [24212, 24891, null], [24891, 28349, null], [28349, 31778, null], [31778, 32104, null], [32104, 32671, null], [32671, 36302, null], [36302, 37763, null], [37763, 39345, null], [39345, 41653, null], [41653, 42552, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42552, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42552, null]], "pdf_page_numbers": [[0, 328, 1], [328, 645, 2], [645, 4271, 3], [4271, 7952, 4], [7952, 10677, 5], [10677, 12480, 6], [12480, 15422, 7], [15422, 18346, 8], [18346, 18756, 9], [18756, 21434, 10], [21434, 23891, 11], [23891, 24212, 12], [24212, 24891, 13], [24891, 28349, 14], [28349, 31778, 15], [31778, 32104, 16], [32104, 32671, 17], [32671, 36302, 18], [36302, 37763, 19], [37763, 39345, 20], [39345, 41653, 21], [41653, 42552, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42552, 0.17167]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
91b7640281d9da1e5e50f14c3ead47b914c9103e
|
Abstract
We present a simple and provably optimal non-adaptive cell probe data structure for the static dictionary problem. Our data structure supports storing a set of $n$ key-value pairs from $[u] \times [u]$ using $s$ words of space and answering key lookup queries in $t = O(\lg(u/n)/\lg(s/n))$ non-adaptive probes. This generalizes a solution to the membership problem (i.e., where no values are associated with keys) due to Buhrman et al. and matches a recent lower bound by Persiano and Yeo.
Using the ideas underlying our data structure, we also obtain the first implementation of a $n$-wise independent family of hash functions with optimal evaluation time in the cell probe model.
1 Introduction
The static membership problem is arguably the simplest and most fundamental data structure problem. In this problem, the input is a set \( S \) of \( n \) integer keys \( x_1, \ldots, x_n \in [u] = \{0, \ldots, u - 1\} \) and the goal is to store them in a data structure, such that given a query key \( x \in [u] \), the data structure supports reporting whether \( x \in S \).
The classic solution to the membership problem is to use hashing. The textbook hashing-based solution is hashing with chaining, where one draws a random hash function \( h : [u] \to [m] \) and creates an array \( A \) with \( m = O(n) \) entries. Each entry \( A[i] \) of the array stores a linked list of all keys \( x \in S \) such that \( h(x) = i \). To answer a membership query for \( x \), we compute \( h(x) \) and scan the linked list in entry \( A[h(x)] \). If \( h \) is drawn from a universal family of hash functions, the time to answer queries is \( O(1) \) in expectation.
The expected query time can be made worst case \( O(1) \) using e.g. perfect hashing [FKS84] or (static) Cuckoo hashing [Pag01, PR01]. In the latter solution, we store two arrays \( A_1 \) and \( A_2 \) of size \( O(n) \) each. These arrays merely store keys in their entries, not linked lists or other data structures. We then draw two hash functions \( h_1 \) and \( h_2 \) and guarantee that each key \( x \in S \) is stored in either \( A_1[h_1(x)] \) or \( A_2[h_2(x)] \). It thus suffices with two lookups to determine if \( x \in S \).
All of the above solutions may also be easily extended to solve the dictionary problem in which the data to be stored is a set of \( n \) key-value pairs \( \{(x_i, y_i)\}_{i=1}^n \). Upon a query \( x \), the data structure must return the value \( y_i \) such that \( x_i = x \), or report that no such pair exists.
1.1 Adaptivity and Membership
A common feature of all the hashing based solutions to the membership and dictionary problem, is that they are adaptive. That is, the memory locations they access depend heavily on the random choice of hash functions. Persiano and Yeo [PY20] recently showed that such adaptivity is crucial to obtain constant query time. More concretely, they studied the membership problem in the cell probe model (see below) and proved super-constant lower bounds for non-adaptive data structures. A non-adaptive data structure is one in which the memory cells to access on a query \( x \) is completely determined from \( x \). Such non-adaptive data structures thus allow retrieving all necessary memory cells in parallel when answering a query. Cuckoo hashing, and other hashing based data structures, are adaptive as they require first reading the random seeds of hash functions and only thereafter can determine which remaining memory cells to access. It is quite remarkable that this one round of adaptivity is enough to reduce the query time from super-constant to constant.
The Cell Probe Model. The cell probe model by Yao [Yao81] is the de-facto model for proving data structure lower bounds. In this model, a data structure consists of a memory of \( s \) cells with integer addresses 0, \ldots, \( s - 1 \), each storing \( w \) bits. Computation is free of charge in this model and only the number of memory cells accessed/probed when answering a query counts towards the query time. A lower bound in the cell probe model thus applies to any data structure implementable in the classic word-RAM upper bound model.
Non-Adaptive Membership. Buhrman, Miltersen, Radhakrishnan and Venkatesh [BMRV02] showed that it is possible to store a data structure of size \( O(n \lg u) \) bits such that membership queries can be answered in \( O(\lg u) \) non-adaptive bit probes (i.e. the cell probe model with \( w = 1 \)). This of course implies a membership data structure with \( O(\lg u) \) probes in the cell probe model,
but it is not clear how to extend it to solve the dictionary problem with the same time and space complexity. Furthermore, the data structure by Buhrman et al. is non-explicit in the sense that they give a randomized argument showing existence of an efficient data structure. Buhrman et al. also show a lower bound of \( t = \Omega(\frac{\log(u/n)}{\log(s/n)}) \) bit probes. In the setting where \( n \) is polynomially smaller than \( u \) and \( s = O(n) \), this matches the upper bound up to constant factors.
The bit probe lower bound result was strengthened to a cell probe lower bound by Persiano and Yeo [PY20] (without citing [BMRV02]), where a membership query must again probe \( t = \Omega(\frac{\log(u/n)}{\log(s/n)}) \) cells to answer membership queries in the natural setting where \( w = \Theta(\log u) \). Persiano and Yeo also cite Brody et al. [BL15] for obtaining a matching upper bound. However, this is not quite true. Brody et al. [BL15] present a dynamic non-adaptive data structure for the predecessor search problem, allowing insertions and deletions of keys while supporting predecessor queries in \( O(\log u) \) probes. A predecessor query for a key \( x \) must return the largest \( x' \in S \) such that \( x' \leq x \). Such a data structure clearly also supports membership queries. However, their data structure critically uses \( s = \Theta(2^w) = \Theta(u) \) memory (cells of arbitrary addresses in \( 0, \ldots, 2^w \) are updated). This may be far more than linear in \( n \) for natural settings of parameters. Also, the lower bound \( t = \Omega(\frac{\log(u/n)}{\log(s/n)}) \) degenerates to constant when \( s = \Theta(u) \). Indeed, if memory cells of addresses \( 0, \ldots, u-1 \) may be used, a simple bit-vector with constant time operations suffices for the static membership problem. Brody et al. [BL15] however prove that for dynamic data structures for predecessor search, this query time is optimal even with \( \Theta(u) \) space.
For the static membership (and dictionary) problem, the best known non-adaptive solution is due to Berger et al. [BHP+06] who construct a (dynamic) dictionary with query time \( t = O(\log u) \) and space \( s = O(n \log n) \). Their solution is aimed at the I/O model, i.e., a single memory access can retrieve \( B \geq 1 \) keys or values. In the Word RAM model this corresponds to having word size \( B \log u \). Their strongest results for the dictionary problem requires word size \( \Omega(\log(n) \log(u)) \), while our results hold for word size \( \log u \).
This still leaves open the problem of obtaining an optimal static and non-adaptive membership data structure, in both the word-RAM model, and in the cell probe model.
**Our Contribution.** In this work, we present a simple and optimal non-adaptive cell probe data structure for the dictionary and membership problem:
**Theorem 1.** For any \( s = \Omega(n) \), there is a non-adaptive static cell probe data structure for the dictionary problem, storing \( n \) key-value pairs \( (x_i, y_i) \in [u] \times [u] \) using \( s \) memory cells of \( w = \Theta(\log u) \) bits and answering queries in \( t = O(\frac{\log(u/n)}{\log(s/n)}) \) probes.
This matches the lower bound by Persiano and Yeo [PY20]. As stated in the theorem, our data structure is implemented in the cell probe model, meaning that we treat computation as free of charge. Implementing the data structure in the more standard upper bound model, the word-RAM, would require the construction of a certain type of explicit bipartite expander graph.
The expansion property we require is much weaker than what is typically studied in the expander graph literature and also than what is required from Berger et al. ‘s solution. Namely, we only require the existence of \( t \)-left-regular bipartite graphs with expansion factor one; however our bipartite graph is highly imbalanced. Our expansion property corresponds to an imbalanced disperser, and therefore is well-studied and has other applications (e.g., [GUV09]). Such dispersers exist by a counting argument, but it remains an open problem to obtain explicit constructions.
1.2 Hash Functions with High Independence
When using hash functions in the design of data structures and algorithms, it is often assumed for simplicity of analysis that truly random hash functions are available. Such a hash function $h : [u] \rightarrow [m]$ maps each key independently to a uniform random value in $[m]$. Or said differently, when drawing the random hash function $h$, we choose a uniform random function in the family of hash functions $\mathcal{H}$ consisting of all (deterministic) functions from $[u]$ to $[m]$. Implementing such a hash function in practice is often infeasible as it requires $u \lg m$ random bits and thus the storage requirement may completely dominate that of any data structure making use of the hash function.
Fortunately, much weaker hash functions suffice in many applications. The simplest property of a family of hash functions $\mathcal{H} \subseteq [u] \rightarrow [m]$, is that it is universal [CW77]. A universal family of hash functions has the property that for a uniform random $h \in \mathcal{H}$, it holds for every pair of keys $x \neq y \in [u]$ that $\Pr[h(x) = h(y)] \leq 1/m$. Universal hashing for instance suffices for implementing hashing with chaining with expected constant time membership queries, but is not sufficient for implementing Cuckoo hashing [CK09]. The next step up from universal hashing is the notion of $n$-wise independent hashing. A family of hash functions $\mathcal{H}$ is $n$-wise independent if, for $h$ drawn uniformly from $\mathcal{H}$, it holds for any set of $k$ distinct keys $x_1, \ldots, x_n$ that $h(x_1), \ldots, h(x_n)$ are independent and uniformly random (or nearly uniformly random). The prototypical example of an $n$-wise independent family of hash function (with nearly uniform hash values) is
$$\mathcal{H} := \left\{ h_{\alpha_0, \ldots, \alpha_{n-1}}(x) = \left( \sum_{i=0}^{n-1} \alpha_i x^i \right) \mod m \mod m \mid \alpha_0, \ldots, \alpha_{n-1} \in [p] \right\}$$
where $p$ is any prime greater than or equal to $u$. That is, to draw a hash function $h$ from $\mathcal{H}$, we sample $\alpha_0, \ldots, \alpha_{n-1}$ uniformly and independently in $[p]$ and let $h(x)$ be the evaluation of the polynomial $\left( \sum_{i=0}^{n-1} \alpha_i x^i \right) \mod p$ mod $m$\(^1\). Clearly, the evaluation time of this hash function is $\Theta(n)$. Whether it is possible to implement $n$-wise independent hash functions with faster evaluation time has been the focus of much research. On the lower bound side, Siegel [Sie89] proved that any implementation of an $n$-wise independent hash function $h : [u] \rightarrow [m]$ using $s$ memory cells of $w = \Theta(\lg u)$ bits, must probe at least $t = \Omega(\min\{\lg(u/n)/\lg(s/n), n\})$ memory cells to evaluate $h$. The hash function above matches the second term in the minimum. For the first term, the result that comes closest is a recursive form of tabulation hashing by Christiani et al. [CPT15] that gives an $n$-wise independent family of hash functions that can be implemented using $s = O(nu^{1/c})$ space and evaluation time $t = O(c \lg c)$ for any $c = O(\lg(u)/\lg n)$. Rewriting the space bound gives $c = \lg u/\lg(s/n)$ and thus $t = O(\lg(u) \lg(\lg(u)/\lg(s/n))/\lg(s/n))$. This is about a $\lg \lg u$ factor away from the lower bound of Siegel in terms of the query time $t$. This algorithm is adaptive and requires $s \geq n^{1+\Omega(1)}$ as they need $\lg u/\lg(s/n) = O(\lg(u)/\lg n)$.
Our Contribution. Designing an optimal $n$-wise independent family of hash functions thus remains open, with or without adaptivity. In this work, we show how to implement such a function in the cell probe model (where computation is free):
**Theorem 2.** For any $s = \Omega(n)$ and $p = \Omega(u)$, there is a non-adaptive static cell probe data structure for storing an $n$-wise independent hash function $h : [u] \rightarrow \mathbb{F}_p$ using $s$ memory cells of $w = \Theta(\lg p)$ bits and answering evaluation queries in $t = O(\lg(u/n)/\lg(s/n))$ probes.
\(^1\)Technically, this hash function is only approximately $n$-wise independent, in the sense that the hash values of any $n$ keys are independent, but only approximately uniform random.
We remark that Siegel’s lower bound is valid in the cell probe model, and thus our data structure is optimal. Furthermore, Siegel’s lower bound holds also for adaptive data structures, whereas ours is even non-adaptive. Compared to the work of Christiani et al., we have a faster evaluation time and only require \( s = \Omega(n) \). The downside is of course that our solution is only implemented in the cell probe model. Implementing our hash function in the word-RAM model would require the same type of explicit expander graph as for implementing our non-adaptive dictionary (and a bit more), further motivating the study of such expanders (see Section 4).
2 Non-Adaptive Dictionaries
We consider the dictionary problem where we are to preprocess a set \( X \) of \( n \) key-value pairs from \([u] \times [u]\) into a data structure, such that given an \( x \in [u] \), we can quickly return the corresponding value \( y \) such that \((x, y) \in X\) or conclude that no such \( y \) exists. We assume that any for any key \( x \), there is at most one value \( y \) such that \((x, y) \in X\).
We focus on non-adaptive data structures in the cell probe model. Non-adaptive means that the memory cells probed on a query depends only on \( x \). We assume \( u = \Omega(n) \) and that the cell size \( w \) is \( \Theta(\log u) \).
As mentioned in Section 1, we base our data structure on expander graphs. We recall the standard definitions of bipartite expanders in the following:
**Definition 1.** A \((u, s, t)\)-bipartite graph with \( u \) left vertices, \( s \) right vertices and left degree \( t \) is specified by a function \( \Gamma : [u] \times [t] \rightarrow [s] \), where \( \Gamma(x, y) \) denotes the \( y \)th neighbor of \( x \). For a set \( S \subseteq [u] \), we write \( \Gamma(S) \) to denote its neighbors \( \{\Gamma(x, y) : x \in S, y \in [t]\} \).
**Definition 2.** A bipartite graph \( \Gamma : [u] \times [t] \rightarrow [s] \) is a \((K, A)\)-expander if for every set \( S \subseteq [u] \) with \(|S| = K\), we have \(|\Gamma(S)| \geq A \cdot K\). It is a \((\leq K_{\text{max}}, A)\)-expander if it is a \((K, A)\)-expander for every \( K \leq K_{\text{max}} \).
The literature on bipartite expanders, see e.g. [GUV09], is focused on graphs with near-optimal expansion \( A = (1 - \varepsilon)t \), i.e. very close to the largest possible expansion with degree \( t \). However, for our non-adaptive dictionaries, we need significantly less expansion. We call such expanders non-contractive and define them as follows:
**Definition 3.** A bipartite graph \( \Gamma : [u] \times [t] \rightarrow [s] \) is a \((\leq K_{\text{max}})\)-non-contractive expander if it is a \((\leq K_{\text{max}}, 1)\)-expander.
Said in words, a bipartite is a \((\leq K_{\text{max}})\)-non-contractive expander, if every set of at most \( K \leq K_{\text{max}} \) left-nodes has at least \( K \) neighbors.
Before presenting our dictionary, we present the second ingredient in our dictionary, namely Hall’s marriage theorem. For a bipartite graph with left-vertices \( X \), right-vertices \( Y \) and edges \( E \), an \( X \)-perfect matching is a subset of disjoint edges from \( E \) such that every vertex in \( X \) has an edge. Hall’s theorem then gives the following:
**Theorem 3** (Hall’s Marriage Theorem). A bipartite graph with left-vertices \( X \) and right-vertices \( Y \) has an \( X \)-perfect matching if and only if for every subset \( S \subseteq X \), the set of neighbors \( \Gamma(S) \) satisfies \(|\Gamma(S)| \geq |S|\).
With these ingredients, we are ready to present our dictionary.
Dictionary from Non-Contractive Expander. Given a set of \( n \) key-value pairs \( X = \{(x_i, y_i)\}_{i=1}^n \subset [u] \times [u] \) and a space budget of \( s \) memory cells, we build a data structure as follows:
Construction. Initialize \( s \) memory cells and let \( \Gamma : [u] \times [t] \rightarrow [s] \) be a \((\leq n)\)-non-contractive expander for some \( t \). Construct the bipartite graph \( G \) with a left-vertex for each \( x_i \) and a right vertex for each of the \( s \) memory cells. Add an edge from \( x_i \) to each of the nodes \( \Gamma(x_i, j) \) for \( i = 0, \ldots, t - 1 \). Note that this is a subgraph of the bipartite \((\leq n)\)-non-contractive expander corresponding to \( \Gamma \). It follows that for every subset \( S \subseteq \{x_i\}_{i=1}^n \), we have \( |\Gamma(S)| \geq |S| \). We now invoke Hall’s Marriage Theorem (Theorem 3) to conclude the existence of an \( \{x_i\}_{i=1}^n \)-perfect matching on \( G \). Let \( M = \{(x_i, v_i)\}_{i=1}^n \) denote the edges of the matching. For each such edge \((x_i, v_i)\), we store the key-value pair \((x_i, y_i)\) in the memory cell of address \( v_i \). For all remaining \( s - n \) memory cells, we store a special \( \text{Nil} \) value.
Querying. Given a query \( x \in [u] \), we query the \( t \) memory cells of address \( \Gamma(x, i) \) for \( i = 0, \ldots, t - 1 \). If any of them stores a pair \((x, y)\), we return it. Otherwise, we return \( \text{Nil} \) to indicate that no pair \((x, y)\) exists in \( X \).
Analysis. Correctness follows immediately from Hall’s Marriage Theorem. The space usage is \( s \) memory cells of \( w = \Theta(\lg u) \) bits and the query time is \( t \). The required perfect matching \( M \) can be computed in \( \text{poly}(n, s) \) times after performing \( O(nt) \) queries to obtain the edges of the subgraph induced by the left-vertices \( \{x_i\}_{i=1}^n \). We thus have the following result:
**Lemma 1.** Given a bipartite \((\leq n)\)-non-contractive expander \( \Gamma : [u] \times [t] \rightarrow [s] \), there is a non-adaptive dictionary for storing a set of \( n \) key-value pairs using \( s \) cells of \( w = \Theta(\lg u) \) bits and answering queries in \( t \) evaluations of \( \Gamma \) and \( t \) memory probes. The dictionary can be constructed in \( \text{poly}(n, s) \) time plus \( O(nt) \) evaluations of \( \Gamma \).
Lemma 1 thus gives us a way of obtaining a non-adaptive dictionary from an expander. What remains is to give expanders with good parameters. As mentioned, we do not have optimal explicit constructions of such expanders. However, for the cell probe model where computation is free of charge, we merely need the existence of \( \Gamma \) and not that it is efficiently computable. Concretely, a probabilistic argument gives the following:
**Lemma 2.** For any \( s \geq 2n \) and any \( u \geq n \), there exists a (non-explicit) \((\leq n)\)-non-contractive expander \( \Gamma : [u] \times [t] \rightarrow [s] \) with \( t = \log(u/n)/\log(s/n) + 5 \).
Combining Lemma 1 and Lemma 2 implies our Theorem 1.
Non-Explicit Expander. In the following, we prove Lemma 2. For this, consider drawing \( \Gamma : [u] \times [t] \rightarrow [s] \) uniformly among all such functions/expanders. That is, we let \( \Gamma(x, y) \) be uniform random and independently chosen in \([s]\) for each \( x \in [u] \) and \( y \in [t] \). For each \( S \subseteq [u] \) with \( |S| \leq n \) and each \( T \subseteq [s] \) with \( |T| = |S| - 1 \), define an event \( E_{S,T} \) that occurs if \( \Gamma(S) \subseteq T \). We have that \( \Gamma \) is a \((\leq n)\)-non-contractive expander if none of the events \( E_{S,T} \) occur. For a fixed \( E_{S,T} \), we have
\[ \Pr[E_{S,T}] = (|T|/s)^{|S|} \] and thus a union bound implies
\[
\Pr[\Gamma \text{ is not a } (\leq n)\text{-non-contractive expander}] \leq \sum_{S,T} \Pr[E_{S,T}] = \sum_{i=1}^{n} \sum_{S \subseteq [u] : |S| = i} \sum_{T \subseteq [s] : |T| = i-1} \Pr[E_{S,T}] \leq \sum_{i=1}^{n} \binom{u}{i} \binom{s}{i} (i/s)^{it} \leq \sum_{i=1}^{n} (eu/i)^{i}(es/i)^{i}(i/s)^{ti} = \sum_{i=1}^{n} \left( e^{2}u/t-2 \right)^{i} \leq \sum_{i=1}^{n} (e^{2}(u/n)(s/n)^{t-1})^{i}.
\]
For \( s \geq 2n \) and \( t \geq \lg(u/n)/\lg(s/n) + 5 \), this is at most \( \sum_{i=1}^{n} (e^{2}/16)^{i} < 1 \) and thus proves Lemma 2.
### 3 Hashing
In this section, we show how to construct a \( n \)-wise independent hash function with fast evaluation in the cell probe model. As a data structure problem, such a data structure has a query \( h(x) \) for each \( x \in [u] \). Upon construction, the data structure draws a random seed and initializes \( s \) memory cells of \( w \) bits. The data structure satisfies that the values \( h(x) \) are uniform random in \( \mathbb{F}_p \) and \( n \)-wise independent. Here the randomness is over the choice of random seed.
Similarly to our dictionary, our hashing data structures makes use of a bipartite expander. However, we need a (very) slightly stronger expansion property. Concretely, we assume the availability of a \( (\leq n, 2) \)-expander \( \Gamma : [u] \times [t] \rightarrow [s] \) (rather than a \( (\leq n, 1) \)-expander). The expander \( \Gamma \) thus satisfies that for any \( S \subseteq [u] \) with \( |S| \leq n \), we have \( |\Gamma(S)| \geq 2|S| \).
In addition to the \( (\leq n, 2) \)-expander \( \Gamma \), we also need another function assigning weights to the edges of \( \Gamma \). We say that \( \Pi : [u] \times [t] \rightarrow \mathbb{F}_p \) makes \( \Gamma \) useful if the following holds: Construct from \((\Gamma, \Pi)\) the \( u \times s \) matrix \( A_{\Gamma,\Pi} \) such that entry \((x, y)\) equals
\[
\sum_{j: \Gamma(x,j)=y} \Pi(x, j) \mod p
\]
We have that \((\Gamma, \Pi)\) is useful if every subset of \( n \) rows in \( A_{\Gamma,\Pi} \) is a linearly independent set of vector over \( \mathbb{F}_p^s \). We show later that for any \( (\leq n, 2) \)-expander \( \Gamma \), there exists at least one \( \Pi \) making \( \Gamma \) useful:
**Lemma 3.** If \( \Gamma : [u] \times [t] \rightarrow [s] \) is a \( (\leq n, 2) \)-expander, then for \( p \geq 2eu \), there exists a \( \Pi : [u] \times [t] \rightarrow \mathbb{F}_p \) such that \((\Gamma, \Pi)\) is useful.
In the cell probe model, we may assume that $\Gamma$ and $\Pi$ are free to evaluate and are known to a data structure since computation is free of charge. With such a pair $(\Gamma, \Pi)$ we may now construct our data structure for $n$-wise independent hashing.
**Construction.** Initialize the data structure by filling each of the $s$ memory cells by uniformly and independently chosen values in $\mathbb{F}_p$ (the seed). Let $z_0, \ldots, z_{s-1}$ denote the values in the memory cells.
**Querying.** To evaluate $h(x)$ for an $x \in [u]$, compute and return the value
\[
\sum_{j=0}^{t-1} \Pi(x, j) z_{\Gamma(x,j)} \mod p.
\]
**Analysis.** Observe that the value returned on the query $x$ equals
\[
\sum_{j=0}^{t-1} \Pi(x, j) z_{\Gamma(x,j)} \mod p \equiv \sum_{y=0}^{s-1} \sum_{j: \Gamma(x,j)=y} \Pi(x, j) z_{\Gamma(x,j)} \mod p.
\]
But this is the same as $(A_{\Gamma,\Pi}z)_x$, i.e. the inner product of the $x$'th row of $A_{\Gamma,\Pi}$ with the randomly drawn vector $z$. Since the rows of $A_{\Gamma,\Pi}$ are $n$-wise independent and $z$ is drawn uniformly, we conclude that the query values $h(0), \ldots, h(u-1)$ are $n$-wise independent as well. The query time is $t$ probes and the space usage is $s$ cells of $\lg p$ bits. We thus conclude
**Lemma 4.** Given a bipartite $(\leq n, 2)$ expander $\Gamma : [u] \times [t] \rightarrow [s]$ and a $p \geq 2eu$, there is a cell probe data structure for evaluating an $n$-wise independent hash function $h : [u] \rightarrow \mathbb{F}_p$ using $s$ cells of $w = \Theta(\lg p)$ bits and answering queries in $t$ cell probes.
An argument similar to the proof of Lemma 2, we show the existence of the desired expanders:
**Lemma 5.** For any $s \geq 2n$ and any $u \geq n$, there exists a (non-explicit) $(\leq n, 2)$ expander $\Gamma : [u] \times [t] \rightarrow [s]$ with $t = 2\lg(u/n)/\lg(s/n) + 4$.
Combining Lemma 5, Lemma 3 and Lemma 4 proves Theorem 2. What remains is to prove Lemma 3 and Lemma 5. We start with Lemma 3.
**Proof.** (of Lemma 3) We give a probabilistic argument. Let $\Gamma : [u] \times [t] \rightarrow [s]$ be a $(\leq n, 2)$-expander. Draw $\Pi : [u] \times [t] \rightarrow \mathbb{F}_p$ by letting $\Pi(x, j)$ be chosen uniformly and independently from $\mathbb{F}_p$. Define an event $E_{\beta}$ for every $\beta \in \mathbb{F}_p^n$ with $1 \leq \|\beta\|_0 \leq n$ ($\|\beta\|_0$ gives the number of non-zeros) that occurs if $\beta A_{\Gamma,\Pi} = 0$. We have that $(\Gamma, \Pi)$ is useful if none of the events $E_{\beta}$ occur.
Consider one of these events $E_{\beta}$. Since $\Gamma$ is a $(\leq n, 2)$-expander, we have that the set of rows in $A_{\Gamma,\Pi}$ corresponding to non-zero coefficients of $\beta$ have at least $2\|\beta\|_0$ distinct columns containing an entry that is chosen uniformly at random and independently from $\mathbb{F}_p$. We thus have
\[ \Pr[\beta] \leq p^{-2\|\beta\|_0}. \] A union bound finally implies:
\[
\Pr[\text{\(\Gamma, \Pi\)} \text{ is not useful}] \leq
\sum_{i=1}^{n} \sum_{\beta \in \mathbb{F}_p^2 : \|\beta\|_0 = i} \Pr[E_{\beta}] \leq
\sum_{i=1}^{n} \left( \frac{u}{i} \right) p^i p^{-2i} \leq
\sum_{i=1}^{n} (eu/(ip))^i.
\]
For \( p \geq 2eu \), this is less than 1, which concludes the proof of Lemma 3.
Lastly, we prove Lemma 5.
**Proof.** (of Lemma 5) The proof follows that of Lemma 2 uneventfully. Draw \( \Gamma \) randomly, with each \( \Gamma(x, y) \) uniform and independently chosen in \([s]\). Again, we define an event \( E_{S,T} \) for each \( S \subseteq [u] \) with \( |S| \leq n \) and each \( T \subseteq [s] \) with \( |T| = 2|S| - 1 \). The event \( E_{S,T} \) occurs if \( \Gamma(S) \subseteq T \). We have
\[
\Pr[\Gamma \text{ is not an \( (\leq n, 2) \)-expander}] \leq
\sum_{S,T} \Pr[E_{S,T}] \leq
\sum_{i=1}^{n} \left( \frac{u}{i} \right) \left( \frac{s}{2i} \right)^{(2i)/s}i \leq
\sum_{i=1}^{n} (eu/i)(s/(2i))^{2i}(2i)/s)^{i} =
\sum_{i=1}^{n} \left( \frac{eu(2i)^{t-3}}{s^{t-2}} \right)^i \leq
\sum_{i=1}^{n} \left( e(u/n)/(2n/s)^{t-2} \right)^i
\]
For \( s \geq 4n \) and \( t \geq 2\lg(u/n)/\lg(s/n) + 4 \geq \lg(u/n)/\lg(s/(2n)) + 4 \), this is less than 1, completing the proof of Lemma 5.
**4 Conclusion and Open Problems**
In this work, we gave optimal non-adaptive cell probe dictionaries and data structures for evaluating \( n \)-wise independent hash functions. Our data structures rely on the existence of bipartite expanders with quite weak expansion properties, namely \((\leq n, 1)\) and \((\leq n, 2)\)-bipartite expanders. If efficient explicit constructions of such expanders were to be developed, they would immediately allow us to implement our dictionary in the standard word-RAM model. They would also go a long way towards a word-RAM implementation of \( n \)-wise independent hashing. We thus view our results as strong motivation for further research into such expanders.
Next, we remark that our non-explicit constructions of $(\leq n, 1)$ and $(\leq n, 2)$ expanders are essentially optimal. Concretely, a result of Radhakrishnan and Ta-Shma [RT00] shows that any $(u, s, t)$-bipartite graph with expansion 1 requires $t = \Omega(\lg(u/n)/\lg(s/n))$. In more detail, Theorem 1.5 (a) of [RT00] proves that if $G$ is a $(u, s, t)$-bipartite graph that is an $(n, \epsilon)$ disperser (every set of $n$ left-nodes has at least $(1-\epsilon)s$ right-nodes), then for $\epsilon > 1/2$, the left-degree, $t$, is $\Omega(\lg(u/n)/\lg(1/(1-\epsilon)))$. Since a $(\leq n, 1)$-non-contractive expander is also an $(n, \epsilon)$-disperser with $(1-\epsilon) = n/s$, the lower bound $t = \Omega(\lg(u/n)/\lg(s/n))$ follows.
Finally, we also observe a near-equivalence between non-adaptive data structures for evaluating $n$-wise independent hash functions and non-contractive bipartite expanders. Concretely, assume we have a word-RAM data structure for evaluating an $n$-wise independent hash function from $[u]$ to $[u]$ and assume $w = \lg u$ for simplicity. If the data structure uses $s$ space and answers queries in $t$ time (including memory lookups and computation), then we may obtain an explicit expander from the data structure. Concretely, we form a right node for every memory cell, a left node for every query and an edge corresponding to each cell probed on a query. Now observe that if there was a set of $n$ left nodes $S$ with $|\Gamma(S)| < n$, then from those $|\Gamma(S)|$ memory cells, the data structure has to return $n$ independent and uniform random values in $[u]$. But the cells only have $|\Gamma(S)|w < n\lg u$ bits, i.e. a contradiction. Hence the resulting expander is non-contractive. If the query time of the data structure was $t$, we may obtain the edges incident to a left node simply by running the corresponding query algorithm. Since the query algorithm runs in $t$ time, it clearly accesses at most $t$ right nodes and computing the nodes to access can also be done in $t$ time. A similar connection was observed by [CPT15].
References
|
{"Source-Url": "https://cs.au.dk/~larsen/papers/NonAdaptiveDictionary.pdf", "len_cl100k_base": 8803, "olmocr-version": "0.1.45", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 42326, "total-output-tokens": 10665, "length": "2e13", "weborganizer": {"__label__adult": 0.0004684925079345703, "__label__art_design": 0.0005888938903808594, "__label__crime_law": 0.0006608963012695312, "__label__education_jobs": 0.0008120536804199219, "__label__entertainment": 0.00015592575073242188, "__label__fashion_beauty": 0.0002765655517578125, "__label__finance_business": 0.00048732757568359375, "__label__food_dining": 0.0006246566772460938, "__label__games": 0.001148223876953125, "__label__hardware": 0.0033931732177734375, "__label__health": 0.0014486312866210938, "__label__history": 0.0005555152893066406, "__label__home_hobbies": 0.00022327899932861328, "__label__industrial": 0.0008683204650878906, "__label__literature": 0.0004405975341796875, "__label__politics": 0.0004546642303466797, "__label__religion": 0.0008311271667480469, "__label__science_tech": 0.33642578125, "__label__social_life": 0.00010311603546142578, "__label__software": 0.01025390625, "__label__software_dev": 0.63818359375, "__label__sports_fitness": 0.0003986358642578125, "__label__transportation": 0.0008420944213867188, "__label__travel": 0.0003058910369873047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32803, 0.02311]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32803, 0.32194]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32803, 0.82164]], "google_gemma-3-12b-it_contains_pii": [[0, 693, false], [693, 4587, null], [4587, 8748, null], [8748, 12975, null], [12975, 16614, null], [16614, 20369, null], [20369, 22920, null], [22920, 25789, null], [25789, 27808, null], [27808, 31237, null], [31237, 32803, null]], "google_gemma-3-12b-it_is_public_document": [[0, 693, true], [693, 4587, null], [4587, 8748, null], [8748, 12975, null], [12975, 16614, null], [16614, 20369, null], [20369, 22920, null], [22920, 25789, null], [25789, 27808, null], [27808, 31237, null], [31237, 32803, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32803, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 32803, null]], "pdf_page_numbers": [[0, 693, 1], [693, 4587, 2], [4587, 8748, 3], [8748, 12975, 4], [12975, 16614, 5], [16614, 20369, 6], [20369, 22920, 7], [22920, 25789, 8], [25789, 27808, 9], [27808, 31237, 10], [31237, 32803, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32803, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-23
|
2024-11-23
|
00aec0da8faf4707814f2e71d5b76f7a4ef273c2
|
CS 677: Parallel Programming for Many-core Processors
Lecture 2
Instructor: Philippos Mordohai
Webpage: www.cs.stevens.edu/~mordohai
E-mail: Philippos.Mordohai@stevens.edu
Overview
• Simple encryption example
• Blocks, threads and warps
• CUDA memory types
• Matrix Multiplication using Shared Memory
• Thread Execution and Divergence
• Atomics
Encryption Example
```cpp
#include <iostream>
#include <cutil.h>
using namespace std;
__global__ void cuda_encrypt(char* m, int m_len, int shift)
{
for (int i = 0; i < m_len; i++)
m[i] = (((m[i] - 'a') + shift) % 26) + 'a';
}
```
Courtesy of Werner Backes
int main()
{
char message[255];
int message_len, shift;
char* dev_message;
cin >> message;
cin >> shift;
cout << "plaintext: " << message << endl;
message_len = strlen(message);
cudaMalloc(&dev_message, message_len+1);
cudaMemcpy(dev_message, message, message_len+1, cudaMemcpyHostToDevice);
cuda_encrypt<<<1,1>>>(dev_message, message_len, shift);
cudaMemcpy(message, dev_message, message_len+1, cudaMemcpyDeviceToHost);
cout << "ciphertext: " << message << endl;
return 0;
}
Compilation and Execution
• Compile the example program hello world.cu using the CUDA compiler nvcc.
– `nvcc -I. hello_world.cu -o hello_world`
– The option `-I` is used to add an include path
– `nvcc --help` outputs all available compiler options
• Output:
– Execute `./hello_world`
helloworld
3
plaintext: helloworld
ciphertext: khoorzruog
Parallel Encryption Example
```cpp
#include <iostream>
#include <cutil.h>
using namespace std;
__global__ void cuda_encrypt(char* m, int m_len, int shift)
{
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if (tid < m_len)
m[tid] = (((m[tid] - 'a') + shift) % 26) + 'a';
}
```
int main()
{
char message[255];
int message_len, shift;
char* dev_message;
cin >> message;
cin >> shift;
cout << "plaintext: " << message << endl;
message_len = strlen(message);
cudaMalloc(&dev_message, message_len+1);
cudaMemcpy(dev_message, message, message_len+1, cudaMemcpyHostToDevice);
cuda_encrypt<<<(message_len/32)+1,32>>>(dev_message, message_len, shift);
cudaMemcpy(message, dev_message, message_len+1, cudaMemcpyDeviceToHost);
cout << "ciphertext: " << message << endl;
return 0;
}
Block IDs and Thread IDs
- Each thread uses IDs to decide what data to work on
- Block ID: 1D, 2D or 3D
- Thread ID: 1D, 2D, or 3D
- Simplifies memory addressing when processing multidimensional data
- Image processing
- Solving PDEs on volumes
- ...
© David Kirk/NVIDIA and Wen-mei W. Hwu, 2007-2009
ECE498AL, University of Illinois, Urbana-Champaign
Matrix Multiplication Using Multiple Blocks
- Break-up Pd into tiles
- Each block calculates one tile
- Each thread calculates one element
- Block size equal to tile size
A Small Example
TILE_WIDTH = 2
Block(0,0) Block(1,0)
<p>| | | | |</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>P0,0</td>
<td>P1,0</td>
<td>P2,0</td>
<td>P3,0</td>
</tr>
<tr>
<td>P0,1</td>
<td>P1,1</td>
<td>P2,1</td>
<td>P3,1</td>
</tr>
<tr>
<td>P0,2</td>
<td>P1,2</td>
<td>P2,2</td>
<td>P3,2</td>
</tr>
<tr>
<td>P0,3</td>
<td>P1,3</td>
<td>P2,3</td>
<td>P3,3</td>
</tr>
</tbody>
</table>
Block(0,1) Block(1,1)
A Small Example: Multiplication
Revised Matrix Multiplication Kernel using Multiple Blocks
```c
__global__ void MatrixMulKernel(float* Md, float* Nd, float* Pd, int Width)
{
// Calculate the row index of the Pd element and M
int Row = blockIdx.y*TILE_WIDTH + threadIdx.y;
// Calculate the column idenx of Pd and N
int Col = blockIdx.x*TILE_WIDTH + threadIdx.x;
float Pvalue = 0;
// each thread computes one element of the block sub-matrix
for (int k = 0; k < Width; ++k)
Pvalue += Md[Row*Width+k] * Nd[k*Width+Col];
Pd[Row*Width+Col] = Pvalue;
}
```
Revised Step 5: Kernel Invocation (Host-side Code)
// Setup the execution configuration
dim3 dimGrid(Width/TILE_WIDTH, Width/TILE_WIDTH);
dim3 dimBlock(TILE_WIDTH, TILE_WIDTH);
// Launch the device computation threads
MatrixMulKernel<<<dimGrid, dimBlock>>>(Md, Nd, Pd, Width);
CUDA Thread Block
• All threads in a block execute the same kernel program (SPMD)
• Programmer declares block:
– Block size 1 to 512 concurrent threads
– Block shape 1D, 2D, or 3D
– Block dimensions in threads
• Threads have thread id numbers within block
– Thread program uses thread id to select work and address shared data
• Threads in the same block share data and synchronize while doing their share of the work
• Threads in different blocks cannot cooperate
– Each block can execute in any order relative to other blocks!
Courtesy: John Nickolls, NVIDIA
Transparent Scalability
- Hardware is free to assign blocks to any processor at any time
- A kernel scales across any number of parallel processors
Each block can execute in any order relative to other blocks.
G80 Example: Executing Thread Blocks
- Threads are assigned to Streaming Multiprocessors in block granularity
- Up to 8 blocks to each SM as resource allows
- SM in G80 can take up to 768 threads
- Could be 256 (threads/block) * 3 blocks
- Or 128 (threads/block) * 6 blocks, etc.
- Threads run concurrently
- SM maintains thread/block id #s
- SM manages/schedules thread execution
G80 Example: Thread Scheduling
- Each Block is executed as 32-thread Warps
- An implementation decision, not part of the CUDA programming model
- Warps are scheduling units in SM
- If 3 blocks are assigned to an SM and each block has 256 threads, how many Warps are there in an SM?
- Each Block is divided into 256/32 = 8 Warps
- There are 8 * 3 = 24 Warps
G80 Example: Thread Scheduling (Cont.)
- SM implements zero-overhead warp scheduling
- Warps whose next instruction has its operands ready for consumption are eligible for execution
- Eligible Warps are selected for execution on a prioritized scheduling policy
- All threads in a warp execute the same instruction when selected
G80 Block Granularity Considerations
- For Matrix Multiplication using multiple blocks, should I use 8X8, 16X16 or 32X32 blocks?
- For 8X8, we have 64 threads per Block. Since each SM can take up to 768 threads, there are 12 Blocks. However, each SM can only take up to 8 Blocks, only 512 threads will go into each SM!
- For 16X16, we have 256 threads per Block. Since each SM can take up to 768 threads, it can take up to 3 Blocks and achieve full capacity unless other resource considerations overrule.
- For 32X32, we have 1024 threads per Block. Not even one can fit into an SM!
## Technical Specifications per Compute Capability
<table>
<thead>
<tr>
<th>Technical specifications</th>
<th>Compute capability (version)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>1.0</td>
</tr>
<tr>
<td>Maximum number of resident grids per device (concurrent kernel execution)</td>
<td>t.b.d.</td>
</tr>
<tr>
<td>Maximum dimensionality of grid of thread blocks</td>
<td>2</td>
</tr>
<tr>
<td>Maximum x-dimension of a grid of thread blocks</td>
<td>65535</td>
</tr>
<tr>
<td>Maximum y- or z-dimension of a grid of thread blocks</td>
<td>65535</td>
</tr>
<tr>
<td>Maximum dimensionality of thread block</td>
<td>3</td>
</tr>
<tr>
<td>Maximum x- or y-dimension of a block</td>
<td>512</td>
</tr>
<tr>
<td>Maximum z-dimension of a block</td>
<td>64</td>
</tr>
<tr>
<td>Maximum number of threads per block</td>
<td>512</td>
</tr>
<tr>
<td>Warp size</td>
<td>32</td>
</tr>
<tr>
<td>Maximum number of resident blocks per multiprocessor</td>
<td>8</td>
</tr>
<tr>
<td>Maximum number of resident warps per multiprocessor</td>
<td>24</td>
</tr>
<tr>
<td>Maximum number of resident threads per multiprocessor</td>
<td>768</td>
</tr>
<tr>
<td>Number of 32-bit registers per multiprocessor</td>
<td>8 K</td>
</tr>
<tr>
<td>Maximum number of 32-bit registers per thread block</td>
<td>N/A</td>
</tr>
<tr>
<td>Maximum number of 32-bit registers per thread</td>
<td>124</td>
</tr>
<tr>
<td>Maximum amount of shared memory per multiprocessor</td>
<td>16 KB</td>
</tr>
<tr>
<td>Maximum amount of shared memory per thread block</td>
<td>48 KB</td>
</tr>
<tr>
<td>Number of shared memory banks</td>
<td>16</td>
</tr>
<tr>
<td>Amount of local memory per thread</td>
<td>16 KB</td>
</tr>
<tr>
<td>Constant memory size</td>
<td></td>
</tr>
</tbody>
</table>
More Details of API Features
Application Programming Interface
- The API is an extension to the C programming language
- It consists of:
- Language extensions
- To target portions of the code for execution on the device
- A runtime library split into:
- A common component providing built-in vector types and a subset of the C runtime library in both host and device code
- A host component to control and access one or more devices from the host
- A device component providing device-specific functions
Language Extensions: Built-in Variables
• `dim3 gridSize;`
– Dimensions of the grid in blocks
• `dim3 blockDim;`
– Dimensions of the block in threads
• `dim3 blockIdx;`
– Block index within the grid
• `dim3 threadIdx;`
– Thread index within the block
Common Runtime Component: Mathematical Functions
- `pow`, `sqrt`, `cbrt`, `hypot`
- `exp`, `exp2`, `expm1`
- `log`, `log2`, `log10`, `log1p`
- `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`
- `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`
- `ceil`, `floor`, `trunc`, `round`
- Etc.
- When executed on the host, a given function uses the C runtime implementation if available
- These functions are only supported for scalar types, not vector types
Device Runtime Component: Mathematical Functions
- Some mathematical functions (e.g. \( \sin(x) \)) have a less accurate, but faster device-only version (e.g. \( \_\_\sin(x) \))
- \( \_\_\_\_\text{pow} \)
- \( \_\_\_\_\text{log}, \_\_\_\text{log2}, \_\_\_\text{log10} \)
- \( \_\_\_\_\text{exp} \)
- \( \_\_\_\_\text{sin}, \_\_\_\text{cos}, \_\_\_\text{tan} \)
Host Runtime Component
- Provides functions to deal with:
- **Device** management (including multi-device systems)
- **Memory** management
- **Error** handling
- Initializes the first time a runtime function is called
- A host thread can invoke device code on only one device
- Multiple host threads required to run on multiple devices
Device Runtime Component: Synchronization Function
- `void __syncthreads();`
- Synchronizes all threads in a block
- Once all threads have reached this point, execution resumes normally
- Used to avoid RAW / WAR / WAW hazards when accessing shared or global memory
- Allowed in conditional constructs only if the conditional is uniform across the entire thread block
CUDA Memories
Hardware Implementation of CUDA Memories
• Each thread can:
– Read/write per-thread registers
– Read/write per-thread local memory
– Read/write per-block shared memory
– Read/write per-grid global memory
– Read/only per-grid constant memory
CUDA Variable Type Qualifiers
<table>
<thead>
<tr>
<th>Variable declaration</th>
<th>Memory</th>
<th>Scope</th>
<th>Lifetime</th>
</tr>
</thead>
<tbody>
<tr>
<td>int var;</td>
<td>register</td>
<td>thread</td>
<td>thread</td>
</tr>
<tr>
<td>int array_var[10];</td>
<td>local</td>
<td>thread</td>
<td>thread</td>
</tr>
<tr>
<td><strong>shared</strong> int shared_var;</td>
<td>shared</td>
<td>block</td>
<td>block</td>
</tr>
<tr>
<td><strong>device</strong> int global_var;</td>
<td>global</td>
<td>grid</td>
<td>application</td>
</tr>
<tr>
<td><strong>constant</strong> int constant_var;</td>
<td>constant</td>
<td>grid</td>
<td>application</td>
</tr>
</tbody>
</table>
- “automatic” scalar variables without qualifier reside in a register
– compiler will spill to thread local memory
- “automatic” array variables without qualifier reside in thread local memory
CUDA Variable Type Performance
<table>
<thead>
<tr>
<th>Variable declaration</th>
<th>Memory</th>
<th>Penalty</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>int var;</code></td>
<td>register</td>
<td>1x</td>
</tr>
<tr>
<td><code>int array_var[10];</code></td>
<td>local</td>
<td>100x</td>
</tr>
<tr>
<td><code>__shared__ int shared_var;</code></td>
<td>shared</td>
<td>1x</td>
</tr>
<tr>
<td><code>__device__ int global_var;</code></td>
<td>global</td>
<td>100x</td>
</tr>
<tr>
<td><code>__constant__ int constant_var;</code></td>
<td>constant</td>
<td>1x</td>
</tr>
</tbody>
</table>
- scalar variables reside in fast, on-chip registers
- shared variables reside in fast, on-chip memories
- thread-local arrays & global variables reside in uncached off-chip memory
- Cache is now available, but there is still a significant drop off in speed
- constant variables reside in cached off-chip memory
CUDA Variable Type Scale
<table>
<thead>
<tr>
<th>Variable declaration</th>
<th>Instances</th>
<th>Visibility</th>
</tr>
</thead>
<tbody>
<tr>
<td>int var;</td>
<td>100,000s</td>
<td>1</td>
</tr>
<tr>
<td>int array_var[10];</td>
<td>100,000s</td>
<td>1</td>
</tr>
<tr>
<td><strong>shared</strong> int shared_var;</td>
<td>100s</td>
<td>100s</td>
</tr>
<tr>
<td><strong>device</strong> int global_var;</td>
<td>1</td>
<td>100,000s</td>
</tr>
<tr>
<td><strong>constant</strong> int constant_var;</td>
<td>1</td>
<td>100,000s</td>
</tr>
</tbody>
</table>
- 100Ks per-thread variables, R/W by 1 thread
- 100s shared variables, each R/W by 100s of threads
- 1 global variable is R/W by 100Ks threads
- 1 constant variable is readable by 100Ks threads
Where to declare variables?
Can host access it?
- Yes
- Outside of any function
- __constant__ int constant_var;
- __device__ int global_var;
- In the kernel
- int var;
- int array_var[10];
- __shared__ int shared_var;
- No
Example - thread-local variables
// Ten Nearest Neighbors application
__global__ void ten_nn(float2 *result, float2 *ps, float2 *qs,
size_t num_qs)
{
// p goes in a register
float2 p = ps[threadIdx.x];
// per-thread heap goes in off-chip memory
float2 heap[10];
// read through num_qs points, maintaining
// the nearest 10 qs to p in the heap
...
// write out the contents of heap to result
...
}
Example - shared variables
// motivate shared variables with
// Adjacent Difference application:
// compute result[i] = input[i] - input[i-1]
__global__ void adj_diff_naive(int *result, int *input)
{
// compute this thread’s global index
unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;
if(i > 0)
{
int x_i = input[i];
int x_i_minus_one = input[i-1];
result[i] = x_i - x_i_minus_one;
}
}
Example - shared variables
// motivate shared variables with
// Adjacent Difference application:
// compute result[i] = input[i] - input[i-1]
__global__ void adj_diff_naive(int *result, int *input)
{
// compute this thread’s global index
unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;
if(i > 0)
{
// what are the bandwidth requirements of this kernel?
int x_i = input[i];
int x_i_minus_one = input[i-1];
result[i] = x_i - x_i_minus_one;
}
}
Example - shared variables
// motivate shared variables with
// Adjacent Difference application:
// compute result[i] = input[i] - input[i-1]
__global__ void adj_diff_naive(int *result, int *input)
{
// compute this thread’s global index
unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;
if(i > 0)
{
// How many times does this kernel load input[i]?
int x_i = input[i]; // once by thread i
int x_i_minus_one = input[i-1]; // again by thread i+1
result[i] = x_i - x_i_minus_one;
}
}
Example - shared variables
// optimized version of adjacent difference
__global__ void adj_diff(int *result, int *input)
{
// shorthand for threadIdx.x
int tx = threadIdx.x;
// allocate a __shared__ array, one element per thread
__shared__ int s_data[BLOCK_SIZE];
// each thread reads one element to s_data
unsigned int i = blockDim.x * blockIdx.x + tx;
s_data[tx] = input[i];
// avoid race condition: ensure all loads
// complete before continuing
__syncthreads();
...
Example - shared variables
```c
if(tx > 0)
result[i] = s_data[tx] - s_data[tx-1];
else if(i > 0)
{
// handle thread block boundary
result[i] = s_data[tx] - input[i-1];
}
```
Example - shared variables
// when the size of the array isn’t known at compile time...
__global__ void adj_diff(int *result, int *input)
{
// use extern to indicate a __shared__ array will be
// allocated dynamically at kernel launch time
extern __shared__ int s_data[];
...
}
// pass the size of the per-block array, in bytes, as the third
// argument to the triple chevrons
adj_diff<<<num_blocks, block_size, block_size * sizeof(int)>>>(r,i);
• Only one extern shared array can be declared
• See CUDA programming guide for work-around
About Pointers - Outdated but Useful
• Yes, you can use them!
• You can point to any memory space:
```c
__device__ int my_global_variable;
__constant__ int my_constant_variable = 13;
__global__ void foo(void)
{
__shared__ int my_shared_variable;
int *ptr_to_global = &my_global_variable;
const int *ptr_to_constant = &my_constant_variable;
int *ptr_to_shared = &my_shared_variable;
...
*ptr_to_global = *ptr_to_shared;
}
```
About Pointers - Outdated but Useful
- Pointers aren’t typed on memory space
- `__shared__` int *ptr;
- Where does `ptr` point?
- `ptr` is a `__shared__` pointer variable, not a pointer to a `__shared__` variable!
Don’t confuse the compiler!
```c
__device__ int my_global_variable;
__global__ void foo(int *input)
{
__shared__ int my_shared_variable;
int *ptr = 0;
if(input[threadIdx.x] % 2)
ptr = &my_global_variable;
else
ptr = &my_shared_variable;
// where does ptr point?
}
```
Advice
• Prefer dereferencing pointers in simple, regular access patterns
• Avoid propagating pointers
• Avoid pointers to pointers
– The GPU would rather not pointer chase
– Linked lists will not perform well
• Pay attention to compiler warning messages
– Warning: Cannot tell what pointer points to, assuming global memory space
– Crash waiting to happen
Unified Virtual Address Space
• The location of any memory on the host or on any of the devices which use the unified address space, can be determined from the value of the pointer using `cudaPointerGetAttributes()`
• When copying, the `cudaMemcpyKind` parameter of `cudaMemcpy*()` can be set to `cudaMemcpyDefault` to determine locations from the pointers. This also works for host pointers not allocated through CUDA, as long as the current device uses unified addressing.
Matrix Multiplication using Shared Memory
Review: Matrix Multiplication Kernel using Multiple Blocks
```c
__global__ void MatrixMulKernel(float* Md, float* Nd, float* Pd, int Width)
{
// Calculate the row index of the Pd element and M
int Row = blockIdx.y*TILE_WIDTH + threadIdx.y;
// Calculate the column idenx of Pd and N
int Col = blockIdx.x*TILE_WIDTH + threadIdx.x;
float Pvalue = 0;
// each thread computes one element of the block sub-matrix
for (int k = 0; k < Width; ++k)
Pvalue += Md[Row*Width+k] * Nd[k*Width+Col];
Pd[Row*Width+Col] = Pvalue;
}
```
How about performance on GPU?
- All threads access global memory for their input matrix elements
- Two memory accesses (8 bytes) per floating point multiply-add
- 4B/s of memory bandwidth/FLOPS
- $4 \times 346.5 = 1386$ GB/s required to achieve peak FLOP rating
- 86.4 GB/s limits the code at 21.6 GFLOPS
- The actual code runs at about 15 GFLOPS
- Need to drastically cut down memory accesses to get closer to the peak 346.5 GFLOPS (on G80 - ignore specific numbers)
Idea: Use Shared Memory to reuse global memory data
- Each input element is read by Width threads
- Load each element into Shared Memory and have several threads use the local version to reduce the memory bandwidth
- Tiled algorithms
Tiled Multiply
- Break up the execution of the kernel into phases so that the data accesses in each phase is focused on one subset (tile) of $M_d$ and $N_d$
A Small Example
Every Md and Nd Element is used exactly twice in generating a 2X2 tile of $P$
<table>
<thead>
<tr>
<th>$P_{0,0}$ thread$_{0,0}$</th>
<th>$P_{1,0}$ thread$_{1,0}$</th>
<th>$P_{0,1}$ thread$_{0,1}$</th>
<th>$P_{1,1}$ thread$_{1,1}$</th>
</tr>
</thead>
<tbody>
<tr>
<td>$M_{0,0} \times N_{0,0}$</td>
<td>$M_{0,0} \times N_{1,0}$</td>
<td>$M_{0,1} \times N_{0,0}$</td>
<td>$M_{0,1} \times N_{1,0}$</td>
</tr>
<tr>
<td>$M_{1,0} \times N_{0,1}$</td>
<td>$M_{1,0} \times N_{1,1}$</td>
<td>$M_{1,1} \times N_{0,1}$</td>
<td>$M_{1,1} \times N_{1,1}$</td>
</tr>
<tr>
<td>$M_{2,0} \times N_{0,2}$</td>
<td>$M_{2,0} \times N_{1,2}$</td>
<td>$M_{2,1} \times N_{0,2}$</td>
<td>$M_{2,1} \times N_{1,2}$</td>
</tr>
<tr>
<td>$M_{3,0} \times N_{0,3}$</td>
<td>$M_{3,0} \times N_{1,3}$</td>
<td>$M_{3,1} \times N_{0,3}$</td>
<td>$M_{3,1} \times N_{1,3}$</td>
</tr>
</tbody>
</table>
Breaking Md and Nd into Tiles
- Break up the inner product loop of each thread into phases
- At the beginning of each phase, load the Md and Nd elements that everyone needs during the phase into shared memory
- Everyone accesses the Md and Nd elements from shared memory during the phase
Work for Block (0,0)
Work for Block (0,0)
<p>| | | | |</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>N₀,₀</td>
<td>N₀,₁</td>
<td>N₀,₂</td>
<td>N₀,₃</td>
</tr>
<tr>
<td>N₁,₀</td>
<td>N₁,₁</td>
<td>N₁,₂</td>
<td>N₁,₃</td>
</tr>
<tr>
<td>N₂,₀</td>
<td>N₂,₁</td>
<td>N₂,₂</td>
<td>N₂,₃</td>
</tr>
<tr>
<td>N₃,₀</td>
<td>N₃,₁</td>
<td>N₃,₂</td>
<td>N₃,₃</td>
</tr>
</tbody>
</table>
<p>| | | | |</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>M₀,₀</td>
<td>M₀,₁</td>
<td>M₀,₂</td>
<td>M₀,₃</td>
</tr>
<tr>
<td>M₁,₀</td>
<td>M₁,₁</td>
<td>M₁,₂</td>
<td>M₁,₃</td>
</tr>
<tr>
<td>M₂,₀</td>
<td>M₂,₁</td>
<td>M₂,₂</td>
<td>M₂,₃</td>
</tr>
<tr>
<td>M₃,₀</td>
<td>M₃,₁</td>
<td>M₃,₂</td>
<td>M₃,₃</td>
</tr>
</tbody>
</table>
© David Kirk/NVIDIA and Wen-mei W. Hwu, ECE408/CS483/ECE498al, 2007-2012
Work for Block (0,0)
<table>
<thead>
<tr>
<th></th>
<th>N₀,₀</th>
<th>N₀,₁</th>
<th>N₀,₂</th>
<th>N₀,₃</th>
</tr>
</thead>
<tbody>
<tr>
<td>N₁,₀</td>
<td>N₁,₁</td>
<td>N₁,₂</td>
<td>N₁,₃</td>
<td></td>
</tr>
<tr>
<td>N₂,₀</td>
<td>N₂,₁</td>
<td>N₂,₂</td>
<td>N₂,₃</td>
<td></td>
</tr>
<tr>
<td>N₃,₀</td>
<td>N₃,₁</td>
<td>N₃,₂</td>
<td>N₃,₃</td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th></th>
<th>M₀,₀</th>
<th>M₀,₁</th>
<th>M₀,₂</th>
<th>M₀,₃</th>
</tr>
</thead>
<tbody>
<tr>
<td>M₁,₀</td>
<td>M₁,₁</td>
<td>M₁,₂</td>
<td>M₁,₃</td>
<td></td>
</tr>
<tr>
<td>M₂,₀</td>
<td>M₂,₁</td>
<td>M₂,₂</td>
<td>M₂,₃</td>
<td></td>
</tr>
<tr>
<td>M₃,₀</td>
<td>M₃,₁</td>
<td>M₃,₂</td>
<td>M₃,₃</td>
<td></td>
</tr>
</tbody>
</table>
© David Kirk/NVIDIA and Wen-mei W. Hwu, ECE408/CS483/ECE498al, 2007-2012
Work for Block (0,0)
Work for Block (0,0)
Tiled Matrix Multiplication Kernel
```c
__global__ void MatrixMulKernel(float* Md, float* Nd, float* Pd, int Width)
{
1. __shared__ float Mds[TILE_WIDTH][TILE_WIDTH];
2. __shared__ float Nds[TILE_WIDTH][TILE_WIDTH];
3. int bx = blockIdx.x; int by = blockIdx.y;
4. int tx = threadIdx.x; int ty = threadIdx.y;
// Identify the row and column of the Pd element to work on
5. int Row = by * TILE_WIDTH + ty;
6. int Col = bx * TILE_WIDTH + tx;
7. float Pvalue = 0;
// Loop over the Md and Nd tiles required to compute the Pd element
8. for (int m = 0; m < Width/TILE_WIDTH; ++m) {
// Collaborative loading of Md and Nd tiles into shared memory
9. Mds[ty][tx] = Md[Row*Width + (m*TILE_WIDTH + tx)];
10. Nds[ty][tx] = Nd[(m*TILE_WIDTH + ty)*Width + Col];
11. __syncthreads();
12. for (int k = 0; k < TILE_WIDTH; ++k)
13. Pvalue += Mds[ty][k] * Nds[k][tx];
14. __syncthreads();
}
15. Pd[Row*Width + Col] = Pvalue;
}
```
© David Kirk/NVIDIA and Wen-mei W. Hwu, 2007-2010
ECE408, University of Illinois, Urbana Champaign
// Setup the execution configuration
dim3 dimBlock(TILE_WIDTH, TILE_WIDTH);
dim3 dimGrid(Width / TILE_WIDTH,
Width / TILE_WIDTH);
First-order Size Considerations
• Each **thread block** should have many threads
– TILE_WIDTH of 16 gives 16*16 = 256 threads
• There should be many thread blocks
– A 1024*1024 Pd gives 64*64 = 4096 Thread Blocks
– TILE_WIDTH of 16 gives each SM 3 blocks, 768 threads (full capacity)
• Each thread block performs 2*256 = 512 float loads from global memory for 256 * (2*16) = 8,192 mul/add operations (lines 9-14)
– Memory bandwidth no longer a limiting factor
Tiled Multiply
• Each block computes one square sub-matrix $P_{d_{sub}}$ of size $\text{TILE_WIDTH}$
• Each thread computes one element of $P_{d_{sub}}$
Shared Memory and Threading
• Each SM in G80 has 16KB shared memory
– SM size is implementation-dependent!
– For TILE_WIDTH = 16, each thread block uses 2*256*4B = 2KB of shared memory.
– The SM can potentially have up to 8 Thread Blocks actively executing
• This allows up to 8*512 = 4,096 pending loads. (2 per thread, 256 threads per block)
• The threading model limits the number of thread blocks to 3 so shared memory is not the limiting factor here
– The next TILE_WIDTH 32 would lead to 2*32*32*4B= 8KB shared memory usage per thread block, allowing only up to two thread blocks active at the same time
• Using 16x16 tiling, we reduce the accesses to the global memory by a factor of 16
– The 86.4B/s bandwidth can now support (86.4/4)*16 = 347.6 GFLOPS
• Each SM in Fermi has 16KB or 48KB shared memory
– Configurable vs L1 cache, total 64KB
Tiling Size Effects
![Tiling Size Effects Graph]
- **GFLOPS**
- **tiled only**
- **tiled & unrolled**
- **not tiled**
- **4x4 tiles**
- **8x8 tiles**
- **12x12 tiles**
- **16x16 tiles**
© David Kirk/NVIDIA and Wen-mei W. Hwu, 2007-2010
ECE408, University of Illinois, Urbana Champaign
Memory Resources as Limit to Parallelism
- Effective use of different memory resources reduces the number of accesses to global memory.
- These resources are finite!
- The more memory locations each thread requires → the fewer threads an SM can accommodate → what if each thread required 22 registers and each block had 256 threads?
<table>
<thead>
<tr>
<th>Resource</th>
<th>Per GT200 SM</th>
<th>Full Occupancy on GT200</th>
</tr>
</thead>
<tbody>
<tr>
<td>Registers</td>
<td>16384</td>
<td>( \leq \frac{16384}{768} ) threads = 21 per thread</td>
</tr>
<tr>
<td><strong>shared</strong> Memory</td>
<td>16KB</td>
<td>( \leq \frac{16KB}{8} ) blocks = 2KB per block</td>
</tr>
</tbody>
</table>
Final Thoughts on Memory
• Effective use of CUDA memory hierarchy decreases bandwidth consumption to increase throughput
• Use \texttt{__shared__} memory to eliminate redundant loads from global memory
– Use \texttt{__syncthreads} barriers to protect \texttt{__shared__} data
– Use atomics if access patterns are sparse or unpredictable
• Optimization comes with a development cost
• Memory resources ultimately limit parallelism
Thread Execution and Divergence
Scheduling Blocks onto SMs
- HW Schedules thread blocks onto available SMs
- No guarantee of ordering among thread blocks
- HW will schedule thread blocks as soon as a previous thread block finishes
Mapping of Thread Blocks
- Each thread block is mapped to one or more warps
- The hardware schedules each warp independently
Thread Block N (128 threads) → TB N W1 → TB N W2 → TB N W3 → TB N W4
Thread Scheduling Example
- SM implements zero-overhead warp scheduling
- At any time, only one of the warps is executed by SM
- Warps whose next instruction has its inputs ready for consumption are eligible for execution
- Eligible warps are selected for execution on a prioritized scheduling policy
- All threads in a warp execute the same instruction when selected

TB = Thread Block, W = Warp
Control Flow Divergence
• What happens if you have the following code?
```c
if (foo(threadIdx.x))
{
do_A();
}
el
```
Control Flow Divergence
From Fung et al. MICRO ‘07
Control Flow Divergence
- Nested branches
```c
if (foo(threadIdx.x))
{
if (bar(threadIdx.x))
do_A();
else
do_B();
}
else
do_C();
```
Control Flow Divergence
Control Flow Divergence
- You don’t have to worry about divergence for correctness (*)
- You might have to think about it for performance
- Depends on your branch conditions
* Mostly true, except corner cases (for example intra-warp locks)
Control Flow Divergence
• Performance drops off with the degree of divergence
```c
switch(threadIdx.x % N) {
case 0:
...
...
case 1:
...
...
}
```
Atomics
The Problem
• How do you do global communication?
• Finish a grid and start a new one
Global Communication
• Finish a kernel and start a new one
• All writes from all threads complete before a kernel finishes
stepl<grid1,blk1>>>(...);
// The system ensures that all
// writes from step1 complete.
step2<grid2,blk2>>>(...);
Global Communication
• Would need to decompose kernels into before and after parts
Race Conditions
• Or, write to a predefined memory location
– Race condition! Updates can be lost
Race Conditions
threadId: 0
// vector[0] was equal to 0
vector[0] += 5;
...
a = vector[0];
threadId: 1917
vector[0] += 1;
...
a = vector[0];
• What is the value of $a$ in thread 0?
• What is the value of $a$ in thread 1917?
Race Conditions
• Thread 0 could have finished execution before 1917 started
• Or the other way around
• Or both are executing at the same time
• Answer: not defined by the programming model, can be arbitrary
• CUDA provides atomic operations to deal with this problem
Atomics
• An atomic operation guarantees that only a single thread has access to a piece of memory while an operation completes
• The name atomic comes from the fact that it is uninterruptable
• No dropped data, but ordering is still arbitrary
• Different types of atomic instructions
• atomic{Add, Sub, Exch, Min, Max, Inc, Dec, CAS, And, Or, Xor}
• More types in newer architectures
Compare and Swap
```c
int compare_and_swap(int* register,
int oldval, int newval)
{
int old_reg_val = *register;
if(old_reg_val == oldval)
*register = newval;
return old_reg_val;
}
```
- Most general type of atomic
- Can emulate all others with CAS
Example: Histogram
// Determine frequency of colors in a picture
// colors have already been converted into ints
// Each thread looks at one pixel and increments
// a counter atomically
__global__ void histogram(int* color,
int* buckets)
{
int i = threadIdx.x
+ blockDim.x * blockIdx.x;
int c = colors[i];
atomicAdd(&buckets[c], 1);
}
Example: Workqueue
// For algorithms where the amount of work per item
// is highly non-uniform, it often makes sense
// to continuously grab work from a queue
__global__
void workq(int* work_q, int* q_counter,
int* output, int queue_max)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int q_index = atomicInc(q_counter, queue_max);
int result = do_work(work_q[q_index]);
output[i] = result;
}
Atoms
- Atomics are slower than normal load/store
- You can have the whole machine queuing on a single location in memory
- Atomics unavailable on G80
Example: Global Min/Max (Naive)
// If you require the maximum across all threads
// in a grid, you could do it with a single global
// maximum value, but it will be VERY slow
__global__
void global_max(int* values, int* gl_max)
{
int i = threadIdx.x
+ blockDim.x * blockIdx.x;
int val = values[i];
atomicMax(gl_max, val);
}
Example: Global Min/Max (Better)
// introduce intermediate maximum results, so that
// most threads do not try to update the global max
__global__
void global_max(int* values, int* max,
int *regional_maxes,
int num_regions)
{
// i and val as before ...
int region = i % num_regions;
if(atomicMax(®_max[region],val) < val)
{
atomicMax(max,val);
}
}
Global Min/Max
- Single value causes serial bottleneck
- Create hierarchy of values for more parallelism
- Performance will still be slow, so use judiciously
Atomics - Summary
• Can’t use normal load/store for inter-thread communication because of **race conditions**
• Use **atomic instructions** for sparse and/or unpredictable global communication
• **Decompose data** (very limited use of single global sum/max/min/etc.) for more parallelism
|
{"Source-Url": "https://www.cs.stevens.edu/~mordohai/classes/cs677_s19/cs677s19_week2.pdf", "len_cl100k_base": 9703, "olmocr-version": "0.1.49", "pdf-total-pages": 93, "total-fallback-pages": 0, "total-input-tokens": 144857, "total-output-tokens": 12873, "length": "2e13", "weborganizer": {"__label__adult": 0.0004258155822753906, "__label__art_design": 0.0006089210510253906, "__label__crime_law": 0.0003829002380371094, "__label__education_jobs": 0.0021610260009765625, "__label__entertainment": 0.00011247396469116212, "__label__fashion_beauty": 0.0002002716064453125, "__label__finance_business": 0.00022542476654052737, "__label__food_dining": 0.000469207763671875, "__label__games": 0.0012311935424804688, "__label__hardware": 0.0057220458984375, "__label__health": 0.0005435943603515625, "__label__history": 0.0004203319549560547, "__label__home_hobbies": 0.0001857280731201172, "__label__industrial": 0.001178741455078125, "__label__literature": 0.0002390146255493164, "__label__politics": 0.0003633499145507813, "__label__religion": 0.0008554458618164062, "__label__science_tech": 0.09814453125, "__label__social_life": 0.0001100301742553711, "__label__software": 0.006717681884765625, "__label__software_dev": 0.8779296875, "__label__sports_fitness": 0.0004949569702148438, "__label__transportation": 0.000995635986328125, "__label__travel": 0.0002739429473876953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 31286, 0.02755]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31286, 0.35839]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31286, 0.69208]], "google_gemma-3-12b-it_contains_pii": [[0, 173, false], [173, 347, null], [347, 619, null], [619, 1150, null], [1150, 1514, null], [1514, 1810, null], [1810, 2359, null], [2359, 2724, null], [2724, 2900, null], [2900, 3153, null], [3153, 3185, null], [3185, 3746, null], [3746, 4025, null], [4025, 4598, null], [4598, 4812, null], [4812, 5211, null], [5211, 5577, null], [5577, 5912, null], [5912, 6507, null], [6507, 8455, null], [8455, 8484, null], [8484, 8980, null], [8980, 9240, null], [9240, 9702, null], [9702, 10072, null], [10072, 10419, null], [10419, 10787, null], [10787, 10801, null], [10801, 11053, null], [11053, 11720, null], [11720, 12430, null], [12430, 13020, null], [13020, 13271, null], [13271, 13731, null], [13731, 14173, null], [14173, 14678, null], [14678, 15221, null], [15221, 15738, null], [15738, 15925, null], [15925, 16484, null], [16484, 16937, null], [16937, 17158, null], [17158, 17464, null], [17464, 17830, null], [17830, 18307, null], [18307, 18349, null], [18349, 18910, null], [18910, 19389, null], [19389, 19626, null], [19626, 19784, null], [19784, 19800, null], [19800, 20559, null], [20559, 20848, null], [20848, 20869, null], [20869, 21278, null], [21278, 21691, null], [21691, 21712, null], [21712, 21733, null], [21733, 22815, null], [22815, 22956, null], [22956, 23427, null], [23427, 23582, null], [23582, 24455, null], [24455, 24744, null], [24744, 25349, null], [25349, 25784, null], [25784, 25816, null], [25816, 26020, null], [26020, 26216, null], [26216, 26641, null], [26641, 26764, null], [26764, 26816, null], [26816, 26979, null], [26979, 27003, null], [27003, 27247, null], [27247, 27436, null], [27436, 27436, null], [27436, 27444, null], [27444, 27531, null], [27531, 27770, null], [27770, 27854, null], [27854, 27955, null], [27955, 28184, null], [28184, 28455, null], [28455, 28843, null], [28843, 29119, null], [29119, 29506, null], [29506, 29932, null], [29932, 30084, null], [30084, 30425, null], [30425, 30837, null], [30837, 30996, null], [30996, 31286, null]], "google_gemma-3-12b-it_is_public_document": [[0, 173, true], [173, 347, null], [347, 619, null], [619, 1150, null], [1150, 1514, null], [1514, 1810, null], [1810, 2359, null], [2359, 2724, null], [2724, 2900, null], [2900, 3153, null], [3153, 3185, null], [3185, 3746, null], [3746, 4025, null], [4025, 4598, null], [4598, 4812, null], [4812, 5211, null], [5211, 5577, null], [5577, 5912, null], [5912, 6507, null], [6507, 8455, null], [8455, 8484, null], [8484, 8980, null], [8980, 9240, null], [9240, 9702, null], [9702, 10072, null], [10072, 10419, null], [10419, 10787, null], [10787, 10801, null], [10801, 11053, null], [11053, 11720, null], [11720, 12430, null], [12430, 13020, null], [13020, 13271, null], [13271, 13731, null], [13731, 14173, null], [14173, 14678, null], [14678, 15221, null], [15221, 15738, null], [15738, 15925, null], [15925, 16484, null], [16484, 16937, null], [16937, 17158, null], [17158, 17464, null], [17464, 17830, null], [17830, 18307, null], [18307, 18349, null], [18349, 18910, null], [18910, 19389, null], [19389, 19626, null], [19626, 19784, null], [19784, 19800, null], [19800, 20559, null], [20559, 20848, null], [20848, 20869, null], [20869, 21278, null], [21278, 21691, null], [21691, 21712, null], [21712, 21733, null], [21733, 22815, null], [22815, 22956, null], [22956, 23427, null], [23427, 23582, null], [23582, 24455, null], [24455, 24744, null], [24744, 25349, null], [25349, 25784, null], [25784, 25816, null], [25816, 26020, null], [26020, 26216, null], [26216, 26641, null], [26641, 26764, null], [26764, 26816, null], [26816, 26979, null], [26979, 27003, null], [27003, 27247, null], [27247, 27436, null], [27436, 27436, null], [27436, 27444, null], [27444, 27531, null], [27531, 27770, null], [27770, 27854, null], [27854, 27955, null], [27955, 28184, null], [28184, 28455, null], [28455, 28843, null], [28843, 29119, null], [29119, 29506, null], [29506, 29932, null], [29932, 30084, null], [30084, 30425, null], [30425, 30837, null], [30837, 30996, null], [30996, 31286, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31286, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31286, null]], "pdf_page_numbers": [[0, 173, 1], [173, 347, 2], [347, 619, 3], [619, 1150, 4], [1150, 1514, 5], [1514, 1810, 6], [1810, 2359, 7], [2359, 2724, 8], [2724, 2900, 9], [2900, 3153, 10], [3153, 3185, 11], [3185, 3746, 12], [3746, 4025, 13], [4025, 4598, 14], [4598, 4812, 15], [4812, 5211, 16], [5211, 5577, 17], [5577, 5912, 18], [5912, 6507, 19], [6507, 8455, 20], [8455, 8484, 21], [8484, 8980, 22], [8980, 9240, 23], [9240, 9702, 24], [9702, 10072, 25], [10072, 10419, 26], [10419, 10787, 27], [10787, 10801, 28], [10801, 11053, 29], [11053, 11720, 30], [11720, 12430, 31], [12430, 13020, 32], [13020, 13271, 33], [13271, 13731, 34], [13731, 14173, 35], [14173, 14678, 36], [14678, 15221, 37], [15221, 15738, 38], [15738, 15925, 39], [15925, 16484, 40], [16484, 16937, 41], [16937, 17158, 42], [17158, 17464, 43], [17464, 17830, 44], [17830, 18307, 45], [18307, 18349, 46], [18349, 18910, 47], [18910, 19389, 48], [19389, 19626, 49], [19626, 19784, 50], [19784, 19800, 51], [19800, 20559, 52], [20559, 20848, 53], [20848, 20869, 54], [20869, 21278, 55], [21278, 21691, 56], [21691, 21712, 57], [21712, 21733, 58], [21733, 22815, 59], [22815, 22956, 60], [22956, 23427, 61], [23427, 23582, 62], [23582, 24455, 63], [24455, 24744, 64], [24744, 25349, 65], [25349, 25784, 66], [25784, 25816, 67], [25816, 26020, 68], [26020, 26216, 69], [26216, 26641, 70], [26641, 26764, 71], [26764, 26816, 72], [26816, 26979, 73], [26979, 27003, 74], [27003, 27247, 75], [27247, 27436, 76], [27436, 27436, 77], [27436, 27444, 78], [27444, 27531, 79], [27531, 27770, 80], [27770, 27854, 81], [27854, 27955, 82], [27955, 28184, 83], [28184, 28455, 84], [28455, 28843, 85], [28843, 29119, 86], [29119, 29506, 87], [29506, 29932, 88], [29932, 30084, 89], [30084, 30425, 90], [30425, 30837, 91], [30837, 30996, 92], [30996, 31286, 93]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31286, 0.10581]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
30ef0cd3b26d920e5f6ae059912d02e0a46fd833
|
Chapter 7
Definition and Presentation of Terms
NUPRL offers users an opportunity to extend the basic language of type theory by introducing new, abstract terms whose meaning is defined in terms of existing language constructs. In addition to that users may also modify the visual appearance of abstract terms and adjust the presentation of formal material without changing the formal content itself, which makes it possible to use familiar notation or to present the same material differently to different target groups.
Users can create several kinds of library objects for this purpose. Abstractions are used to introduce the abstract definition of a new term, display forms define the textual presentation of abstract terms, and precedence objects assign precedences for terms to control automatic parenthesization. In Section 4.3.2.2 we briefly described how to create abstractions and display forms using the navigator’s AddDef* button. In this chapter we will describe the contents and features of abstractions, display forms, and precedences as well as editor support for defining them.
7.1 Abstractions
Abstractions are terms that are definitionally equal to other terms. In NUPRL they may be defined in terms of language primitives and other abstractions, but the dependency graph for abstractions should be acyclic. In particular, an abstraction not depend on itself. Recursive definitions can be introduced using the AddRecDef button as described in Section 4.3.2.2.
Abstraction definitions have form
\[ \text{lhs} \equiv \text{rhs} \]
where \( \text{lhs} \) and \( \text{rhs} \) are pattern terms that may contain free variables. The latter are implicitly universally quantified. When NUPRL unfolds some \( \text{lhs-inst} \) instance of \( \text{lhs} \), it first matches this instance against the pattern \( \text{lhs} \) and generates bindings for the free variables of \( \text{lhs} \) accordingly. It then applies these bindings to the free variables in \( \text{rhs} \) to calculate the term \( \text{rhs-inst} \) into which \( \text{lhs-inst} \) unfolds. Therefore, all free variables of \( \text{rhs} \) must also occur free in since otherwise unfolding a definition would yield a term with unbound variables. An example of an abstraction object is given below.
\[
\begin{array}{l}
\text{- ABS: int}\_\text{seg} \\
\{i..j\} \equiv \{k:Z \mid i \leq k < j\}
\end{array}
\]
1This includes user defined terms, primitive terms of NUPRL’s type theory, and even the terms used for describing NUPRL editing features such as the navigator, proof terms, or the appearance of abstractions and display forms.
The abstraction defines a type of segments of integers. The abstraction object `int_seg` already
consults a display form in the presentation of the left hand side of the definition. The structure
of the left hand side becomes more readily apparent if we write it in uniform syntax (which can
be made visible by exploding the term as described in Section 5.4.5).
\[ f_{i..j} \] is `int_seg(i;j)`, a term with opid `int_seg`, no parameters, and two subterms. An instance of the left hand side is
\[ f_{0..10} \], which would unfold to \[ f_{k:Z \mid 0 \leq k < 10} \].
Just as abstractions can be unfolded by applying their definition left-to-right, so instances of
their right hand sides can be folded up to be instances of their left hand sides. Folding, however does
not always work, as information can be lost in the unfolding process. For instance, an abstraction
can have variables and parameters that are not used in its definition but are only used for “book-
keeping purposes”. In this case the variables and parameters only occur on the left hand side of the
definition and would have to be inferred when folding up a specific instance of the right hand side.
7.1.1 Bindings in Abstractions
In additions to ordinary variables, abstractions can have binding structure. Consider, for instance,
the definition of the `unique existence` quantifier below.
\[ \exists!x:T. P[x] = \exists x:T. P[x] \land (\forall y:T. P[y] \Rightarrow y=x \in T) \]
Here \( x \) represents a variable that becomes bound in the term \( P[x] \) and this binding structure
must be mapped from the abstract term \( \exists!x:T; x\cdot P[x] \) to its definition
First-order matching and substitution are inadequate for handling terms with binding structure,
since they consider variables to be independent from each other and thus cannot express the
dependency between \( x \) and \( P[x] \). NUPRL’s therefore uses second-order matching and substitution
functions to handle abstractions with binding variables in a systematic way.
A second-order binding is a binding \( v \mapsto x_1, \ldots, x_n.t \) of a second-order variable \( v \) to a
second-order term \( x_1, \ldots, x_n.t \). A second-order variable is essentially an identifier as with normal
variables, but it also has an associated arity \( n \geq 0 \). Second-order terms are a generalization of terms
that can be thought of as ‘terms with holes’, i.e. as terms with missing subtrees. They can be
represented by bound-terms such as \( x_1, \ldots, x_n.t \), where the binding variables are place-holders for
the missing subtrees. In a second-order binding \( v \mapsto x_1, \ldots, x_n.t \), the arity of \( v \) must be equal to \( n \).
An instance of a second-order variable \( v \) with arity \( n \) is a term \( v[a_1; \ldots; a_n] \), where \( a_1, \ldots, a_n \)
are terms, also called the arguments of \( v \). A second-order substitution is a list of second-order
bindings. The result of applying the binding \( [v \mapsto w_1, \ldots, w_n.t_{w_1}, \ldots, w_n] \) to the variable instance
\( v[a_1; \ldots; a_n] \), is the term \( t_{a_1}, \ldots, a_n \) – the arguments of the instance of the second-order variable fill
the holes of the second-order term.
In our above example, \( P \) is a second order variable with arity 1, and the terms \( P[x] \) and \( P[y] \) are
second-order-variable instances. Consider unfolding an instance of the left-hand side, say the term
\( \exists!i:Z. \ i=0 \in Z \). The substitution generated by matching this against \( \exists!x:T. P[x] \), would be
\[ [P \mapsto i.\ i=0 \in Z ; T \mapsto Z ] \]
and the result of applying this to the right hand side of the definition would be
\[ \exists x:T. \ x=0 \in Z \land (\forall y:Z. \ y=0 \in Z \Rightarrow y=x \in Z) \]
2Roughly, second-order terms are like functions on terms but there are subtle differences between the two concepts.
Actually, the matching and substitution functions used by NUPRL are a little smarter than shown above, as they try to maintain names of binding variables. The result one would get in NUPRL would be
\[ \exists i : T. \ i = 0 \in \mathbb{Z} \ \land \ (\forall y : \mathbb{Z}. \ y = 0 \in \mathbb{Z} \ \Rightarrow \ y = i \in \mathbb{Z}) \].
NUPRL does not allow nested bindings on the left-hand side of abstraction definitions. All variables must either be first-order or second-order variables with first-order variable arguments.
### 7.1.2 Parameters in Abstractions
Abstractions can also contain *meta-parameters*, i.e. placeholders for parameters that matching and substitution treat as variables. We usually indicate that a parameter is meta by prefixing it with a \$ sign. For example, we might define an abstraction `label\{x:t,i:n\}` as shown below
```
- ABS: label
label\{tok:t,nat:n\}\() \Rightarrow \langle tok, nat >
```
Meta-parameters make it possible to map parameters in newly defined abstractions onto parameters of existing terms. In the above example labels are defined as pairs of tokens and natural numbers and the parameter \$tok\$ is mapped onto the parameter of the term `token` while the parameter \$nat\$ is mapped onto the parameter of the term `natural number`, which is revealed when the right-hand side of the definition is exploded into `pair(token\{tok:t\};natural\{nat:n\})`.
Level-expression variables occurring in level-expression parameters of abstraction definitions are always considered meta-parameters, so there is no need to designate them explicitly. However, indicating meta-parameters explicitly makes it easier to identify them as such.
In general, the term on the left-hand side of an abstraction can have a mixture of normal and meta-parameters. You can define a family of abstractions which differ only in the constant value of some parameter. However, it is an error to make two abstraction definitions with left-hand sides that have some common instance.
### 7.1.3 Attributed Abstractions
A recently added feature of abstraction definitions is an optional list of *attributes* or *conditions*. An attribute is simply an alpha-numeric label associated with the abstraction and the general form of an abstraction with conditions \(c_1, \ldots, c_n\) is:
\[(c_1, \ldots, c_n) : \text{lhs} \Rightarrow \text{rhs}\]
Abstraction conditions can be used to hold information about abstractions that may be useful to tactics and other parts of the NUPRL system. They could, for instance, be used to group abstractions into categories, and when doing a proof, one could ask for all abstractions in a given category to be treated in a particular way, e.g. to unfold all abstractions of a category “notational abbreviations”.
### 7.1.4 Editor Support
In this section, we describe the editor support for abstraction objects. An abstraction can be viewed by opening it with the navigator (Section 4.3.1.1) or by using the `VIEW-ABSTRACTION` command (\(\langle C-X\rangle ab\)) on a term containing an instance of it (Section 5.7). The following commands and key sequences may be used for editing abstractions.
<table>
<thead>
<tr>
<th>Key</th>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>(C-M-I)</td>
<td>INITIALIZE</td>
<td>initialize object / condition</td>
</tr>
<tr>
<td>so_varn</td>
<td>INSERT-TERM so_varn</td>
<td>insert second order var with n args</td>
</tr>
<tr>
<td>(C-M)</td>
<td>CYCLE-META-STATUS</td>
<td>make parameter meta / normal</td>
</tr>
<tr>
<td>(C-M-S)</td>
<td>SELECT-TERM-OPTION</td>
<td>open condition sequence</td>
</tr>
<tr>
<td>(C-O)</td>
<td>OPEN-SEQ-TO-LEFT</td>
<td>open slot in cond seq to left</td>
</tr>
<tr>
<td>(M-O)</td>
<td>OPEN-SEQ-TO-RIGHT</td>
<td>open slot in cond seq to right</td>
</tr>
</tbody>
</table>
Since most abstraction objects are created using the **AddDef** mechanism described in Section 4.3.2.2, the left and right hand side of the abstraction is already present when the object is opened. In the rare case that the abstraction object was created with the **MkObj** command button (Section 4.3.2.1) it will contain an empty term slot when it is first visited, which must be initialized before a definition can be entered.
The **INITIALIZE** command will create an uninstatiated abstraction definition term, which looks like:
\[
[ab \text{ lhs}] == [ab \text{ rhs}]
\]
To enter the abstract term on the left hand side of the definition, one has to provide its object identifier, its parameters, and a list of its subterms together with the variables to be bound in these subterms. Ways to create new terms with the term-editor are described in Sections 5.4.4 and 5.4.5. The term for the right hand side of the definition is entered in the usual structural top-down fashion of the term-editor as explained in Section 5.4.
**so_varn** has to be used to enter second order variable instances on the left and right hand sides of the definition. This will insert a term of the form \(\text{variable}(x:v)(a_1;\ldots;a_n)\), where \(x\) is the variable’s name, and \(n > 0\) is a natural number. The library display form object for this term is named **so_varn** so this family of names can be used to reference them.
Note that abstraction objects are the only places where these second-order variable instances are used. When writing propositions, second-order variable instances are simulated using the **so_apply** abstraction.
**CYCLE-META-STATUS** converts a parameter into a meta-parameter if the text cursor is in the parameter’s text slot. If the parameter is already meta, using this twice will cycle its status back to being a normal parameter.
**SELECT-TERM-OPTION** enables a user to add conditions to an abstraction. By default, an abstraction definition term has an empty condition sequence as a subterm, which is hidden by the display form for abstractions. Moving the term cursor over the whole abstraction term and using **SELECT-TERM-OPTION** will add an empty term slot for a condition. The condition term is much like the term for variables; it has a single text slot, and otherwise no other display characters. To get additional slots for condition terms one may use **OPEN-SEQ-TO-LEFT** or **OPEN-SEQ-TO-RIGHT**.
### 7.2 Term Display
Display form objects are used to control the visual presentation of formal mathematical concepts. They define how a term shall appear when it is being displayed on the screen or printed on paper. This enables users to present formal content within a variety of notations without having to change the internal logical representation of these terms. Display forms are commonly created whenever a definition is introduced using the **AddDef** mechanisms (Section 4.3.2.2), but they may also be added for existing abstractions as well as for the primitive terms of the library.
102
In Nuprl the presentation of all formal content, including the appearance of the navigator, the editor, sequents, and proofs is controlled by display forms and may be adjusted according to the preferences of a user. Even the mechanisms for editing and presenting display forms themselves may be modified. The display forms for the quantifiers (all\_df, exists\_df) and the logical connectives (and\_df, or\_df, ...), for instance, appear as “display form generators”.
The top level structure of a display form object is summarized by the grammar shown in Figure 7.1. An object contains one or more display form definitions. Each definition has a right-hand-side term to which the display form applies, and a sequence of formats that specify how to display the term. A definition also has an optional sequence of attributes that specify extra information about the definition.
Usually, all the definitions in one object refer to a closely related set of terms. When choosing a display form to use for a term, the layout algorithm tries definitions in a backward order, so definitions are usually ordered from more general to more specific.
### 7.2.1 Editing Display Form Objects
Since most display forms are created using the AddDef* mechanism described in Section 4.3.2.2, a right-hand-side term, a standard sequence of formats, and an alias attribute (see Section 7.2.4 below) are already present when the object is opened. If the object was created with the MkObj* command (Section 4.3.2.1) it will contain an empty term slot, which must be initialized before a display form definition can be entered.
The command (C-M-I) will create an initial display form definition, which looks like:
\[
== [\text{rhs}]
\]
To get additional slots for display form definitions one may use the commands (C-0) and (M-0).
An initial display form definition has an empty attribute sequence as a subterm, which is hidden by the display form for display form definitions. Moving the term cursor over the whole term and using (C-M-S) will add an empty term slot for an attribute.
### 7.2.2 Right-hand-side Terms
The right-hand-side term is a pattern. A definition applies to some term \( t \) if \( t \) is an instance of the right-hand-side term. The display definition matcher has a notion of meta-variable different from that of Nuprl’s usual matching routines; it has 3 kinds of meta-variable: meta-parameters, meta-bound-variables, and meta-terms.\(^3\) Meta-parameters and meta-bound-variables correspond to text slots on the left-hand side of a definition, and meta-terms correspond to term slots.
---
\(^3\)The meta-parameters are different from those used in abstraction definitions. To be clear, we sometimes call those ones abstraction-meta-variables and the ones in display definitions, display-meta-variables.
The right-hand-side term is restricted to being a term whose subterms are either constant terms, i.e. terms with no meta-variables, or meta-terms. To enter a meta-term into a term slot one has to use the name `mterm`. To turn parameters and variable into meta-parameters or meta-bound-variables, position a text cursor in the appropriate parameter or bound variable slot and give the `cycle-meta-status` command `(C-M)` (twice). Display-meta-variables are readily recognized because they have `<>` as delimiters.
The rhs right-hand-side term may also contain normal parameters, bound variables and variable terms. These are treated like constants: for a definition to be applicable, they must match exactly.
### 7.2.3 Format Sequences
Format sequences are text sequences that may contain slots for meta-variables and commands for controlling the layout of formal material through insertion of optional spaces, line breaking, and indentation. Except for text strings, all formats must be entered into term slots, which may be created as described in Section 5.4.2.
The various kinds of formats are summarized in the table below. The `Name` column gives the name that has to be entered into a term slot to create the format, while the `Display` column describes how the format will be presented within a display form definition.
<table>
<thead>
<tr>
<th>Name</th>
<th>Display</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>slot</td>
<td><code><id:ph></code></td>
<td>text slot format</td>
</tr>
<tr>
<td>lslot</td>
<td><code><id:ph:L></code></td>
<td>term slot format</td>
</tr>
<tr>
<td>eslot</td>
<td><code><id:ph:E></code></td>
<td>term slot format</td>
</tr>
<tr>
<td>sslot</td>
<td><code><id:ph:*></code></td>
<td>term slot format</td>
</tr>
<tr>
<td>pushm</td>
<td><code>{→i}</code></td>
<td>push margin</td>
</tr>
<tr>
<td>popm</td>
<td><code>{←}</code></td>
<td>pop margin</td>
</tr>
<tr>
<td>break</td>
<td><code>{\a}</code></td>
<td>break</td>
</tr>
<tr>
<td>sbreak</td>
<td><code>{\?a}</code></td>
<td>soft break</td>
</tr>
<tr>
<td>hzone</td>
<td><code>{[HARD]}</code></td>
<td>start hard break zone</td>
</tr>
<tr>
<td>szone</td>
<td><code>{[SOFT]}</code></td>
<td>start soft break zone</td>
</tr>
<tr>
<td>lzone</td>
<td><code>{[LIN]}</code></td>
<td>start linear break zone</td>
</tr>
<tr>
<td>ezone</td>
<td><code>{}</code></td>
<td>end break zone</td>
</tr>
<tr>
<td>space</td>
<td><code>{Space}</code></td>
<td>optional space</td>
</tr>
</tbody>
</table>
#### 7.2.3.1 Slot Formats
Slot formats are placeholders for the children of a display form instance. Text slots are generally used for meta-parameters and meta-bound-variables, while term slot formats contain meta-terms.
The `id` in a slot format is the name of the slot. The slot corresponds to the meta-variable of the right-hand-side term with the same name. `ph` is place-holder text, which will appear (enclosed within `[]`’s) in the slot whenever it is uninstantiated in some instance of the display form. The `L,E` and `*` options on the term slot formats control parenthesization of the slot and are discussed in Section 7.2.4.2.
#### 7.2.3.2 Margins
The margin control format `{→i}`, where `i ≥ 0`, pushes a new left margin `i` characters to the right of the format position onto the `margin stack`. The layout algorithm uses the top of the margin stack
to decide the column to start laying out at after a line break. To create the format, enter \texttt{pushm}
into a term slot and edit the number 0 in the format $\{\rightarrow 0\}$ accordingly.
The margin control format $\{\leftarrow\} (\texttt{popm})$ pops the current margin off the top of the margin stack and restores the left margin to a previous margin. Usually display forms should have matching \texttt{pushm}'s and \texttt{popm}'s.
### 7.2.3.3 Line Breaking
Line-breaking formats divide the display into nested \textit{break zones}. There are 3 kinds of break zone: \textit{hard}, \textit{linear}, and \textit{soft}. The effect of the \textit{break} format $\{\backslash a\}$ depends on the break zone kind:
- In a \textit{hard} zone, $\{\backslash a\}$ always causes a line break.
- In a \textit{soft} zone, either none or all of the $\{\backslash a\}$ are taken.
- In a \textit{linear} zone, $\{\backslash a\}$ never causes a line break. Instead, its position is filled by the text string $a$, which usually is a sequence of blank characters.
Break zones are started and ended by zone delimiters. Display form format sequences should usually include matching start and end zone formats. There is one end delimiter $\{\}\$ (\texttt{ezone}) for all kinds of zones. Each kind of zone has its own start delimiter:
- $\{[\mbox{HARD}]\}$ (\texttt{hzone}) starts a hard zone.
- $\{[\mbox{SOFT}]\}$ (\texttt{szone}) starts a soft zone.
- $\{[\mbox{LIN}]\}$ (\texttt{lzone}) starts a linear zone.
A linear zone is special in that all zones nested inside are also forced to be linear. Therefore a linear zone contains no line-breaks and always is laid out on a single line. If a linear zone doesn’t fit on a single line, the layout algorithm chooses subterms to elide (see Section 5.3) to try and make it fit.
When laying out a soft zone, the layout algorithm first tries treating it as a linear zone. If that would result in any elision, then it treats the zone as a hard zone.
The \textit{soft break} format $\{\backslash ?a\}$ (\texttt{sbreak}) is similar to the break format but is not as sensitive to the zone kind. Soft breaks in linear zones are never taken, but otherwise, the layout algorithm uses a separate procedure to choose which soft breaks to take and which not. This procedure uses various heuristics to try and layout a term sensibly in a given size window with at little elision of subterms as possible.
### 7.2.3.4 Optional Spaces
The \textit{space} format $\{\texttt{Space}\}$ inserts a single blank character if the character before it isn’t already a space. Otherwise it has no effect.
### 7.2.4 Attributes
Attributes specify extra information about display form definitions. By default, display form definitions are created with a right-hand-side term, a standard sequence of formats, and a single alias attribute. Moving the cursor over the whole attribute term and using (C-0) or (M-0) will create additional attribute slots to the left or right of this attribute.
Possible display form attributes are summarized in the table below. The \textit{Name} column gives the name that has to be entered into a term slot to create the attribute, while the \textit{Display} column describes how it will be presented within a display form definition.
The alias attribute provides an alternate name which the input editor recognizes as referring to
the definition. Alternate names are often convenient abbreviations for the full names of definitions.
The iteration attributes ithd and ittl control selection of a definition by the display layout
algorithm. They are used to come up with convenient notations for iterated structures, which are
discussed in Section 7.2.4.1. The parens and prec attributes affect automatic parenthesization,
described in Section 7.2.4.2. The index attribute together with the name of the object containing
a definition give a unique name for the definition. Conditions specify requirements for using a
display form definition. Each condition $c_1, \ldots, c_n$ in the conds term is a term with a alpha-numeric
label associated with the display form definition.
### 7.2.4.1 Iteration
The iteration attributes control choice of display form definition based on immediately-nested
occurrences of the same term. The idea is to group occurrences into iteration families. An iteration
family has a head display form definition and one or more tail definitions. A tail definition can only
be used as an immediate subterm of a head in the same family or another tail in the same family.
Choice of display form is also affected by the use of the iterate variable $#$ as the id of a term slot
format (Section 7.2.3.1). If $#$ is used in some term slot of a definition, then the definition is only
usable if the same term occurs in the subterm slot that uses the #.
The following set of display forms for $\lambda$ abstraction terms, for instance, makes sure that the $\lambda$
character is suppressed on nested occurrences:
\[
\begin{align*}
\lambda<x:var>.<t:term:E> & = \text{lambda}(<x>.<t>) \\
\#Hd A & ::= \lambda<x:var>,<#:term:E> = \text{lambda}(<x>.<#>) \\
\#Tl A & ::= <x:var>.<t:term:E> = \text{lambda}(<x>.<t>) \\
\#Tl A & ::= <x:var>,<#:term:E> = \text{lambda}(<x>.<#>)
\end{align*}
\]
Using these, the term $\text{lambda}(x.\text{lambda}(y.\text{lambda}(z.x)))$ will be displayed as $\lambda x,y,z.x$ instead of $\lambda x.\lambda y.\lambda z.x$.
### 7.2.4.2 Parenthesization
Automatic parenthesization is controlled by certain display definition attributes, term slot options,
and by definition precedences. A precedence is an element in the precedence order, which is
determined by the precedence objects in the NUPRL library. A display form definition is assigned a
precedence by giving it a prec attribute which names some precedence element.
**Precedence Objects** collectively introduce a set of precedence elements, and define a partial
order on them. The components of a precedence object and the names used to enter them by are
summarized in the table below. The prser, preq, and prpar terms are sequence constructors that
may be nested. The standard editor commands described in Section 5.4.2 work on the sequences built with these terms.
<table>
<thead>
<tr>
<th>Name</th>
<th>Display</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>prser</td>
<td>(p_1 \ldots p_n)</td>
<td>serial precedence term</td>
</tr>
<tr>
<td>preq</td>
<td>{p_1 = \ldots = p_n}</td>
<td>equal precedence term</td>
</tr>
<tr>
<td>prpar</td>
<td>[p_1</td>
<td>\ldots</td>
</tr>
<tr>
<td>prel</td>
<td>obname</td>
<td>element of precedence order</td>
</tr>
<tr>
<td>prptr</td>
<td><em>obname</em></td>
<td>precedence object pointer</td>
</tr>
</tbody>
</table>
Object names and object pointers are the primitive elements in a precedence order. Serial precedence terms impose a linear order on a set of precedences \(p_1 \ldots p_n\). Equal precedence term declare all precedences \(p_i\) to be equal in the precedence order. Parallel precedence terms declare all precedences \(p_i\) to have the same “rank” in the precedence order while being unrelated to each other.
Each display form not explicitly associated with any precedence element is implicitly associated with a unique precedence element unrelated to all other precedence elements. The uniqueness implies that two such display forms have unrelated precedence.
Examples of a base set of precedences set up for the current NUPRL theories can be found in the standard theory core_1.
**Automatic Parenthesis Selection.** The parenthesization of a term slot of a display form is controlled by the *parenthesis slot-option*, i.e. the third field of the term slot in the display form definition (see Section 7.2.3.1), by the *parens* attribute of the display form filling that term slot, and by the relative precedences of the term slot and the term filling it. The precedence of a term slot is usually that of the display form containing it, although it is possible to assign precedences to individual slots. The parenthesis control works as follows:
- Term slots are parenthesized only if the filling display form has a *parens* attribute. If this attribute is absent, the slot is never parenthesized. The *parens* attribute must be explicitly added to a display form definition for that definition to ever be parenthesized.
- Term slots are parenthesized unless parenthesization is suppressed by the parenthesis slot-options. These options have the following meanings:
- **L**: Suppress parentheses if the display-form precedence is *less than* the display-form precedence of the term filling the slot.
- **E**: Suppress parentheses if the display-form precedence is *less than or equal to* the display-form precedence of the term filling the slot.
- *****: Always suppress parentheses.
The **L** and **E** options make it possible to represent the conventional precedences and associativity laws of standard infix operators. If they are used in the definitions of display forms for the arithmetic terms \(\text{plus}(a; b)\), and \(\text{times}(a; b)\), then the term \(\text{plus}(a; \text{times}(b; c))\) is displayed as \(a + b \ast c\), but \(\text{times}(a; \text{plus}(b; c))\) is displayed as \(a \ast (b + c)\). Similarly, \(\text{function}(A; \text{function}(B; C))\) is displayed as \(A \rightarrow B \rightarrow C\), but \(\text{function}(\text{function}(A; B); C)\) is displayed as \((A \rightarrow B) \rightarrow C\).
The **L**, **E** and ***** characters in the display of term slot formats are display forms for parenthesization control terms. To change the parenthesis slot-options, one may delete the term and enter the new option using the names shown in the table below.
The parenthesization control terms also allow the specification of the delimiter characters used for parenthesization, and a precedence for the individual slot. No specific editor support has yet been provided for these features.
### 7.2.5 Examples
As an example, we walk through the entry of a display form definition from scratch. We start by creating a new display form object and viewing it. Click the **MkObj** button, enter \texttt{tst\_df} as name and \texttt{disp} as kind, and click the **OK** button.\(^4\)
Open the object by pressing the right arrow or clicking on it with the mouse. This will pop up a window, containing a highlighted empty term slot. Initialize the display form definition by entering \(\langle\text{C-M-I}\rangle\). The window now looks like:
\[
\text{- DISP:: tst\_df}
\]
We begin by entering the right-hand side of the display form. Click \(\Leftrightarrow\) on the \texttt{[rhs]} placeholder, and enter \texttt{.exists\_unique(0;1)} to create a new term (see Section 5.4.4). Do not fill in the variable slot or either of the subterm slots. The definition should now look like:
\[
\text{- DISP:: tst\_df}
\]
Enter \(\Leftrightarrow\) or click \(\Leftrightarrow\) on the left-most term slot and enter \(<T>\), \(<x>\), and \(<P>\) as meta-terms and meta-variable, respectively, by typing \texttt{.mterm\_T j x \textbackslash{}h C-M i \textbackslash{}mterm\_P}. As a result you get:
\[
\text{- DISP:: tst\_df}
\]
To create a display form for the term on the right hand side, click \(\Leftrightarrow\) on the first = to get a text cursor in the empty format sequence on the left-hand side of the definition. Type \(\langle\text{C-#}\rangle\texttt{163!(C-0)slot}\texttt{\_x\_var(C-F)}\rangle\) to generate an \(\exists\) symbol and an exclamation mark as initial text and a slot for the variable \(x\). The definition should now look like:
\[
\text{- DISP:: tst\_df}
\]
Enter a colon, the type slot, a period, a space, and the second term slot:
\(\langle\text{C-0)sslot\_T\_type(C-F)(C-F)\_type(C-F)\_type(C-F)\_type(C-F)\_type(C-F)\rangle\langle\text{C-0)eslot\_P\_prop}\). The definition should now look like:
\(\langle\text{C-0)sslot\_T\_type(C-F)(C-F)\_type(C-F)\_type(C-F)\_type(C-F)\rangle\langle\text{C-0)eslot\_P\_prop}\)
\(^4\)Note that the **MkObj** button is not present in user theories. The only way to create display forms is through the \texttt{AddDef} and \texttt{AddDefDisp} buttons, which already generate a right-hand-side term, a standard sequence of formats, and an alias attribute.
The display form definition is now complete and may be saved by closing the display form object with `C-Z`. However, the definition does not yet include line breaking or parenthesization information. In particular, it does not contain any visible delimiter for the end of the `prop` slot.
We therefore want the layout algorithm to automatically parenthesize the display form. To add parenthesizing attributes, click on the second `=` character to get a term cursor over the whole definition, and then enter `(C-M-S)` to get two empty attribute slots, with a term cursor over the first:
```
- DISP:: tst_df
[attr]: [attr]:exists_unique((T;x;.P)) == exists_unique((T;x;.P))
```
To instantiate the attribute slots enter `parens` `prec` `exists`. To get:
```
- DISP:: tst_df
Parens::Prec(exists) == exists_unique((T;x;.P))
```
This means that we assign the same precedence to the term `exists` as is assigned to the term `exists` in the standard libraries.
We may also add a soft-break format such that the period separating the `type` slot from the `prop` slot does not appear if a break is taken. Click on the `.` character and delete it using `C-D`. Enter `break`, click on the `g` after the `?` character in the soft break display form, and enter `. `.
```
- DISP:: tst_df
Parens::Prec(exists) == exists_unique((T;x;.P))
```
Finally, we add a second display form for the term `exists`, which drops the type information from the display whenever the type is `N`.
Click on the second `=` character to get a term cursor over the whole definition, and then enter `(M-0)` to get a second initial display form definition after it.
```
- DISP:: tst_df
Parens::Prec(exists) == exists_unique((T;x;.P))
```
Copy the first definition into the second as follows: enter `(C-K)` to replace the initial display form by an empty term slot, move the term cursor over the whole first definition, copy it with `(M-K)`, move the term cursor back over the empty term slot, and paste the first definition with `(C-Y)`.
```
On the right hand side of the definition, replace the meta-term $<T>$ by the type constant $\mathbb{N}$. Click \texttt{LEFT} on the $<$ character, enter (C-K) and then type $\texttt{nat}$ to enter the type $\mathbb{N}$.
On the left hand side, remove the term slot for $T$ by clicking \texttt{LEFT} on the $>$ character (!) and entering (C-K). Remove the colon with \texttt{BACKSPACE}.
In a similar way, one may add further display form definitions with iteration families to suppress the $\exists$ string and duplicate type information in nested occurrences of the term $\exists!x:T.P_x$. The display form object \texttt{exists\_df} in the standard theory \texttt{core\_1} can be used as an example for doing that.
|
{"Source-Url": "http://www.cs.cornell.edu/home/kreitz/PDF/02cucs-NuprlManual-07definition.pdf", "len_cl100k_base": 8717, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 37414, "total-output-tokens": 9118, "length": "2e13", "weborganizer": {"__label__adult": 0.00037384033203125, "__label__art_design": 0.00151824951171875, "__label__crime_law": 0.0004737377166748047, "__label__education_jobs": 0.01171875, "__label__entertainment": 0.00022101402282714844, "__label__fashion_beauty": 0.0002114772796630859, "__label__finance_business": 0.0005235671997070312, "__label__food_dining": 0.0003969669342041016, "__label__games": 0.001346588134765625, "__label__hardware": 0.0009016990661621094, "__label__health": 0.0005273818969726562, "__label__history": 0.0006823539733886719, "__label__home_hobbies": 0.00025081634521484375, "__label__industrial": 0.0008225440979003906, "__label__literature": 0.00116729736328125, "__label__politics": 0.000560760498046875, "__label__religion": 0.0008606910705566406, "__label__science_tech": 0.1932373046875, "__label__social_life": 0.00029659271240234375, "__label__software": 0.045013427734375, "__label__software_dev": 0.73779296875, "__label__sports_fitness": 0.0003693103790283203, "__label__transportation": 0.0004940032958984375, "__label__travel": 0.0002543926239013672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33943, 0.01602]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33943, 0.73242]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33943, 0.82634]], "google_gemma-3-12b-it_contains_pii": [[0, 2628, false], [2628, 6519, null], [6519, 9677, null], [9677, 13474, null], [13474, 16290, null], [16290, 19064, null], [19064, 22345, null], [22345, 25175, null], [25175, 28660, null], [28660, 31207, null], [31207, 33227, null], [33227, 33943, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2628, true], [2628, 6519, null], [6519, 9677, null], [9677, 13474, null], [13474, 16290, null], [16290, 19064, null], [19064, 22345, null], [22345, 25175, null], [25175, 28660, null], [28660, 31207, null], [31207, 33227, null], [33227, 33943, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33943, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33943, null]], "pdf_page_numbers": [[0, 2628, 1], [2628, 6519, 2], [6519, 9677, 3], [9677, 13474, 4], [13474, 16290, 5], [16290, 19064, 6], [19064, 22345, 7], [22345, 25175, 8], [25175, 28660, 9], [28660, 31207, 10], [31207, 33227, 11], [33227, 33943, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33943, 0.11494]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
276ee13bde637057e60acfb040e39199a58b1cc6
|
[REMOVED]
|
{"Source-Url": "http://dbis.eprints.uni-ulm.de/601/1/HaReBa_Handbook.pdf", "len_cl100k_base": 8854, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 43416, "total-output-tokens": 11730, "length": "2e13", "weborganizer": {"__label__adult": 0.0004024505615234375, "__label__art_design": 0.0010385513305664062, "__label__crime_law": 0.0004620552062988281, "__label__education_jobs": 0.003383636474609375, "__label__entertainment": 0.00014066696166992188, "__label__fashion_beauty": 0.0002875328063964844, "__label__finance_business": 0.0046844482421875, "__label__food_dining": 0.0004718303680419922, "__label__games": 0.0008487701416015625, "__label__hardware": 0.0011987686157226562, "__label__health": 0.0006008148193359375, "__label__history": 0.0005130767822265625, "__label__home_hobbies": 0.00019788742065429688, "__label__industrial": 0.003021240234375, "__label__literature": 0.0005002021789550781, "__label__politics": 0.0003581047058105469, "__label__religion": 0.0004906654357910156, "__label__science_tech": 0.1842041015625, "__label__social_life": 0.00016438961029052734, "__label__software": 0.099365234375, "__label__software_dev": 0.6953125, "__label__sports_fitness": 0.00033283233642578125, "__label__transportation": 0.00186920166015625, "__label__travel": 0.0002503395080566406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51180, 0.01822]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51180, 0.45289]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51180, 0.89686]], "google_gemma-3-12b-it_contains_pii": [[0, 1489, false], [1489, 4545, null], [4545, 5691, null], [5691, 8292, null], [8292, 11011, null], [11011, 13206, null], [13206, 15625, null], [15625, 17335, null], [17335, 19971, null], [19971, 22677, null], [22677, 25435, null], [25435, 27883, null], [27883, 30061, null], [30061, 33045, null], [33045, 34708, null], [34708, 36865, null], [36865, 37869, null], [37869, 40469, null], [40469, 43502, null], [43502, 45862, null], [45862, 48734, null], [48734, 51180, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1489, true], [1489, 4545, null], [4545, 5691, null], [5691, 8292, null], [8292, 11011, null], [11011, 13206, null], [13206, 15625, null], [15625, 17335, null], [17335, 19971, null], [19971, 22677, null], [22677, 25435, null], [25435, 27883, null], [27883, 30061, null], [30061, 33045, null], [33045, 34708, null], [34708, 36865, null], [36865, 37869, null], [37869, 40469, null], [40469, 43502, null], [43502, 45862, null], [45862, 48734, null], [48734, 51180, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51180, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51180, null]], "pdf_page_numbers": [[0, 1489, 1], [1489, 4545, 2], [4545, 5691, 3], [5691, 8292, 4], [8292, 11011, 5], [11011, 13206, 6], [13206, 15625, 7], [15625, 17335, 8], [17335, 19971, 9], [19971, 22677, 10], [22677, 25435, 11], [25435, 27883, 12], [27883, 30061, 13], [30061, 33045, 14], [33045, 34708, 15], [34708, 36865, 16], [36865, 37869, 17], [37869, 40469, 18], [40469, 43502, 19], [43502, 45862, 20], [45862, 48734, 21], [48734, 51180, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51180, 0.12579]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
7658b891ede86039c479e24626695da9b3a1b2e3
|
Living Models – Ten Principles for Change–Driven Software Engineering
Ruth Breu, Berthold Agreiter, Matthias Farwick, Michael Felderer, Michael Hafner, Frank Innerhofer–Oberperfler
University of Innsbruck, Institute of Computer Science, Technikerstr. 21A, 6020 Innsbruck, Austria, {ruth.breu, berthold.agreiter, matthias.farwick, michael.felderer, m.hafner, frank.innerhofer–oberperfler}@uibk.ac.at
Abstract The new generation of collaborative IT systems poses great challenges to software engineering due to their evolving nature and their high quality requirements. In particular, the management of collaborative systems requires the integration of perspectives from IT management, software engineering and systems operation and a systematic way to handle changes. In this paper we will present the core ideas of Living Models – a novel paradigm of model–based development, management and operation of evolving service oriented systems. A core concern of Living Models is to support the cooperation of stakeholders from IT management, software engineering and systems operation by providing appropriate model-based abstractions and a focus on interdependencies. Based on this idea the running services together with their modelling environments constitute the basic unit of quality management and evolution. Living Models provides a coherent view of the quality status of the system (integrating the perspectives of all stakeholders) which evolves together with the running systems. This comes along with a software engineering process in which change is a first-class citizen. In this paper we will present ten core principles of Living Models together with three application scenarios.
Key words: Service oriented systems; systems evolution; quality management; software engineering process; evolution
1 Preface
I was among Manfred Broy’s students when he got his first Professor’s position at the University of Passau. So I can proudly state that Manfred Broy heavily influenced the long way from the first day of my studies (he was lecturer of ”Introduction into Computer Science” in the first semester) to my habilitation and beyond.
†This work is sponsored by QE LaB – Living Models for Open Systems – FFG 822740, SecureChange EU grant number 231101, COSEMA – funded by the Tiroler Zukunftsstiftung and MATE – FWF project number P17380
His dedication to Software Engineering lead to the dedication to Software Engineering of a considerable amount of his students including me. I had the chance to take part in the development of a small research group at the University of Passau engaged in foundational research on formal methods to one of the largest research groups in Software Engineering at TU München being open minded to the manifold challenges of software development in practice.
Among the many visionary concepts Manfred Broy established in the research community I would like to mention the concept of system models as a foundational basis for modern multi–perspective modeling of systems. With our contribution I would like to demonstrate that also after 15 years of research on system models the comprehensive view of systems is still a hot topic.
Finally, I would like to take the opportunity and thank Manfred Broy for his great support of careers “with special needs”. Many female (and also male) colleagues could tremendously benefit from his willingness to find flexible solutions. In my case this ranged from support to get scholarships during my family phase, untypical contracts (5 hours per week) to continuous encouragement.
2 Introduction
Agility, flexibility of business processes and efficient cooperation across organisational boundaries have emerged as important success factors of enterprises. Agile, flexible and collaborative business services require agile, flexible and collaborative IT services. Therefore, a broad range of technologies, standards and architectures has been developed in the recent years.
Most of these approaches follow the paradigm of service oriented systems. Basically a service oriented system consists of a set of independent stakeholders offering and calling services. Orchestration and choreography technologies allow the flexible composition of services to workflows [30, 26]. Arising application scenarios have demonstrated the power of service oriented systems. This ranges from the exchange of health related data among stakeholders in health care, cross–linking of traffic participants to new business models like SaaS (Software as a Service).
While major international efforts in industry and academia so far have focused on the development of standards, technologies and frameworks for realising service oriented systems only a minority of approaches deal with software engineering aspects. This contrasts with the challenges attached with the design and operation of service oriented systems.
First, service oriented systems in most cases are dynamically evolving systems. For instance, in a networked health care scenario this means that information exchange will start with a number of hospitals and practitioners and will be successively extended by new stakeholder instances, stakeholder types (e.g. pharmacies, laboratories), services and workflows. As a consequence the borderline between software engineering and operation of these systems at runtime almost disappears.
Second, due to the open nature of these systems complex quality properties like functional correctness, security and privacy of processed information play a major role for design and operation. In the health care scenario, the correctness and integrity of patient–related data is of uttermost importance for the safety of human lives. In addition, many security requirements are imposed by legal regulations. In the health
care scenario this includes complex access rules to patient related data and the ownership of the patient with respect to his/her data. In this respect many of these quality attributes have a strong dependency with IT management, e.g. concerning the compliance of systems. In addition many quality attributes are enforced by configuration at runtime, thus require the consideration of the runtime environment in the quality management process.
In the current stage of development it is commonly accepted that model based software development provides a valuable contribution to meet parts of these challenges. In particular, in the area of service composition corresponding products (e.g. [1, 2]) have found their way into practice. However, most existing frameworks focus on the construction of solutions and neglect quality support and the consideration of change as a first-class citizen. In this respect they are not yet capable to meet the challenges imposed by dynamically evolving systems and their need for systematic quality management.
In this paper we present core principles and application scenarios of the novel paradigm of Living Models. Living Models focuses on model based management, design and operation of dynamically evolving systems. The innovation of our approach is threefold. First, Living Models is based on the tight coupling of models and code. This comprises a bi-directional information flow from models to code and from code and the runtime system back to the models. Second, Living Models supports the management of quality requirements fostering the cooperation between stakeholders in IT management, software engineering and systems operation. Third, Living Models is attached with a novel process model focusing on change and change propagation.
The name “Living Models” points to the tight coupling of the models with the running (=living) systems and to the support of the stakeholders’ daily tasks at appropriate levels of abstraction. We developed this paradigm based on our experience of many years of research in the area of model driven software development with a focus on security engineering and model based quality assurance [4, 17, 18, 11]. At the same time it is a starting point for the elaboration of methods and tools for the systematic development of high quality service oriented systems.
The remainder of this paper is structured as follows. In Section 3 we clarify the problem context and the core idea of Living Models. This is broken down into ten principles presented in Section 4. Section 5 demonstrates how these principles can be materialised in application scenarios in the domains of security engineering, enterprise architecture modeling and system testing. Finally, Section 6 summarises related work and draws a conclusion.
3 Problem Statement and Core Idea
An example for the potential effects of a rather small change is the computer failure at Lufthansa in 2004.\(^1\) The reason for the failure was the launch of a new computer programme, which lead to a software problem that brought the check-in system down. As a result of this failure 60 European flights were cancelled, affecting about 6,000 passengers. Also other partners in the airline’s network were suffering delays as a
consequence. This small example shows that the analysis of quality attributes (here: availability of the check-in system) in many cases requires the analysis of interdependencies across the layers ranging from IT management, software engineering to systems operation. This comprises the following tasks and roles.
**IT Management** is concerned with planning, management and analysis of IT services from the viewpoint of the business strategy and the business processes. This comprises responsibility for the recognition and evaluation of IT related risks and the compliance of the IT services. Typical roles within IT management are the CIO (chief information officer) and the CISO (chief information security officer).
**Software Engineering** deals with the design, implementation, maintenance and evolution of IT services. The task of software engineers is to establish agreement on requirements, quality attributes and resources and to deliver IT services satisfying these requirements and quality attributes based on the available resources. Typical roles within software engineering are the requirements engineer, the software architect and the quality manager.
**Systems Operation** aims towards the reliable and secure operation of IT services. This comprises the deployment and configuration of IT services, their runtime monitoring and the recognition of runtime-related risks. Typical roles within systems operation are the system administrator and the platform responsible (e.g. for ERP applications).
In an evolving context the integrated view of the three domains together with a continuous quality management process is crucial (cf. Figure 1). In order to materialise this concept three major research challenges have to be met.
- **RC1** – To provide a coherent view of the quality status of the system (integrating the perspectives of all stakeholders)
- **RC2** – To keep track of the quality status while the system and its requirements evolve
- **RC3** – To support the collaboration of stakeholders for achieving the necessary quality level
Our core idea to meet these challenges is a rigorous use of models to bridge the gap between the domains and the related stakeholders.
In a Living Models environment the basic unit of evolution constitutes the executable system together with its model-based views (cf. Figure 2). Each view provides a working platform supporting specific stakeholders like the requirements engineer, the security engineer or the tester. Each view records the current state of the system at an appropriate level of abstraction together with the current quality state. The quality state may be determined by qualitative attributes (evaluated by the responsible stakeholder) or by quantitative attributes (e.g. based on information collected in the runtime environment). It is in the responsibility of the stakeholders to transform each quality attribute into its target state (e.g. to transform risks into the state where the current risk level is acceptable or to transform a component in a state where the number of passed test cases is above a certain threshold).
Changes in any of these views are propagated to the other views and stakeholder tasks are generated. Changes may have an effect on the quality state of a view and the goal of the tasks generated is to transform the system again in its target state. For instance, the change of a legal requirement may require the security and risk analysis of relevant IT services, while the recognition of a new technical threat (e.g. change of a running service) may require the reanalysis of its business impact.
In this respect the entire system (= executable system together with its model views) strives to a state in which the quality attributes are in their target state. The prerequisite of this concept is the documentation of dependencies between model elements (including the code) which is in our opinion an indispensable foundation for an evolutionary approach.
4 Ten Principles for Living Models
In the following we will present ten principles which we consider to be crucial for establishing a Living Models environment. In Section 5 we will demonstrate how these principles are realised in different application scenarios and what benefits can be achieved.
Concerning the notion of models we accept any instance adhering to a Domain Specific Language (e.g. described by a MOF-compliant meta model [MOF]) as a model. For example, this comprises instances of (UML) class diagrams and state diagrams, but also enterprise models ([31, 28]) and even machine-executable code and semi-structured information like interlinked textual requirements descriptions.
**P1 – Stakeholder-Centric Modelling Environments**
Living Models environments should be stakeholder-centric in the sense that they are targeted to specific stakeholders and their tasks. Most importantly this means that the stakeholders can operate on an appropriate abstraction level and lower levels are hidden to them.
As an example the CIO operates based on concepts like business processes, information objects and IT services for aligning IT landscapes with business goals and for software project planning. The system tester formulates, executes and evaluates test cases at the level of the system requirements.
A Living Models environment does not necessarily have to provide a homogeneous modelling environment. More importantly all modelling environments have to contribute to a common system view (see P3).
The models in a Living Models environment provide the backbone for the stakeholders’ work and collaboration. In order to support the tasks of a stakeholder properly the models may be enhanced by any kind of information. This may range from simple attributes like the cost of some model element (e.g. of a purchased software service) to service level agreements or emergency plans. This includes facilities to connect this information, like the support of cost calculations.
**P2 – Close Coupling of Models and Running Systems**
In contexts where the running systems are the main target any model and sophisticated model analysis is useless if the model does not reflect the running system. Therefore in an evolving environment the tight coupling of models and the runtime environment is crucial. We talk of tight coupling if the runtime environment and the models are in consistent states and if there is some tool support to link models with the running system. This may comprise the following patterns.
- Models are used to generate code at design time
- Models are used to configure code at runtime
- Models are generated out of the code (e.g. architecture models)
- There is a tool-supported direct connection of models and code, e.g. test cases generated out of some requirements model are executed on the running system
- Model elements and code components are linked with each other and changes in either of them are propagated to the other end enforce change of the other
Combining P1 and P2 a Living Models environment consists of a set of modelling environments where each of these modelling environments supports the work of specific stakeholders at an appropriate level of abstraction and has a direct link to the executing system.
**P3 – Bidirectional Information Flow between Models and Code**
In order to provide a full-fledged working platform it is recommendable that information does not only flow from models to code and the running system, respectively, but also vice versa. As an example, workflow management systems feed back runtime information (number of running workflow instances, average completion time and the like) to the model level. This supports stakeholders in their task to assess and to improve workflow schemas.
In a more general view we conceive a Living Models environment to have sensors in the runtime environment. These sensors collect information which is brought back to the modelling environment and interpreted at the level of the model elements. A further example is information about usage frequency and duration of IT services which is brought back to the IT landscape model and supports the CIO in aligning IT services towards business goals.
In order to realise such sensors in a Living Models environment the following patterns can be used.
- generation of sensor software (observers and adapters) based on sensor definitions at model level
- injection of meta model information in the code, and
- code reflection in order to transmit runtime information to the code level.
**P4 – Common System View**
A prerequisite for a continuous quality management process and the collaboration of stakeholders is a common system view. In order to provide an appropriate level of preciseness and a basis for tool support the common system view is defined by a System Meta Model comprising meta model elements and their interrelationships.
The System Meta Model constitutes the backbone of the change management process. The meta model elements are the basic units of change and the associations between the meta model elements are the basis for traceability and change propagation.
Figure 3 and Figure 4 show a System Meta Model we use as reference model in our research platforms (cf. Section 5). For defining the System Meta Model we apply the following core concepts.
First, the System Meta Model comprises both functional and non–functional aspects of the system and attaches non–functional aspects to functional aspects. For instance, we do not talk of security requirements in general, but of security requirements of a business process or security requirements of a component. Thus, we associate the non–functional meta model element SecurityRequirement with the functional meta model elements BusinessProcess and Component, respectively. Figure 3 shows the functional part of the System Model (Functional System Meta Model), Figure 4 depicts the Security Meta Model as an example for non–functional aspects. Both diagrams are connected by the fact that the Security Meta Model refers to a meta model element FunctionalModelElement being superclass of each class in the Functional System Meta Model. Thus, the Security Meta Model enhances each functional model element by concepts such as a security objective, a security requirement or a security risk (for further information we refer to [17]). We call the Security Meta Model a plug–in of the Functional Meta Model. Examples of other plug–ins are a Test plug–in, a Cost plug–in or a Performance plug–in.
Second, the Functional System Meta Model defines the core concepts of the stakeholders’ view on the system. The Functional System Meta Model is structured into three components for IT Management, Systems Operation and Software Engineering, respectively. Each of these components may comprise other components, e.g. the Software Engineering component contains the sub–components Requirements, SW Ar-
architecture and Code. The IT Management and Systems Operation component of our reference model is aligned with established Enterprise Architecture models like the Zachmann framework [31] or TOGAF [28]. They relate model elements from a business perspective (e.g. Information, BusinessProcess, Role) with model elements from an IT Application perspective (RunningService) and from a technical perspective (Node, Location), respectively. The Software Engineering component is structured into a requirements perspective (with the spanning concepts of a Service, an Actor and a Class, cf. [11]), a Software Architecture perspective (with logic components and interfaces as the core concepts) and the Code perspective (with code components and classes as the core concepts).
The associations in the System Meta Model induce dependency chains across the perspectives, e.g. from a business process to the server (Node) where its IT support (Running Service) is deployed.
Third, a System Meta Model defining the atomic meta model elements may be attached with a set of views. Each view represents a portion of the System Meta Model aggregating the meta model elements relevant to specific stakeholders. As an example, the Security Meta Model (cf. Figure 4) defines a Security Risk View defining the model elements relevant for the management of IT security risks. Figure 5 defines a partial view representing the mapping between the logical components of the SW Architecture and the code components.
Similar to the conventions of most modeling tools we also call the composition of meta model elements to a view a diagram (type), e.g. the Security Risk Diagram defined in Figure 4 and the Architecture to Code Mapping Diagram defined in Figure 5.
Referring to the usual notion of a model or diagram (like a business process model or a class diagram) each such diagram may be represented in an arbitrarily fine-grained way in the System Meta Model. For instance, a business process model may be represented entirely by the meta model element BusinessProcess or by its complete meta model (e.g. determined by the BPMN meta model). In our perception any information attached with a meta model can be integrated in the System Meta Model and its plug-ins and therefore be subject of traceability and change. This comprises code fragments (instances of the meta model elements Class, Component, cf. Figure 3) or textually described requirements (instances of the meta model elements Security Requirement, Threat, cf. Figure 4).
P5 – Persistence
The System Meta Model defines the schema for its instances (the so-called System Models). A System Model describes the current state of a system at all levels of abstraction (from business processes to physical nodes) including all relevant information (e.g. security risks, costs, quality state).
System Models are the target of change and evolution. In order to support systematic analysis and reaction to change System Models have to be made persistent. In this spirit system evolution is described by a sequence of System Models.
In addition, planning facilities should enable the analysis of alternative solutions (e.g. comparing security safeguards within different architectural variants). This way,
the consideration of sequences of System Models has to be extended to the usual general view of versioning including branches and model merging.
Figure 6 extends the System Meta Model concept by a simple versioning concept based on a predecessor/successor relation. For clarification sample System Model instances are depicted.
During the lifetime of the system not only the System Models but also the System Meta Model may be subject to change and evolution. In this respect and in the spirit of the MOF language hierarchy [25] the System Meta Model itself has to be conceived as an instance of a meta model of a higher level. Concerning details on the requirements to model versioning in a Living Models environment we refer to [3]. For constructing and maintaining System Models the use of automated techniques is crucial. For instance, tools of static code analysis help to maintain interdependencies at code and software architecture level and model based testing tools help to link the requirements level with the code level.
P6 – Information Consistency and Retrieval
System Models are complex networks of information describing the current state of the system. Constraints checking and information retrieval are two important services stakeholders have to be provided with. For instance, a CSO would like to check if every security threat at technical level is related with some security requirement at business level (describing the business impact of the technical threat). Similarly, the software architect would like to check if each service at requirements level has a corresponding service at architecture level.
Information retrieval goes beyond such checks in delivering not only a Boolean value but any kind of information based on the System Model. The work of Hanschke [20] and Buckl et al. [6] demonstrates that information visualisation plays an important role for information retrieval in System Models. Both approaches define a set of diagram types to visualise the connections between information at application and business layer. As an example, the Process Support Map visualises which business processes are supported by which business applications in which organisational units.
P7 – Domains and Responsibilities
A System Model describes the current status of the entire system providing the basis for information traceability and cooperation among stakeholders. Each stakeholder operates on a subset of model elements in the System Model, e.g. being responsible for the construction or quality assessment of these model elements.
More precisely, we attach the System Meta Model with a role model. Roles define the stakeholders (e.g. CIO, software architect, ERP applications responsible) and rights describe the actions the stakeholder is able to perform on the model elements, e.g. creation/modification of model elements or creation of certain events (cf. P9).
The set of model elements a stakeholder is responsible for is called his/her domain.
For instance, the CIO may be responsible for the whole IT management layer, while the domain of application responsibles is a range of model elements on the application and physical layer.
P8 – Model Element States
In order to support the daily tasks of stakeholders it should be possible to attach each model element in a System Model (e.g. a business process, an information object or a running service) with arbitrary information. This may range from a service level agreement, a model (e.g. an activity diagram) considered as black box in the change process, a key figure (e.g. the average number of running instances of a business process) or a state.
States play a particular role in the change-driven process since they determine the quality relevant milestones in the lifecycle of the model element. For instance, a requirement may be added, evaluated (i.e. was subject of a quality assessment activity) or implemented.
P9 – Change Events
In our framework any change is perceived as an event which triggers consecutive steps of actions. Possible types of change events are the following.
- a time event (e.g. a threat analysis of the system has to be performed periodically)
- the change (modification/creation/deletion) of a model element in the System Model (e.g. the change of a compliance requirement or the change of a running service to a new release)
- events initiated by the stakeholders (so-called action events, e.g. the notification that a requirement has been validated manually or the notification that the set of requirements is considered to be complete)
Each change event is associated with a model element in the current System Model triggering change propagation and change handling according to the change-driven process described in P10.
In addition a Change Request conceptualizes the context of several change events (e.g. all change events related with the exchange of a running service). The notion of change requests provides a bridge to change management processes in IT Service Management (e.g. ITIL [23]). These processes describe the organisational handling of change, e.g. defining the necessary organisational structure (boards, responsibles) and process steps (e.g. prioritising and scheduling change requests). Figure 7 depicts the interrelationships between the change relevant concepts. Here we assume that every class of the System Meta Model is subclass of ModelElement.
P10 – Change-Driven Process
The support of a change driven software engineering process is an essential element in a Living Models environment. While conventional software engineering processes are controlled by sequences of activities a change driven process is controlled by change events, the current (lifetime) state of model elements and the interrelationships of model elements in the System Model. Change events trigger change propagation and a change handling process.
Change propagation determines which parts of the current System Model are affected by a change event. This may include the firing of new change events. Change handling is concerned with processing all relevant change events in order to finish the related change request.
More formally the change driven process is materialised through (UML) state machines attached to the meta model elements of the System Meta Model. The states of the state machines represent the major milestones in the lifetime of the respective model element and correspond to completed activities in conventional software engineering processes. Each state machine has one or several target states and it is in the responsibility of the associated stakeholder to transform model elements in their target state. In this spirit a System Model can be attached with a set of green and red lights, representing model elements in their target state or not yet in their target state, respectively.
As an example, Figure 8 shows the state machine of the meta model element SecurityRequirement. A security requirement can be in the state added (the security requirement has been identified and attached with a functional model element, e.g. a business process), complete (associated risks have been identified and declared to
be complete at the current stage of development) or in the target state evaluated (all associated risks have been evaluated). State transitions in the state machines are triggered by events of the following kind:
- time events (e.g. triggering analysis actions to be performed periodically)
- conditions on the system state (e.g. in Figure 8 the state of a security requirement is changed from complete to evaluated if all associated risks are in state evaluated)
- action events initiated by the stakeholders (e.g. with the action event complete in Figure 8 the stakeholder declares the set of associated risks to be complete)
- change events caused by the modification/creation/deletion of some model element
Based on the state machines the change propagation and change handling process can be realised by the following three steps.
A. Change Event – A change event causes a state transition of the affected model element according to its associated state machine.
B. Change Propagation – The state transition may fire further change events sent to related model elements (or model elements may observe state transitions of related model elements). The change propagation rules realised in the state machines may vary from no propagation (the change is handled locally) to change propagation under certain conditions (e.g. only if a certain threshold is exceeded) or change propagation to selected related model elements, to change propagation to all related (or even all) model elements.
C. Change Handling – The change handling process is defined by the goal to transform all affected model elements of step B in their target state. In general this requires manual tasks (realised by action events) performed by the responsible stakeholders.
Note that the change propagation step may cause a chain of state transitions across layers and responsibility domains of the stakeholders. In particular, dependencies between model elements of different responsibility domains support the cooperation of the related stakeholders. For instance, in this way the observation of a threat at technical level may be forwarded and interpreted across the layers triggering actions at business layer (e.g. if a re-evaluated business risk is getting too high).
The states in the state machines correspond to completed activities in known process models (e.g. the sequences of activities in the waterfall model [27] or the V-Model XT [29] or the sequence of security related activities in security engineering processes like SDL [21] or CLASP [16]). While these process models can be supported in our framework a change-driven process offers two main advantages.
First, the change-driven process fosters process steps on parts of the system (the ”delta” of change). Second the quality state of the system is recorded, can be analysed at any point of time and can be tracked by tools. The price to be paid is the maintenance of model elements and their interdependencies. In our experience many companies have started to collect huge amounts of data (e.g. about IT landscapes, run-time properties) but are not yet able to use this huge analysis potential since data interconnection is missing. In this respect the Living Models paradigm provides a first step to exploit this potential. However, it is clear that still a lot of work has
to be done. This concerns both the elaboration of patterns for the tool-supported maintenance of model elements and their interdependencies (reducing efforts and costs) and considerations of return of investment.
5 Application Scenarios
In this section we demonstrate three application scenarios of the Living Models principles. Each of these application scenarios has been developed in our research projects in cooperation with industry partners.
- SECTET/COSEMA is a framework for the model–based analysis of security requirements and risks (COSEMA) together with a platform for the model–based configuration of security services (SECTET). SECTET/COSEMA covers the full reference Functional System Meta Model (cf. Figure 3) and focuses on security as a quality attribute.
- Living Landscape Models is a tool–based method in the area of Enterprise Architecture Modeling. It covers the IT Management and Systems Operations domain of the Functional System Meta Model.
- Telling TestStories is a framework for model–based acceptance tests. It covers the Requirements and Code layer of the Software Engineering domain of the Functional System Meta Model.
5.1 The SECTET/COSEMA Living Security Models Environment
5.1.1 COSEMA
In the project COSEMA\(^2\) we work on a framework which supports a collaborative approach to information security management (ISM). The various activities related to
\(^2\) http://www.cosema.org/
ISM involve many different stakeholders in an organisation. Ranging from compliance and legal experts, to IT managers, network and system administrators, functional managers and last but not least end users each of these stakeholders play important roles in security management. To support a collaborative approach to the analysis of security requirements and risks COSEMA delivers a model-based framework which fosters the collaboration of these different stakeholders with their diverse backgrounds. Important aspects thereby are the support of communication among these stakeholders and the provision of tailored perspectives reflecting the different levels of abstraction of the stakeholders.
The COSEMA approach is based on a three layered functional model of the enterprise comprised of business, application and physical layer (cf. Fig. 3). This functional system model is extended with the security plug-in (cf. Fig. 4) to annotate the enterprise model with security concepts such as security objectives, requirements, risks and threats. Fig. 9 provides a schematic example of an enterprise model extended with security relevant information.
The COSEMA framework realizes the following principles of Living Security: Involving different stakeholders with diverse backgrounds it realizes \textit{P1 – Stakeholder Centric Modelling Environments} to provide each of these stakeholders with tailored perspectives and representations of the models. Principle \textit{P4 – Common System View} is realized to provide the means for traceability along dependency relations of the functional system model. In order to maintain consistency in the collaborative information security analysis principle \textit{P6 – Information Consistency and Retrieval} plays an important role. Another important aspect to support the collaboration of different stakeholders is principle \textit{P7 – Domains and Responsibilities} which allows to restrict access rights of the stakeholders to specific aspects of the enterprise model and security plug-in. Principle \textit{P8 – Model Element States}, \textit{P9 – Change events} are the basis for defining triggers and events that lead to new tasks that have to be carried out by a specific stakeholder.
5.1.2 The SECTET Framework
The SECTET [17] framework supports business partners during the development and distributed management of decentralized peer-to-peer scenarios. Primarily developed for the realization of decentralized, security critical collaboration across domain boundaries – so-called inter-organizational workflows, it realizes a domain architecture aiming at the correct technical implementation of domain-level security requirements. It consists of three core components (cf. Figure 10): A. Security Modeling. The modeling component supports the collaborative specification of a scenario at an abstract level as a high-level Platform Independent Model (PIM)). The PIM consists of a Business Process Model complemented by Security Policies. The modeling component implements an intuitive domain specific language, which is rendered in a visual language based on UML2 for various modeling tools. The modeling occurs at a level of abstraction appropriate to bridge the gap between domain experts on one side and engineers on the other side, roles chiefly involved in two different phases of the engineering process – the requirements engineering and the design phase respectively.
B. Code Generation & Model Transformation. Business Process Models and Security Policies are mapped to a set of Platform Independent Security Patterns (PISP) leveraging abstract security services and protocols enforcing specified security policies. The engineer may choose among a number of alternative PISP reflecting various architectural options (e.g., brokered authentication vs direct authentication). The PISPs are then refined into Platform Specific Security Protocols of various granularity until they can be mapped into configuration code for the components of the target architecture. The layered approach is introduced in [24]. C. Security as a Service – Reference Architecture. The Reference Architecture (RA) transposes the model of Software as a Service to the security domain and thereby realizes Security as a Service (SeAAS). SeAAS resolves some of the conceptual and practical issues linked with the current practice to implement security functionality exclusively at the endpoint (e.g., significant processing burden on the endpoint, cumbersome maintenance and management of the distributed security infrastructures, lack of interoperability with external service requesters). But SeAAS also goes beyond the mere bundling of security functionality within one security domain as it realizes complex security requirements for decentralized processes involving two or more domains. We introduced SeAAS in [19].
The SECTET framework realizes several principles of Living Security. Primarily targeted at domain experts (P1 – Stakeholder Centric Modelling Environments), it relies on models to generate code for a target architecture (P2 – Close Coupling of Models and Running Systems). The collaboration of domain experts with security engineers and administrators is realized through a common view on the decentralized, security-critical process (P4 – Common System View). Although the framework’s backbone consists of a common System Meta Model comprising meta model elements and their interrelationships, each stakeholder only operates on a subset of model elements through his customized modeling environment (P7 – Domains and Responsibilities). The framework supports to handle changing security requirements efficiently and effectively (P9 – Change Events). New requirements percolate from abstract models through all layers of abstractions (P2 – Close Coupling of Models.
and Running Systems) and enable the stakeholders to take appropriate actions (P10 – Change Driven Process). The SECTET framework is currently being applied to use cases from the domotics industry and healthcare with our partners Telefonica I+D in the SecureChange project³ and IT Icoserve GmbH in context of research related to Living Security Models of the QE-LaB Competence Centre ⁴.
5.2 Living IT–Landscape Models
Enterprise Architecture Management (EAM), and in particular IT–landscape modelling try to model the IT and business elements of a company, in order to support the achievement of various goals in an enterprise. These goals include a business-aligned IT, achieving transparency over dependencies in the IT–landscape, being able to assess risks, secure regulatory compliance, and plan IT-landscape transformations in an enterprise as well as being able to analyse change impact. Conforming to our Reference Meta Model (cf. Fig. 3), typical EAM models consist of four layers. Among them are: A Business Layer describing the core business processes, business functions and products of an enterprise, a Data Layer describing the data items exchanged within the enterprise at an abstract level, an Information System Layer describing the enterprise information systems that support the business and their interconnections, and an Infrastructure Layer that describes the technical infrastructure which supports the information systems, e.g. servers and databases. In its simplest manifestation, EAM is conducted by modelling the enterprise-wide relations in a non–standardised way, for example on presentation slides. In its most sophisticated form, EAM is supported by
³ http://www.securechange.eu/
⁴ http://qe-lab.at/
modelling tools\textsuperscript{5}, standardised notations and is accompanied with appropriate processes in the organisation. Both approaches, however, face a common problem. The elicitation of the necessary information to create the EAM models is time consuming, and due to rapid changes in enterprises, the information is often quickly outdated. This problem evokes a significant research question: How can enterprise architecture models, and IT–landscape models in particular, be automatically kept in–sync with the IT–landscape they represent, and how can information from different sources be correlated such that connections between model elements can be automatically inferred? Together with our industry partner iteratec GmbH\textsuperscript{7} we tackle these questions by applying the principles of Living Models. For realising the Living Models principles in the context of enterprise architecture management we apply a federated approach to EAM as proposed by Fischer et al.\textsuperscript{15} and extend it by making use of standardised interfaces and Semantic Web technology, i.e. logics. Figure 11 visualises this federated approach which we describe in more depth in \cite{10}. The basic concept is that arbitrary information sources are connected to a centrally stored model. Each information source, such as project management tools, application servers and hardware monitors, contributes its information to this centralised system model. The communication facilities for this provision implement standardised interfaces \cite{8}. When the central model receives data from a connected (runtime) information source, it adds this information to its semantic knowledge base. We then use rules to infer knowledge about relationships between model elements, and whether data from distinct information sources actually represent the same physical thing. However, this process still needs to be supervised by a human to avoid errors and to ensure desired quality. After the rules have been applied, the central model pushes the new information to the EAM tool. In particular we extended the open-source EAM tool iterateplan\textsuperscript{8}, which has been developed by our industry partner iteratec GmbH.
\textsuperscript{5} http://www.iteraplan.de (accessed on 2010-08-09)
\textsuperscript{6} http://www.ids-scheer.com/en/Software/ARIS_Software/ARIS_ArchiMate_Modeler/21980.html (accessed on 2010-08-09)
\textsuperscript{7} http://www.iteratec.de
\textsuperscript{8} http://www.iteraplan.de
Our approach and its prototypical realisation uses several of the Living Models principles. By keeping the EAM tool iteraplan in-sync with the real world, we provide a stakeholder centric view to the EAM practitioner and other involved actors (P1 – Stakeholder Centric Modelling Environments). Furthermore, information flows from running systems to the model and back (P2 – Close Coupling of Models and Running Systems, P3 – Bidirectional Information Flow between Models and Code). In our implementation, the Semantic Web knowledge base represents the common system view (P4 – Common System View) that also provides for persistence (P5 – Persistence). With rules and constraints we check the consistency of the aggregated knowledge, and, in addition, infer new knowledge (P6 – Information Consistency and Retrieval). The information flow in our system is driven by change events therefore P9 – Change Events and P10 – Change Driven Process are at the heart of our implementation.
Living Landscape Models allow for tight coupling of the EAM tool and other relevant information sources in an organisation. This directly tackles the synchronicity problem between EA models, resp. key figures relying thereon, and the infrastructure, and allows for making decisions with up-to-date information and quickly respond to changes in the environment.
5.3 Living Requirements with Telling TestStories
Requirements testing methods for service oriented systems evaluate the system’s compliance with its specified requirements and have to consider complex quality properties of systems and their dynamic evolvement. Model-driven testing approaches, i.e., the derivation of executable tests from test models by analogy to model-driven engineering are particularly suitable for requirements testing of service oriented systems because tests can be adapted easily to evolving requirements and complex quality properties can be expressed by models.
Telling TestStories (TTS) [13] is a tool–supported methodology for model–driven requirements testing of service oriented systems. TTS has been developed in cooperation with the German SME Softmethod GmbH9 and applied to industrial case studies for functional requirements testing of a telecommunication application [14] and security requirements testing of a home networking application [12]. The core artefacts, their relationships and representation in TTS are depicted in Figure 12.
The requirements model contains the functional and non–functional requirements for system development and testing. Its structured part consists of a requirements hierarchy.
The system model describes the system structure and system behavior in a platform independent way. It is based on the notion of services. Each service is assigned to a requirement and to an executable service in the running system to guarantee traceability.
The test model defines the test requirements, the test data and the test scenarios as so called Test Stories. Test stories are controlled sequences of service operation invocations exemplifying the interaction of services and assertions for computing verdicts. Test stories may be generic in the sense that they do not contain concrete objects but variables which refer to test objects provided in tables. Test stories are validated,
---
9 http://www.softmethod.de
checked for coverage or in specific cases generated from the system model. TTS supports classical test-driven development because with test models and adapters it is possible to achieve executable tests even before the system implementation has been finished. Test stories are linked to requirements and associated with services of the systems by service calls. Requirements are traceable to executable test stories and are therefore Living Requirements. The test controller, the adapter and the test code form the test system. The test controller executes the generated test code and accesses the system services via adapters. Our implementation of the test controller executes test code in Java. Adapters for each service are the link for traceability between the executable system, the test model and the requirements.
The system under test is a running service oriented system.
In TTS, traceability between all artefacts is guaranteed. Requirements, tests and services are associated on the model level via links between model elements. Each modeled service in the system is associated with an executable service in the system. The adapters link service calls in the model to executable services. Therefore every service invocation is traceable to a requirement.
TTS has been designed and implemented based on the principles of Living Models. Due to the traceability between all types of artefacts, TTS provides a close coupling of models and running systems (P2 – Close Coupling of Models and Running Systems) and a bidirectional information flow between models and code (P3 – Bidirectional Information Flow between Models and Code). For different stakeholders specific environments are provided (P1 – Stakeholder Centric Modelling Environments), e.g., a test report view for IT managers or a test model view for quality managers. TTS
provides an integrated meta model for system, tests, and requirements under consideration of non-functional properties (P4 – Common System View) and checks for model consistency and coverage (P6 – Information Consistency and Retrieval). The remaining principles are considered in a TTS based approach to manage the evolution of test models by attaching state machines to all model elements. The test evolution framework then guarantees the consistent evolution of the system and its tests and uses the states of model elements to generate regression test suites.
6 Conclusion
In the preceding sections we have identified core research challenges for evolving open systems with high quality requirements and have presented ten principles which in our opinion are essential to meet these challenges. The major aspects of the new Living Models paradigm are the systematic handling of changes at all levels of abstraction, continuous quality management and the integration of IT management, software engineering and systems operation.
Living Models has been built upon the ideas of model based software development and Enterprise Architecture Management ([31], [9], [6]). Software processes controlled by state machines can be found in specific areas and tools of software engineering, e.g. in requirements specification [22] and bug tracking [7]. The UNICASE system [5] is a framework for global software engineering similarly based on the interconnection of model elements. However, UNICASE does not support a change-based process and does not consider aspects of IT management and systems operation nor quality management.
In Section 5 we demonstrated how the principles of Living Models are materialised in application oriented frameworks and what benefits can be achieved. These frameworks covered the fields of security engineering, enterprise architecture modeling and model-based acceptance tests.
There still remains a lot to be done. First, the Living Models paradigms in the presented frameworks still have to be elaborated in many facets. In addition, the systematic tool-supported management of interdependencies between model elements in the System Model is a major concern. Finally, we have started to conceptualise generic tool support for the change-driven software engineering process. This poses many challenges in direction of model versioning, merging models of various sources, co-evolution of meta models and models and supporting the state machine based change propagation and change handling process.
References
|
{"Source-Url": "https://qe-informatik.uibk.ac.at/wp-content/uploads/2014/03/BreuLivingModels.pdf", "len_cl100k_base": 9848, "olmocr-version": "0.1.50", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 52897, "total-output-tokens": 12517, "length": "2e13", "weborganizer": {"__label__adult": 0.00029921531677246094, "__label__art_design": 0.00045871734619140625, "__label__crime_law": 0.00028705596923828125, "__label__education_jobs": 0.0011892318725585938, "__label__entertainment": 5.644559860229492e-05, "__label__fashion_beauty": 0.00013899803161621094, "__label__finance_business": 0.0003285408020019531, "__label__food_dining": 0.0002703666687011719, "__label__games": 0.0005173683166503906, "__label__hardware": 0.0005164146423339844, "__label__health": 0.0003690719604492187, "__label__history": 0.0002646446228027344, "__label__home_hobbies": 7.033348083496094e-05, "__label__industrial": 0.0003218650817871094, "__label__literature": 0.00025177001953125, "__label__politics": 0.0001951456069946289, "__label__religion": 0.00038743019104003906, "__label__science_tech": 0.01739501953125, "__label__social_life": 8.630752563476562e-05, "__label__software": 0.007045745849609375, "__label__software_dev": 0.96875, "__label__sports_fitness": 0.00021755695343017575, "__label__transportation": 0.0003757476806640625, "__label__travel": 0.0001857280731201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58174, 0.02041]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58174, 0.16406]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58174, 0.91413]], "google_gemma-3-12b-it_contains_pii": [[0, 2555, false], [2555, 5994, null], [5994, 9441, null], [9441, 11509, null], [11509, 14116, null], [14116, 17193, null], [17193, 20355, null], [20355, 23602, null], [23602, 23931, null], [23931, 25232, null], [25232, 28172, null], [28172, 30781, null], [30781, 34109, null], [34109, 35535, null], [35535, 37772, null], [37772, 41362, null], [41362, 43094, null], [43094, 45602, null], [45602, 48924, null], [48924, 50767, null], [50767, 53989, null], [53989, 57356, null], [57356, 58174, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2555, true], [2555, 5994, null], [5994, 9441, null], [9441, 11509, null], [11509, 14116, null], [14116, 17193, null], [17193, 20355, null], [20355, 23602, null], [23602, 23931, null], [23931, 25232, null], [25232, 28172, null], [28172, 30781, null], [30781, 34109, null], [34109, 35535, null], [35535, 37772, null], [37772, 41362, null], [41362, 43094, null], [43094, 45602, null], [45602, 48924, null], [48924, 50767, null], [50767, 53989, null], [53989, 57356, null], [57356, 58174, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58174, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58174, null]], "pdf_page_numbers": [[0, 2555, 1], [2555, 5994, 2], [5994, 9441, 3], [9441, 11509, 4], [11509, 14116, 5], [14116, 17193, 6], [17193, 20355, 7], [20355, 23602, 8], [23602, 23931, 9], [23931, 25232, 10], [25232, 28172, 11], [28172, 30781, 12], [30781, 34109, 13], [34109, 35535, 14], [35535, 37772, 15], [37772, 41362, 16], [41362, 43094, 17], [43094, 45602, 18], [45602, 48924, 19], [48924, 50767, 20], [50767, 53989, 21], [53989, 57356, 22], [57356, 58174, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58174, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
34c394de2ae6c6861ea660add8222bf83badcfca
|
[REMOVED]
|
{"len_cl100k_base": 14575, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 52036, "total-output-tokens": 17862, "length": "2e13", "weborganizer": {"__label__adult": 0.0003724098205566406, "__label__art_design": 0.000308990478515625, "__label__crime_law": 0.00026106834411621094, "__label__education_jobs": 0.0013647079467773438, "__label__entertainment": 4.941225051879883e-05, "__label__fashion_beauty": 0.00014531612396240234, "__label__finance_business": 0.0002751350402832031, "__label__food_dining": 0.0002472400665283203, "__label__games": 0.00047135353088378906, "__label__hardware": 0.000457763671875, "__label__health": 0.00029087066650390625, "__label__history": 0.00015878677368164062, "__label__home_hobbies": 9.071826934814452e-05, "__label__industrial": 0.00021779537200927737, "__label__literature": 0.0001806020736694336, "__label__politics": 0.00020575523376464844, "__label__religion": 0.00032138824462890625, "__label__science_tech": 0.0027980804443359375, "__label__social_life": 0.00012826919555664062, "__label__software": 0.005275726318359375, "__label__software_dev": 0.98583984375, "__label__sports_fitness": 0.0002529621124267578, "__label__transportation": 0.0003383159637451172, "__label__travel": 0.000171661376953125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72458, 0.04843]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72458, 0.22475]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72458, 0.91305]], "google_gemma-3-12b-it_contains_pii": [[0, 3613, false], [3613, 8448, null], [8448, 15767, null], [15767, 16906, null], [16906, 24524, null], [24524, 29323, null], [29323, 33144, null], [33144, 36530, null], [36530, 41378, null], [41378, 45328, null], [45328, 49739, null], [49739, 56239, null], [56239, 63533, null], [63533, 72216, null], [72216, 72458, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3613, true], [3613, 8448, null], [8448, 15767, null], [15767, 16906, null], [16906, 24524, null], [24524, 29323, null], [29323, 33144, null], [33144, 36530, null], [36530, 41378, null], [41378, 45328, null], [45328, 49739, null], [49739, 56239, null], [56239, 63533, null], [63533, 72216, null], [72216, 72458, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72458, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72458, null]], "pdf_page_numbers": [[0, 3613, 1], [3613, 8448, 2], [8448, 15767, 3], [15767, 16906, 4], [16906, 24524, 5], [24524, 29323, 6], [29323, 33144, 7], [33144, 36530, 8], [36530, 41378, 9], [41378, 45328, 10], [45328, 49739, 11], [49739, 56239, 12], [56239, 63533, 13], [63533, 72216, 14], [72216, 72458, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72458, 0.07054]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
ca510f8391b872dc2f1e7d47fd012eaba08b0cea
|
Runtime Reprioritization for Online Aggregation Queries
THESIS
Presented in Partial Fulfillment of the Requirements for the Degree Master of Science in
the Graduate School of The Ohio State University
By
Karthik Tunga Gopinath, B.E
Graduate Program in Computer Science and Engineering
The Ohio State University
2013
Dissertation Committee:
Dr. Arnab Nandi, Advisor
Dr. Srinivasan Parthasarathy
Copyright by
Karthik Tunga Gopinath
2013
Abstract
The need for interactive ad-hoc analytics has been steadily rising. The traditional batch processing of large data takes order of seconds to several minutes for query execution, which cannot guarantee an interactive experience. With ever increasing size of data, gaining an interactive experience is non-trivial. Online aggregation solves part of the problem by returning estimated results at regular intervals. An online aggregation system allows the user to observe the progress of the query but falls short when it comes to controlling the query execution. We propose an online aggregation system that takes query priority as a dynamic user defined input, allowing the user to control the progress of query execution by adjusting the priority at runtime. The framework derives concepts from online aggregation and shared scan query execution model, coupled with our priority based scheduling to allow for dynamic user defined query reprioritization. We also show how the proposed system behaves for different underlying storage formats.
This document is dedicated to Claudia.
Acknowledgments
I would like to convey my gratitude to my advisor Dr. Arnab Nandi, for giving me the opportunity to be part of his exciting and young research group. He has been my source of inspiration and I would like to thank him for all guidance he has given throughout my research. I appreciate his ability of identifying crucial and challenging research problems as well as giving me the freedom to learn and explore different aspects of the field on my own. His high standard of expectations has always kept me pushing for more.
I would like to thank Prasanth Jayachandran and Niranjan Kamat for their hard work and dedication to research. I have lost track of the countless caffeine filled late night programming sessions that we had in the department lounge. For most part of our research, we followed “get home before the sun rises” principle, which is evident in our code check-in patterns. Without their passion for solving interesting problems I do not think I would have got this far.
I would like to thank the entire datateam for providing all the support that they have. They were always present during our submissions and appreciate them for that.
Next I would like to thank my awesome friends and roommates Puneeth and Rohan for all their support. This most certainly would not have been possible without them.
I would also like to mention my close friends – Abhishek for all the free food, Chatty for all this brilliant puns, Farhang for his simple “NO” replies, Manas for all the late night walks to get food, Vineet for his sheer dedication, Tarun for his “you are at least making progress, I am doing nothing” talks and finally Ramya for her amazing home cooked food.
I will always be short of words to thank my parents for their love and all their sacrifices without which I would not be who I am today.
Finally, Claudia, for always being behind me every ever I go. She is a huge part of what I am today. She alone has the power of saying a lot without saying anything at all.
Vita
May 1987 .......................................................... Mangalore, India.
2005 .......................................................... Innisfree House School, Bangalore, India
2009 .......................................................... B.E, R.V College of Engineering, Bangalore, India
June 2012 – August 2012 ............................... Intern, Microsoft, Redmond
Jan 2013 to present ................................. Graduate Research Associate, Department of Computer Science and Engineering, The Ohio State University
PUBLICATIONS
FIELDS OF STUDY
Major Field: Computer Science and Engineering
# Table of Contents
Abstract ............................................................................................................................................. ii
Acknowledgments .......................................................................................................................... iv
Vita .................................................................................................................................................... vi
Publications ....................................................................................................................................... vi
Fields of Study .................................................................................................................................. vi
Chapter 1: Introduction ...................................................................................................................... 1
Chapter 2: Related Work .................................................................................................................... 3
Chapter 3: Online Aggregation ......................................................................................................... 5
3.1 Implementing an online aggregation system .............................................................................. 5
3.1.1 Architecture .......................................................................................................................... 6
3.1.2 Event based VS polling ......................................................................................................... 9
3.1.3 Calculating Estimates and Confidence Interval ..................................................................... 10
Chapter 4: Bounded Time Execution ............................................................................................... 13
4.1 Why is bounded time execution important? .............................................................................. 13
4.2 Actor Model .............................................................................................................................. 14
4.3 DICE Description ...................................................................................................................... 16
4.4 Akka .......................................................................................................................................... 17
List of Tables
Table 1: List of notations used.......................................................... 11
List of Figures
Figure 1: System Architecture Diagram ................................................................. 7
Figure 2: Mapreduce using actor model .................................................................. 15
Figure 3: Actor ...................................................................................................... 18
Figure 4: Shared Mailbox ..................................................................................... 20
Figure 5: AutoExpireMailbox ............................................................................. 24
Figure 6: Demonstrating the effect of change in priority ....................................... 28
Figure 7: Illustrating absence of Query Starvation .............................................. 35
Figure 8: Hysteresis curve for different values of CONSTANT .......................... 39
Figure 9: Control flow in the execution engine .................................................... 40
Figure 10: Varying Priority with independent scans ............................................ 43
Figure 11: Elevator scan ..................................................................................... 44
Figure 12: Parallel Execution of query ................................................................ 48
Figure 13: Shared Scan Optimization .................................................................. 50
Figure 14: Varying Priority with shared scans ..................................................... 51
Figure 15: Lock and Lock-free approach ............................................................ 53
Figure 16: Lock and Lock-free block execution time .......................................... 54
Figure 17: Lock and Lock-free total execution time ............................................. 56
Figure 18: Execution time breakdown ................................................................ 57
Figure 19: Comparing Row Storage and Column Storage ................................. 59
Chapter 1: Introduction
Traditionally most databases are like black boxes. Everything inside a database is isolated from the user. The user has no idea about what is happening while her query is executing. Once issued, the user has to wait until the database returns the result. The response time of the query varies, depending on an array of factors such as the number of queries currently running, the system resources that are available etc. This is where online aggregation becomes very useful [13]. An online aggregation engine continuously returns estimated results with some confidence interval. The user need not wait to get a ballpark estimate of the true value of the result since the system returns estimates of the value at frequent intervals. The one useful feature is that the user can stop the query when she is satisfied with the confidence interval. Even with online aggregation the user has no control over the query execution. She cannot decide how fast or slow her query executes. A solution to this problem is to associate a “priority” or “weight” with each query. This value defines the “importance” of the query. A high value of priority could mean higher importance when compared to a low value of priority. However, this is a static value, which has to be assigned when issuing the query. This provides a coarse level of control to the user. Once issued the user still cannot perform any other operation that will affect the execution rate of the query. To provide true control over the execution
rate of the query, the user should be given the ability to change the priority of the query at runtime. The user should be able to increase or decrease the rate of execution of the query during its execution.
We propose an online aggregation system that takes query priority as a user defined input. The priority of a query dictates how fast or slow the query executes. This priority, associated with each query, can be modified at runtime. If the user wants to increase the rate of execution of a particular query, increasing the priority will bring about such an effect. This ability to change the rate of execution using query priority gives the user a larger degree of control when compared to the previous approaches.
With the conventional approach the user is forced to wait until the query returns with the result. This archaic approach can sometimes become frustrating to the user. Online aggregation answers this problem by returning estimated results at regular intervals. This works well for small to medium sized data. When the size of data becomes very large, it will take a long time for the confidence interval to reach a desired value. This again might keep the user waiting. By providing the ability to change the priority of a query at runtime, the user can change the rate of execution of the query. This ability will also keep the user engaged and provide an interactive experience, which is not possible with conventional querying approaches.
Chapter 2: Related Work
Query scheduling is not a new problem. There has been extensive research in this space, resulting in many approaches to query scheduling. Query scheduling is a very broad topic of study. Scheduling of queries is performed for varying number of reasons. Martens, Rahm, et al. [1] propose dynamic query scheduling to better utilize the system resources. It looks at factors such as CPU and IO to formulate the scheduling algorithm. This is different from what we are proposing. We are looking at user input as the factor for scheduling queries. Pang, Carey, et al. [2] also discuss query scheduling for databases. This paper works along the lines of real-time database systems. It deals with time-constrained queries. It proposes an algorithm called “Priority Adoption Query Resource Scheduling” (PAQRS). System resource the paper mainly talks about is memory, more specifically dynamic memory allocation for queries. The “priority” in the algorithm is for urgent queries. Urgency of a query is dependent on its deadline. Earlier deadline queries are given a higher priority. This differs from our approach since the priority in the above paper is system defined and the priority of a query in our system is user defined. We also do not deal directly with resource scheduling. Garofalakis, Ioannidis, et al. [3] talk about how to handle multi-dimensionality of resources that each query requires. The paper talks about Time-Shared and Space-Shared resources. Even though
these components do occur in our approach we do not directly address them. This paper is orthogonal to our research and will only supplement our effort. Bouganim, Fabret, et al. [4] talk about query fragments scheduling, which we do not deal with in our research. Gupta, Sudarshan Vishwanathan [5] discuss ideas about common sub queries across many queries and how to approach it. Agrawal, Kifer, Olston [9] talk about how to reschedule queries based on their sharable aspect. Even though we look at shareable queries, it is not a factor in our scheduling algorithm. The paper also focuses on batch type jobs such as map reduce, while we focus more on ad hoc type queries. Hoogeveen [10] focus on scheduling with multi-criteria optimization for single as well as parallel environments. Zukowski, Héman, et al. [6] is a very interesting paper that speaks about query scheduling to make better use of shared scans. Unlike elevator scan cooperative scans are not sequential. Cooperative scan decides which chuck of data is the most “interesting” to load. This paper is the closest to some of the problems we solve. We adopt a modified form of elevator scan and so do not overlap with work done in this paper. Additionally, we have another factor, priority, which brings in added complexity. Agarwal, Mozafari, et al. [20] perform bounded execution time with corresponding error rates. Bounded time execution is discussed in detailed in chapter 4.
To the best of our knowledge, our system is the first to look at query scheduling with dynamic user define reprioritization for online aggregation queries.
Chapter 3: Online Aggregation
Online aggregation is an idea put forth by Joseph M. Hellerstein, Peter J Haas and Helen J. Wang in their paper “Online Aggregation” [13]. As already mentioned an online aggregation system returns estimated results with error bounds at regular intervals. Unlike traditional database systems, where the user is kept waiting while the query executes, this approach provides continuous feedback to the user. Online aggregation is not always suitable. It is not applicable for queries that just want to retrieve information stored in a database. It cannot be used when information such as name or address is to be retrieved or inserted into a database. In our research, we do not address such queries. It is useful when performing analysis, such as “average age of users” or “total number of items sold”. If the data is very large and exact answers are not a necessity, online aggregation is a perfect match. It always informs the user about estimated values so that the user can terminate the query if she is satisfied with the estimate and the corresponding confidence interval.
3.1 Implementing an online aggregation system
In this section we will discuss how we have built the online aggregation system. Our system is written entirely in java. It is built taking query reprioritization into account. All the components are asynchronous and highly parallel. By being asynchronous it has a
very good reaction time to a change in query priority. We have a threaded execution framework that can execute a query over different data blocks in parallel. This execution engine can also stop a query in the middle of its execution. It also has the unique ability to pause a query execution. When resumed the query execution will continue from the point it was paused without any need to recalculate results.
3.1.1 Architecture
Like any other online aggregation engine, our system also returns continuous results to the user. In addition to that the user of this system has the flexibility to increase or decrease the rate at which her query is executing. If the query execution is slow and she wants to see the results at a faster rate, all she has to do is increase the priority of the query. A user of this system need not necessarily be the end user viewing the results. Another system, that feeds inputs, could be used to leverage the abilities of our system.
Figure 1 describes the architecture of the online aggregation system. It has two main components
- Master
- Slave
Master
This component is the interface for the user. It accepts queries and returns results in an online manner. The master also accepts changes in priority for a particular query. The
master has two components 1) Query Catalog 2) Aggregator. The query catalog as the name suggests stores information about each query. It stores catalog information such as number of rows processed so far and the updated result of every query. It can also store other information such as how fast or slow the user wants to see the results for her query.

**Figure 1: System Architecture Diagram**
This is different from the rate of execution of the query. This information tells the system about how frequent the user wants to view a change in the result. For example, let us assume that initially the user is viewing change in result every 4 seconds. As the query
progresses she might want to increase this rate, setting it to 1 second, to catch the finer changes in the estimated result.
The aggregator module is responsible for aggregating the results that are returned by the slaves. This module is important when the system has more than one slave node. If the system consists of a single slave node, then the slave node can perform all the aggregations. In case of a distributed system the data is partitioned over multiple slave nodes and needs additional aggregation at the master end.
**Slave**
The slave forms the core of the entire system. It manages the execution of all queries in the system. This component is highly parallel and has an asynchronous implementation. Every module in this component runs independently of the other modules. This is very important not only for an online aggregation system but also for very quick response time in case of a change in priority of a query. The catalog modules are for storing and retrieving information about the queries.
Query catalog stores information about each query such as number of rows processed, rate of execution and current priority of a query. This information frequently changes and is updated after every cycle of execution of the query. It has a more detailed explanation in chapter 5.
Execution catalog stores the execution information of each query. It holds information such as the number of blocks executed so far as well as startBlock and maxBlock values. The importance of startBlock and maxBlock is discussed in chapter 5.
Executor and Aggregator are the modules responsible for the actually execution of a query. These components are intricately connected. Executor manages multi-threaded execution of the query. It is asynchronous and can instantly include a newly issued query into its current execution cycle. The aggregator performs the aggregation on the data. It provisions basic aggregations like SUM, COUNT, AVG, MIN, MAX. It also has added features like lock and lock-free aggregation.
### 3.1.2 Event based VS polling
Our initial implementation used Jetty to send and receive data between master and the slaves. Jetty is a HTTP webserver. It has many features like SPDY, Web Sockets and JNDI that are very useful for a distributed application. Jetty uses a threaded model to handle concurrent requests. Each query request is handled from start to finish by a single thread. Any I/O calls, like a remote service call, is synchronous. With synchronous I/O calls, the thread is blocked and is idle till the I/O call returns, effectively blocking incoming requests.
In order to deal with idle time of the thread when it is blocked on I/O operations, jetty introduced a feature called continuations. This feature enables a connection to be suspended, which frees the thread. The thread can be reused when the connection is resumed. This feature is useful for an online aggregation system where the execution engine has to continuously return results back to user.
Continuations does not scale well with increase in number of concurrent queries. As the number of concurrent queries increased, the frequency of suspending and resuming
connections also increased, introducing additional overhead in the system. This is due to the high volume of result messages sent from the slave back to the master. Jetty did not meet the throughput requirements of our system.
To deal with this problem, we moved to an event driven system. Here the thread is not blocked on I/O calls instead it is interrupt driven. When a thread issues I/O calls, instead of waiting for the calls to return, the thread continues to process other requests, and only comes back when the I/O calls return. The event driven model scales well as the number of queries increase. We made use of an event driven approach that met our throughput requirements.
3.1.3 Calculating Estimates and Confidence Interval
As already stated, online aggregation returns estimated results with some confidence interval. To calculate the confidence interval, COUNT and VARIANCE values for each group are needed. These values are calculated in each thread of the execution engine. The variance and count are combined, from all threads, resulting in a single value of count and variance for each group in the result. The procedure to calculate combined variance is given below. The table describes each variable needed in the formula
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td>$s^2_h$</td>
<td>variance of group $h$</td>
</tr>
<tr>
<td>$n_h$</td>
<td>number of tuples in group $h$</td>
</tr>
<tr>
<td>$n_{hi}$</td>
<td>number of tuples belonging to group $h$ from the $i^{th}$ query</td>
</tr>
<tr>
<td>$m_{hi}$</td>
<td>mean of the group $h$ from the $i^{th}$ query</td>
</tr>
<tr>
<td>$m_h$</td>
<td>mean of the group $h$ from all queries</td>
</tr>
<tr>
<td>$v_{hi}$</td>
<td>variance of the group $h$ from the $i^{th}$ query</td>
</tr>
<tr>
<td>$\bar{\sigma}{\hat{\tau}}$</td>
<td>variance of the estimator for the measure SUM</td>
</tr>
<tr>
<td>$\bar{\sigma}{\hat{\gamma}}$</td>
<td>variance of the estimator for the measure AVG</td>
</tr>
<tr>
<td>$\bar{\sigma}{\hat{\rho}}$</td>
<td>variance of the estimator for the measure COUNT</td>
</tr>
<tr>
<td>$H$</td>
<td>Total number of groups in the union of all the queries</td>
</tr>
<tr>
<td>$N$</td>
<td>Total number of tuples in the table</td>
</tr>
</tbody>
</table>
Table 1: List of notations used.
Below is the formula for combining many variances into a single variance, per group.
\[ s_h^2 = \frac{1}{n_h - 1} \left( \sum_{i=1}^{numQ} n_{hi}(m_{hi} - m_h)^2 + \sum_i (n_{hi} - 1)v_{hi} \right) \]
The derivation of the formula is discussed in DICE [21]. After combining variances the confidence interval, for each group, is calculated using the below formula.
\[ P = \frac{n_h \times N}{\sum_{h=0}^{H} n_h} \]
\[ C.I = (m_h \times P) \pm (1.96 \times s_h \times P) \]
The combining of variances has to be performed both on the slaves as well as the master. At the slave side, combining is performed across the results from different execution threads. At the master side, the combining is done on the continuous results returned by the slave.
Chapter 4: Bounded Time Execution
4.1 Why is bounded time execution important?
Bounded time execution, in context of database, is to execute a query within a specific amount of time. There are many time critical applications that need response time to be within a specified time. Some examples of such applications are control systems at airports, stock exchanges, medical applications etc. All these applications are time constrained. The response time always has to be within the specific time limit. Varying response time could be the difference between winning and losing millions in case of stock exchange and much larger consequences in case of medical applications. It is imperative that query response is retained within the specific time.
Bounded time execution does not necessarily entail real time responses, even though this is often the case. Bounded time can also signify predictable response time. To design an execution engine with predictable query response time is a non-trivial task.
There are different ways to handle time bound execution, one of which is to use sampling. Instead of processing the entire data a sample of data is processed, returning estimated results with error bounds. Such an approach is shown in BlinkDB [20], where samples of various resolutions are built offline. Depending on the response time and the
error bounds, the query is executed on the appropriate samples. DICE [21] is another system that also uses sampling to perform time bound execution of speculative queries.
4.2 Actor Model
DICE uses the actor model for the architectural design. As mentioned in the previous chapter the actor model is more scalable and built for highly concurrent applications.
In an application using the actor model the “actor” forms the building block of the application. In the actor model, information flows in the form of messages. Typically an actor receives a message and performs appropriate computation in response to that message. When the computation is complete the actor can either reply with another message or simply do nothing.
The actor model adheres to the principle that everything is an actor. In this aspect the actor model resembles object oriented programming model where everything is an object, but is different in terms of execution flow. Object model typically has a sequential and synchronous implementation, while the actor model is typically built for concurrent and asynchronous applications.
An actor in response to a message it receives can perform any of the below tasks:
- Perform some computation based on the message.
- Forward the message to other actors.
- Can create a new actor to process each message.
All of the above mentioned tasks could be done sequentially and synchronously or asynchronously and in parallel. It is the parallel and asynchronous execution that makes the actor model such a powerful concept.
The actor model being asynchronous and concurrent has no global actor to coordinate between the various actors in the system.
Figure 2: Mapreduce using actor model
Figure 2 shows how a simple mapreduce program can be implemented using the actor model. The major difference is that here each map actor is a single thread compared to a java virtual machine in a typical mapreduce implementation. Also, with the actor model reducers needs to be split in to reduce and aggregator (Agg) actors. The reduce actors perform the task of shuffle and sort. The aggregation of the values are done using the aggregator actor. Here all the data is transferred in the form of messages. The <Key,Value> pair emitted from the map actor can be sent to the reduce actor in the form of a message. The correct reduce actor can be chosen using an appropriate hash function. A good hash function can take care of skew in data as well.
4.3 DICE Description
DICE is a distributed and interactive cube exploration system. DICE consists of three main components.
Faceted Cube Exploration – The systems introduces a novel session-oriented cube exploration model. It introduced a facet-based cube exploration model. It models the transitions as traversals from one facet to the next. The permitted traversals are parent traversal, child traversal, sibling traversal and pivot traversal.
Distributed Execution Engine – DICE has a distributed execution engine that employs a hierarchical master-slave approach, such that all queries are issues to the master and responded to by the master. The execution engine delivers sub-second latencies for query execution over a fixed user-defined sample of data. The execution engine supports parallel execution of queries over large amounts of partitioned data. The execution engine
is highly scalable and has been tested up to 50 nodes while retaining interactive latencies in query execution.
*Speculative and Bounded Time Execution* – It also introduces the concept of speculative execution. Speculative queries, which are based on the current executing query, are executed in anticipation of the user’s next cube traversal. Using the current facet the system enumerates all the possible traversals, which are then prioritized and executed within a fixed bounded time of 5000ms. The results of these speculative queries are cached to decrease the execution time of the next traversal in case of successful speculation.
### 4.4 Akka
Both DICE and our online aggregation system make use of a framework called Akka. Akka is an open source implementation of the actor model. It has support for both synchronous and asynchronous implementation. Having a non-blocking IO framework makes it an ideal candidate for implementing a distributed event driven system. Once all components of the architecture are implemented scaling out, with akka, is as simple as installing the components on a new node and connecting it to the system. Akka also has fault tolerance built into the framework, which alleviates the need for the application to implement fault tolerance.
4.4.1 Components
Akka has many components. We will discuss two components that are essential to our implementation of bounded time execution.
4.4.1.1 Mailbox
Every actor is associated with exactly one mailbox. All the messages for an actor are sent to its mailbox. Mailbox is the element that connects the receiving actor with the message sender. The actor processes messages from its mailbox in order of their arrival. Internally the mailbox is implemented as a queue. All the different senders enqueue their respective messages in the mailbox and the receiving actor dequeues the messages and processes them. An important point to note here is that message order is maintained per sender, but not across senders. What this means is that, the messages from different senders will not have an ordering between them.

Figure 3: Actor
The default mailbox follows first in first out (FIFO) approach. This is the preferred implementation. There are other mailbox implementations such as priority mailbox. Here, dequeue operation is based on the priority of the messages in the queue. This will be useful in systems that support priority, such as ours, where there are multiple senders to a single receiving actor. Even though there is no relative ordering between the multiple senders, the priority of the message will ensure an ordering between them after the message is enqueued.
Another implementation is the shared mailbox. Unlike the previous approach, a single mailbox is shared across all the actors. This mailbox supports concurrent operations. This implementation is useful when load balancing across all the actors is required. Figure 4 describes this type of implementation.
The mailbox implementation might look like a performance bottleneck, but it is not the case. The entire logic for obtaining the next message is in the dequeue operation. An entire scan of the mailbox is not needed.
4.4.1.2 Router
A router is an actor whose only task is to route the messages to other actors. This forms a very critical part of the system. This is the component where different routing algorithms can be implemented. We will discuss two routing algorithms that play a role in bounded time execution implementation.
**RoundRobinRouter**
This is the default router. As the name suggests it performs round-robin routing. It routes messages to different actors in a round robin manner. Whether this is a good load balancing approach is debatable. If each message takes the same amount of time to process then this router divides work equally across the actors. On the other hand if the processing time of each message is not equal, this approach is not optimal.
**SmallestMailboxRouter**
The problem with round robin approach is when each message takes varying time to process and the time is not known prior to processing the message. Messages that take long to process might be routed to the first actor and messages that take small amount of time to process might be routed to the second actor. The second actor will complete all its messages and remain idle while the first actor is still processing its messages. To overcome this problem, the smallest mailbox router is used. This router routes messages to actors that have finished processing their respective previous message and are waiting for the next message. If the previous example is considered, both the actors will be occupied and the resources are completely used. This is the router used by DICE.
**4.5 Bounded Time Implementation**
Akka has no implementation that supports bounded time execution. Bounded time execution needs support for time out. DICE has a hard limit of 5000ms for the speculated query execution, which implies that after 5000ms all the currently executing queries have
to be stopped and all the pending queries in the mailbox have to be invalidated. None of the components of akka support such a requirement, which meant a custom implementation is required.
Out of the two requirements, stopping a currently executing query is simpler. This is achieved by interrupting the thread that is executing the query. Interrupting the thread at the application level is not sufficient. There is a separate thread inside the database context that is still executing. It has to be made sure that the interrupt is propagated to the executing thread in the database as well.
The solution to the second requirement is more complicated. One major problem with time out in a distributed system is clock synchronization. The 5000ms time limit should start counting down when the master sends the speculated queries to the slave. After 5000ms the queries have to be invalidated at the slave node, which means the slave node should be aware of the exact time the count down started at the master node. This poses a time synchronization problem.
One solution to synchronize the clocks across the cluster is to use Network Time Protocol (NTP). Using NTP, time across all the nodes in the cluster can be synchronized. However, this is not a viable solution. Dedicated NTP servers are required to perform clock synchronization. Scaling out the cluster will now have added overhead of clock synchronization. The biggest problem with this approach is that it still might not guarantee synchronization at the millisecond level. This is a very crucial limitation and given that DICE is dealing at millisecond level, the problem becomes more complicated.
4.5.1 AutoExpireMailbox
We implemented a new mailbox called *AutoExpireMailbox*. This mailbox is implemented considering auto expiry of messages after 5000ms. The implementation does not assume any form of clock synchronization between the nodes in the cluster. The algorithm for timeout is implemented at the slave nodes.
As stated above, the problem is to determine when the count down starts. To solve this problem we implement a new mailbox in the Akka system, *AutoExpireMailbox*. The mailbox only maintains queries that are within 5000ms of the count down start time.
*AutoExpireMailbox* uses an unbounded concurrent queue to hold query messages. It also makes use of a variable, *startTime*, which stores the timestamp of the first query message that is enqueued. This indicates the start of the count down. During every dequeue operation, we check the time difference between the time dequeue operation was invoked and *startTime*. If the difference is greater than 5000ms, we flush the query message queue, reset *startTime* value and return null. If the difference is less than 5000ms, we return the head of the queue and remove the query message from the queue. This doesn’t not add overhead since the check is performed only on a dequeue operation and each check has O(1) runtime.
4.5.1.1 Algorithm
Below is the pseudo code for the enqueue and dequeue operation in *AutoExpireMailbox*.
```python
1 enqueue(queryMessage)
2 if startTime == -1
3 startTime = getCurrentTime()
4 queue.add(queryMessage)
```
Algorithm: Enqueue
```java
def dequeue()
if queue is empty
return null
time = getCurrentTime()
diff = time - startTime
if diff >= 5000
queue.flush()
startTime = -1
return null
else
return queue.pop()
```
Algorithm: Dequeue
Chapter 5: Query Reprioritization
5.1 Why is query prioritization important?
In any database, which runs queries in parallel, not all queries have the same importance. There are always few queries, which are more important than other queries. Without prioritization a database cannot differentiate such queries. With current systems we can assign a priority to a query at the time of issuing the query. This is static priority. The priority remains the same throughout the life span of the query execution. This definitely helps when we know the exact query and its importance. In case of exploratory analysis the user might not know the exact query that gives the results she desires. In such cases the user will not know the importance of a specific query beforehand. She might find out as she is viewing estimated results in an online fashion. In a system that supports static priority, she cannot change the priority of the query after issuing it or while viewing the estimated results in an online manner.
Online aggregation does not guarantee faster execution of the query. It only provides the ability for the user to view the estimated value of the result at regular intervals. A query over large data is going to take relatively long time to attain low error bounds. Queries that run in the order of several seconds are not necessarily at an interactive level. Research such as Nandi, Jagadish [23] and Kamat, Jayachandran, et al. [21] has shown
how important it is even for queries over large data to be interactive. If the rate of execution of the query can be changed at runtime, by changing the using user-defined priority, the execution can be done at a more interactive level when compared to a simple online aggregation system.
Another use case for dynamic priority is ad hoc queries. These queries are when a ballpark approximation of the true result is required. Depending on the estimate result that is returned, the user might want to speed up or slow down the execution rate of the query. In an online aggregation system, results are returned to the user only at regular intervals. The system does not expose anything else. The user has to be contented with the rate at which the confidence interval changes. Even if she desires a faster decrease in confidence interval, it cannot be achieved with current online aggregation system. Current online aggregation engines do not address the above-mentioned problems. A solution to these problems is to allow the user to change the priority of a query at runtime. Doing this will provide the user with a fine-grained control over the execution of the query. The user can then increase, decrease, pause or stop the execution as she pleases.
Figure 6: Demonstrating the effect of change in priority
Figure 6 describes the idea behind runtime reprioritization. The graph plots time in milliseconds on the X-axis and number of rows processed on the Y-axis. For simplicity we use only two queries, Query-1 and Query-2, issued by different users. Both these queries are run on our online aggregation engine. They start returning estimated results as soon as they are issued. Initially, both the queries have equal priority, i.e. at the time of issuing both the queries have the same priority value. We observe that during the initial stages of execution, both these queries process equal number of rows over time, right up to 4000 milliseconds. After viewing the estimated results for a couple of seconds, the user of Query-1 increases the priority of Query-1. Immediately the system takes the change in priority into account and starts processing Query-1 at a faster rate compared to Query-2. This is visible from the graph. The line depicting rows processed for Query-1 starts rising
and completes at the 16000-millisecond mark. At this point the system is running only Query-2 and hence there is a rise in the rows processed for Query-2 until it completes. The line at the top shows the total number of rows processed over time across all queries. The remaining line, passing in between Query-1 and Query-2, illustrates what happens when there is static prioritization. In this case, no change in priority is allowed at runtime, resulting in both queries running at the same rate and completing at the 26000-millisecond mark. The reason why all the query lines flattened out at the end is because the queries have completed their execution between the two time intervals.
5.2 Varying Rate of Execution
In our system the rate of execution of queries can be changed at runtime. This is made possible by providing the user the ability to associate a query with a dynamic priority. The priority can be changed during the execution of the query. This value decides the rate of execution of a query. The number of parallel queries that the system can handle is decided on the resources available. There is no fixed universal number. The system does not restrict on the number of parallel queries. Like any other database system, if the number of queries exceeds what the system can handle, performance of the system decreases.
The rate of execution of a query can be modeled in different ways. One way is time slicing. This is the traditional approach taking in most operating systems today. At the kernel level the each process gets a certain time to execute before it swapped with another process. This happens in a round-robin manner. Our system uses the number of
rows processed as a factor to decide the rate of execution. More number of rows processed equates to higher execution rate. Each query is executed for a certain number of rows before being swapped by another query. Intermediate query result is sent back to the user each time the query is swapped. The current priority of the query decides the number of rows it processes each time, before it is swapped. A query with higher priority processes more number of rows before it is swapped as compared to a query with lower priority. The value of the priority cannot be taken as an absolute term for deciding the number of rows to process. It has to be normalized before execution. This is important since a query with a very high priority will execute for a very large number of rows. If this query is IO bound it will be blocked for most its execution time. This inherently blocks the other queries running and an online aggregation engine cannot have long blocked periods. For example – If Query-1 needs 4 seconds to execute 1 million tuples, all other queries are blocked for 4 seconds. Therefore, it becomes essential that we break the execution into chunks and normalize the priority. We describe how we normalize the priorities.
\[ P_{TOTAL} = \sum_{i=1}^{n} P_i \]
\[ P_{wi} = \frac{p_i}{P_{TOTAL}} \]
First we sum priorities \( P_{TOTAL} \) of all the queries currently executing. The weighted priority \( P_{w1} \) is then calculated. This weighted priority decides how many rows a query processes before being swapped.
As mentioned before, we define the basic unit of storage as a block. Each block consists of a fixed number of rows. Queries are executed at blocks level granularity. Research [19] has shown that processing data in blocks instead of a single row at a time, results in better performance due to pipelining and processor cache.
We execute queries in a round robin manner. A calculated number of blocks are processed per query before being swapped. A cycle is complete when all the queries have executed additional blocks of data. All queries are always executed in one cycle. In order to reduce blocking delays we introduce a parameter, \( BLOCKS\_PER\_CYCLE \). The “BLOCKS” in the parameter name refers to blocks of data and not blocking delay. The value of this parameter indicates the number of blocks to execute per cycle. For example if \( BLOCKS\_PER\_CYCLE \) is set to 10000, 10000 blocks of data is processed across all the queries per cycle. If there are two queries running with priorities of 25 and 5 respectively, Query-1 processes 8400 blocks per cycle and Query-2 processes 1600 blocks per cycle.
\[
P_{TOTAL} = 25 + 5 = 30
\]
\[
P_{w1} = \frac{25}{30} \approx 84 \, (84\%)
\]
\[
P_{w2} = \frac{5}{30} \approx 16 \, (16\%)
\]
Query-1 processes 84 percent of 10000 blocks, 8400 blocks and Query-2 processes 16 percent of 10000 blocks, 1600 blocks. This is how the rate of execution is decided.
The $BLOCKS\_PER\_CYCLE$ parameter is deeper implications. It, along with the number of rows per block, decides the frequency at which the user is provided with a new estimated result. This is different from the rate of execution. This signifies how frequent the user views a change in estimated result. If the $BLOCKS\_PER\_CYCLE$ has a low value, the result is sent back to the user at a high frequency. On the other hand if the value is very high the result is sent back at a very low frequency, longer intervals.
$BLOCKS\_PER\_CYCLE$ also affects the total number of context switches in the system. Context switching in our engine is switching between query executions. This entails procedures such as saving the current query’s execution info, updating query catalog, sending the result back etc. However, sending the result back does not affect the time, since it is done asynchronously in a separate thread, but all other procedures add to the overhead. When many queries are simultaneously executing, context switching cannot be avoided. The goal is to find a balance between context switching overhead and query execution progress.
\[
Context \ Switches_{Cycle} = \ Number \ Of \ Queries
\]
\[
Number \ of \ Cycles \ = \ \frac{Total \ Number \ Of \ Blocks}{BLOCKS\_PER\_CYCLE}
\]
\[
Context \ Switches_{TOTAL} \ = \ Context \ Switches_{Cycle} * Number \ of \ Cycles
\]
\[
Time_{Effective} \ = \ Time_{Process\ Blocks} - Time_{Context \ Switches_{TOTAL}}
\]
The above equations are self-explanatory. We have to increase $T_{effective}$ by reducing $T_{Context\ switches_{TOTAL}}$. This is achieved by decreasing the number of cycles, which is in turn accomplished by having higher value of $BLOCKS\_PER\_CYCLE$. The consequences of having a high value for $BLOCKS\_PER\_CYCLE$ are already discussed.
Finding a balance between context switching overhead and query execution progress is not a straightforward approach. It depends on lots of factors like resources available, query type (IO bound or computation bound), nature of the underlying storage etc and hence varies across different usage of the system. Looking at all the above aspects, choosing a good value for $BLOCKS\_PER\_CYCLE$ is non trivial and hence the parameter is made configurable.
5.3 Query Starvation
In any scheduling algorithm starvation is always a problem. Starvation is when a process does not get sufficient resources to execute. This happens when the scheduling algorithm always has high priority processes coming in. In our context starvation equates to query starvation, when a particular query does not execute for a long time. In an online aggregation system, which provides the ability of dynamic query reprioritization, query starvation is a real possibility. In our online aggregation engine, query starvation equates to a query being blocked for a long time because of other high priority queries in the system. By definition of online aggregation this is not allowed. A query should always
return estimated results at regular intervals without being blocked for a long period of time.
A common solution to process starvation is employing a technique called Aging. Each process has an aging factor. This factor increases every time a process is denied resources when requested. As the aging factor increases the priority of the process is also increased. Some systems also have an upper bound on the aging factor, after which the process is forcefully given resources.
Incorporating an Aging factor is one approach. Instead, our execution engine avoids starvation altogether. This is achieved by simply following a round robin approach in selecting the next query for execution. The priority of the query is not considered when choosing the next query. The priority rather, as explained before, decides how many blocks of data are processed in a cycle.
For all the experiments we use machines having 4 GB memory, intel xeon quad core processors and 720 GB of disk space. The cluster has a 1 Gbps switch. Data is row-oriented with 5 million rows and 6 columns, consisting of strings, integers and floating-point data types.
Figure 7: Illustrating absence of Query Starvation
Figure 7 demonstrates how we avoid query starvation. Query-1, Query-3, Query-4 are executed with a priority of 10 and Query-2 are executed with a priority of 1. Query-1 and Query-2 are initially issued. Query-3 is issued after 2 seconds and Query-4 is issued after 4 seconds. Even though Query-3 and Query-4 are issued at a later time with higher priority, Query-2 continues to execute, at a much lower rate, without being starved. The system is capable of handling many more queries, but only 4 are used in this experiment for the sake of simplicity. The various bends in the lines are because of queries being issued and queries completing their execution.
5.4 Hysteresis
What happens to the system if the user accidently or intentionally misuses the ability to change priority of a query at runtime? As already mentioned, another system can leverage the abilities of our execution engine. For example, consider we have gestureGB [22] feeding queries and priorities based on the user’s gesture. When the user of gestureGB performs a burst of rapid gestures, causing the priority of the query to change continuously, the execution engine will have problems executing other queries currently running in the system. Even though the system remains accurate in the execution of individual queries, it introduces unpredictability in the rate of execution of queries with respect to its priority. Hysteresis has to be dealt with at the execution level. There are two approaches that we discuss
- Hard Limit on the number of changes.
- Introducing a hysteresis factor into query priority.
**Hard Limit**
This approach sets a hard limit on the number of changes in priority for every query. This limit can be a universal constant for the entire system, which means each query gets the same limit. This could be unfavorable since the system will consist of users with different access levels. A privileged user will end up having the same authority as an unprivileged user. A way to deal with this would be to make it a user specific constant. A trusted or a privileged user is allowed more number of changes per query while an untrusted user is
allowed fewer changes per query. With this approach the limit has to be monitored per user basis by the administrator. Any changes to the limit for a user has to be done manually.
**Introducing a Hysteresis factor**
Hysteresis is still a possibility with the hard limit approach. The system is still affected if a trusted user accidently changes the priority of a query at a high frequency. In order to avoid this, variability needs to be introduced into the query priority. This variability should be a function of the number of changes in priority for each query. Let's call this hysteresis factor. The hysteresis factor should have a positive effect for the initial few changes in priority. Having a negative impact initially on the change in priority of a query contradicts the concept of changing priority at runtime. As the number of changes increases, beyond a threshold, the hysteresis factor should have a negative effect on the priority of the query. It should act like a penalty. The nature of this function suggests a Gaussian like distribution. The below formula is used to calculate the priority with hysteresis.
\[
P_H = P_u \times \frac{1}{e^{(2)(\text{Number of changes} - \text{CONSTANT})}}
\]
\[
P_H = \text{Priority with Hysteresis}.
\]
\[
P_u = \text{User defined priority}.
\]
The \emph{CONSTANT} variable decides how soon the hysteresis factor has a negative effect on the query priority. Higher value of the constant results in more tolerance, which means that the system will allow more changes in priority before having a negative effect on the priority. A low value for the constants results in less tolerance, allowing fewer changes before it has a negative effect. The value of \emph{CONSTANT} is configurable. Like the first approach it can be a universal constant or a user specific constant. In the later case, a privileged user is allowed higher tolerance, which denotes more changes in priority before being penalized.
Figure 8 shows how the hysteresis factor behaves for different values of \emph{CONSTANT}. The X-axis is the user-defined priority and the Y-axis is the priority with hysteresis factor. Each curve is for a different value of \emph{CONSTANT}. At a value of 20, the blue curve, the system allows more changes in a positive effect before having a negative effect on the priority. As the value of the \emph{CONSTANT} decreases so does the tolerance in the system. At a very high number of changes in the priority, the priority with hysteresis factor simply reduces to 0, which is the lowest priority.
5.5 Control Flow
Figure 9 describes the flow in our execution engine on the slave nodes. The execution engine first requests for a query from the query catalog. As mentioned before the queries are executed in round robin fashion. The weighted priority of the query is calculated using the formulae mentioned in section 5.2. The calculation is performed on the latest priority of the queries running in the system. An important point to note is that, the execution thread is separate from the thread that updates the priority of the query. This is needed for fast response time in case of change in query priority. With separate threads
and asynchronous model of execution, any change in query priority is reflected instantaneously.
Once the weighted priority is calculated, we determine the number of blocks to process for the current query in this cycle. Next, the engine acquires the execution information of
Figure 9: Control flow in the execution engine
the query from the execution catalog. This information consists of fields such as the number of blocks executed, next block that has to be executed etc. The execution information consists of more fields, which are covered in the following sections. Once the information is obtained, the query is executed in parallel. Each executing thread is assigned one block to be processed. After all threads complete their execution, the result is calculated and sent back to the master. The master will perform post aggregation and return the estimated result back to the user. On the slave side, the execution engine updates the execution catalog and the query catalog. The query catalog contains information needed to collect statistics about the query such as rate of execution, number of rows processed so far etc. The same procedure is followed for the next query.
5.5.1 Algorithm
Below are pseudo codes for the execution engine.
```
calculateWeightedPriority(P)
for q in queries
p = getQueryPriority(q)
total = total + p
Pw = P / total
return Pw
```
Algorithm: Calculation of weighted priority.
Algorithm: The main execution.
5.6 Elevator Scan
In the previous sections we saw how the execution engine implements query reprioritization. We did not discuss about tables the queries were run on. All the queries were run on the same table, which means there was data overlap over all the queries. We observe that Query-2 and Query-3 ran over the same table, there was data overlap between them. Both the queries processed the same data to compute their results. When the entire table cannot fit in memory, pages are requested from disk. This is traditionally implemented in databases by using an LRU cache. The pages are cached after reading from disk. This constitutes an IO operation, which are expensive. The disadvantage of
the LRU approach is that if one query starts at a different time, the cached pages will already be swapped out before they can be reused.
Figure 10: Varying Priority with independent scans
In this case, Query-2 and Query-3 are making separate IO calls even though they operate over the same data. Is there a way to exploit this overlap? Is there a way to minimize the IO cost?
There are been work done in this area. Unterbrunner, Giannikis, et al. [7] talk about response time predictability using elevator scans. Wang, Das Sarma, et al. [8] and Agrawal, Kifer, Olston. [9] are recent work done in this area. They both examine how to
use shared scans to achieve faster processing for batch-oriented system such as MapReduce. This model can easily extended to an ad-hoc type of system, such as ours.
Elevator scan is simply a sequential scan, of the table, that is always running. Incoming queries attach themselves to the table scanner, which is scanning some part of the table, and begin executing. The queries detach from the scanner when they are done processing the entire table. This is a cache efficient approach since all queries are executed on the data block paged in from disk. Once processed, that block of data will never be paged in for those set of queries. This results in constant IO cost, for reading data, irrespective of the number of queries executing concurrently. Figure 11 illustrates how an elevator scan works. The table scanner is currently scanning from block A to block B. All queries that have not finished processing these blocks operate on the data.

Figure 11: Elevator scan
5.6.1 Query Priority With Elevator Scan
Elevator scan introduces the ability to share table scans between many queries. This implies that queries that share scans have to run simultaneously. Previously, with independent scans, each query processed different number of blocks per cycle of execution depending on its weighted priority. With shared scans this presents some problems. If each query that is sharing the scan has to process different number of blocks per cycle, then maintaining and calculating the different blocks processed for each query in the shared scan becomes a tedious process. To avoid this overhead, we bring in table priorities. In this technique, priorities are calculated per table. The effective priority of the table decides the number of blocks that will be processed for a given cycle. Any change in priority of a query affects the table priority as well. Below are the formulae for calculating the weighted priority of a table.
\[ P_{Table_t} = \sum_{i=0}^{m} P_i \ \forall \ Query \ i \ on \ Table \ t \]
\[ P_{Table_{Total}} = \sum_{t=0}^{T} P_{Table_t} \]
\[ P_{Table_{wt}} = \frac{P_{Table_t}}{P_{Table_{Total}}} \]
5.6.2 Algorithm
With shared scan there has to be different algorithm for execution. The algorithm for shared scan is given below. All operations are done at a table level. Like the previous approach, the tables are chosen in a round robin fashion. Once the table is decided, the execution engine calculates the weighted priority of the table. This is done using the formulae mentioned above. It can be argued that summing the query priorities for a table might not be an ideal method to calculate a table’s effective priority. For instance, let us consider a table, Table-1, having a large number of low priority queries and another table, Table-2, having a single high priority query. In a situation where the summation of the query priorities of Table-1 is greater than that of Table-2, Table-1 will result in having higher weighted priority. This might not be the desired effect with respect to the high priority query on Table-2, but considering the system as a whole, assigning higher effective priority to Table-1 would prove to be more beneficial. Another option is to use the mean of the query priorities, per table, instead of sum. The right approach depends on how the system is used and hence we have implemented this as a plug-and-play feature. A custom implementation for calculating the effective priority of a table can be used.
Algorithm: The main execution using shared scan
```java
execute()
while(true)
table = getNextTable()
if table == NULL
continue
info = getTableInfo(table)
Pweighted = calculateWeightedPriority(table)
numBlocks = getNumBlocks(Pweighted)
blocks = getTableData(table, numBlocks)
queries = getQueriesForTable(table)
for block in blocks
executeQueriesInParallel(queries, block)
updateTableCatalog(table, info)
for q in queries
if q is not complete
putQuery(table, q)
if table has queries
putTable(table)
```
Algorithm: Calculating the weighted priority for shared scans
```java
calculateWeightedPriority(currentTable)
for t in tables
queries = getQueriesForTable(t)
for q in queries
p = getQueryPriority(q)
tableTotal = tableTotal + p
if t == currentTable
currentTableTotal = tableTotal
allTablesTotal = allTablesTotal + tableTotal
Pweighted = currentTableTotal/allTablesTotal
return Pweighted
```
5.6.3 Parallel Execution for Elevator Scan
In an independent scan, executing a query in parallel is a trivial task. Each block of data can be processed in a separate thread. If there are many blocks for a query to execute, a thread pool can be utilized to limit the number of threads created.
Figure 12 describes the idea behind parallel execution of a query. For each cycle, the number of blocks to process is calculated. The blocks of data are requested form the underlying datastore. In case an independent scan only the current query is passed to each executor thread and for shared scan all the queries for the particular table are passed to each executor thread.
Figure 12: Parallel Execution of query
Parallel execution for shared scan is a non-trivial task. Since each query can start and end at different blocks, extra care has to be taken during execution. The execution engine has to make sure that a block is processed only once for each query. Since the number of blocks to process per cycle, for any query, can change at runtime, we might wind up processing the same block twice, for a query. For example, let us assume a query starts at block 5000, and it has to end at block 4999. If the blocks per cycle for the table was 10, we would process 10 blocks in parallel. This would mean blocks 5000 - 5009, 5010 - 5019 and so on till blocks 4990 - 4999 are processed in parallel. With the ability to change the priority of a query, let us assume the blocks per cycle changed to 20. With this change, the execution engine could have to execute blocks 4990 - 5009 in parallel, but the query has already processed blocks 5000 – 5009 at the start. This condition has to be avoided.
An easy way to deal with this is to associate a query with all the remaining blocks that have to be executed for it to complete. Even though this solves the problem, it comes at a cost of high memory consumption. The memory consumption increases linearly as the number of concurrent queries increases. We develop a naïve algorithm using only two variables to identify if a block is already processed or not.
Our algorithm uses only two variables per query, \textit{startBlock} and \textit{maxBlock}. The \textit{startBlock} variable holds the starting block number of the query. This value can be different for different queries on the same table, depending on when the query is issued with respect portion of the table that is being scanned. The \textit{maxBlock} variable stores the highest block number processed so far. It is updated every time the execution of the query for each cycle is complete. The \textit{maxBlock} always lies between the \textit{startBlock} and the total number of blocks for the table. Only blocks between $0 - \textit{startBlock}$ and between $\textit{maxBlock} - \text{total block count}$, are processed in each cycle. In the previous example, \textit{startBlock} will have value 5000 and \textit{maxBlock} will have the value of 10000. When the execution engine executes blocks 4990 – 5009, only block 4990 – 4999 are executed, since other blocks, 5000 – 5009, do not meet the condition. Figure 13 describes the technique. The portion in red (between \textit{startBlock} and \textit{maxBlock}), are the already executed blocks of the table. The remaining portion, in blue, is the blocks yet to be executed. The algorithm is given below.

Algorithm: Parallel execution method for shared scans
After applying all the above technique we can see an increase in the over performance of the system. Figure 14 describes the benefit of using shared scans. The same experiment, as described in Figure 10, is run again, this time with shared scans. As before, Query-1 is run on Table-1 while Query-2 and Query-3 is run on Table-2.

Figure 14: Varying Priority with shared scans
This time we see that when the priority of Query-2 is increased, because of shared scan, the rate of execution of Query-3 also increases. We also observe that all three queries complete sooner when compared to the previous approach.
5.7 Lock-Free Aggregation
An aspect of the system that has not been mentioned so far is aggregation. Our system supports basic aggregations such as SUM, COUNT and AVERAGE. The execution engine makes use of hash aggregate to achieve it. This is implemented in java by using a HashMap. If the execution in single threaded, there are no locks. The downside of this is that the execution is slow. One of the approaches to improve performance is to have parallel executions. This is already discussed above.
When using threads to execute a query in parallel, the hash map that stores the aggregates has to be shared across numerous threads. This introduces a point of synchronization. If two threads modify the map simultaneously, the outcome can be wrong, inconsistent and unpredictable. In order to obtain the correct result, one thread has to lock the map when modifying any value, resulting in the second thread being blocked until the lock on the map is released. There are various data structures, such as concurrent maps, that have optimization to improve performance. Instead of locking the entire data structure, only the value that is accessed is locked. The optimization permits locking part of the data structure instead of the entire data structure. Consequently, two threads can simultaneously change values in the map as long as they access different keys. The
problem with such data structures is that, writes are blocking but reads are non-blocking. This gives rise to read-modified-write problems. This is the exact approach hash aggregates take. It reads a value, modifies it based on the value read and writes the new value back to the map. In between the read and the write operations, if another thread reads the old value, it results in a dirty read. Hence, we cannot use such optimized data structure and have to lock on the entire map.
**Locked Aggregation**
![Locked Aggregation Diagram]
**Lock Free Aggregation**
![Lock Free Aggregation Diagram]
Figure 15: Lock and Lock-free approach
We observe that the synchronization (lock) time is high, relative to the total time of execution. This time increases as the number of threads increase. In case of shared scans,
an obvious optimization is to shuffle the query order in different threads. This results in different threads executing different queries at the same time, which reduced the time a thread is blocked, waiting to acquire the lock. This helps performance to some extent, but the synchronization time is still considerably high.
Another approach, in case of shared scans, is to have individual maps per thread. This idea is derived of MVCC, Multi-version concurrency control. Each thread operates on its own aggregation map, one per query. With this approach there is no locking necessary. An additional step that is however required is to perform another aggregation, on the maps from different threads. The additional aggregation is not expensive and is observed to always be in the order of tens of milliseconds for each query in a cycle.

Figure 16: Lock and Lock-free block execution time
In Figure 16 we look at a more detailed experiment. It shows the pure aggregation time needed for lock and lock-free aggregations. Each point in the graph signifies the time needed to aggregate 20 blocks of data. Each block has 10000 rows and there are 20 threads running in parallel. The X-axis is the number of blocks and the Y-axis is the time in milliseconds. The experiment is run with 8 queries, all having SUM as measure, each issued 5 seconds after the previous query. In both lock and lock-free aggregation, we see that the general trend, in aggregation time for 20 blocks of data, is to first increase and then decrease. The initial increase is because of issuing of new queries. It is the highest in the middle. It then decreases as queries complete their execution. We observe that lock-free approach always takes less time to perform the aggregation compared to the locked approach. The high variability in the time taken with the locked approached is because of the locking overhead. Most threads are blocked while a single thread holds the lock. The variability in the lock-free approach is discussed later.
Figure 17 shows the total query execution time for both lock and lock-free aggregation. As expected the lock-free aggregation is faster compared to the locked approach. On closer inspection, we see that it is only 2.25 seconds faster. Given that the time needed for aggregation in the lock-free approach was considerably smaller, the difference in total execution time is marginal. The lock-free approach is losing time in another part of the execution.
Figure 17: Lock and Lock-free total execution time
Figure 18 shows a detailed breakdown of the execution. We observe the time needed for aggregation is smaller for lock-free compared to locked approach. The main reason why the two approaches report very similar total execution time is because of the difference in garbage collection (GC) time. The garbage collection time signifies the time the application is paused, in order to reclaim memory. We notice that the GC time for lock-free approach is nearly double that of locked approach.
This is largely attributed to the individual maps, refer Figure 15, all the different threads create. In the locked approach there is a single map, per query, that is shared among all the threads. In the lock-free approach each thread creates a new map for every query. At the end of the final aggregation step, all these maps are dereferenced, which means that the garbage collector will claim all these to create some free space. In order to deal with memory fragmentation, the garbage collector pauses the application, moves all the referenced objects to a side of the heap, reassigns the pointer and frees the remaining contiguous memory space.
5.8 Storage
Work mentioned in the above sections was run on data stored in row-oriented form. Row oriented storage is the traditional storage format. In the recent past column oriented storage have emerged to be more useful under certain usage. For example column oriented are the preferred format in analytics. Column oriented storage are preferred because by principled, less data has to be read from disk. During query execution only the required columns are read from disk, unlike row store where all the columns of a row are read from disk. This provides a huge performance improve with wide tables. Column stores also have added benefits when it comes to compression. Since values in a column tend to be similar, they provide better compression ratio compared to row stores.
It is evident that column oriented storage format will benefit online aggregation system. Each query will read only the required columns during execution. The idea of shared scans for column storage is not intuitive. There are problems such as different rate of scans for different columns, choosing which column to scan etc. It is still worth performing experiments to compare row storage, with the different approaches mentioned, and column storage.
We perform an experiment for comparing execution time for row and column storage format. For all the experiments we use machines having 4 GB memory, intel xeon quad core processors and 720 GB of disk space. The cluster has a 1 Gbps switch. Data comprises of 5 million rows and 6 columns, consisting of strings, integers and floating-point data types. The data used is identical in both the formats. We plot the time it takes to complete executing the queries for both the formats.
The X-axis shows the number of queries and the Y-axis shows time in milliseconds. The case of row format, both the independent and the shared scan for considered. As the graphs reveals row storage with independent scans shows the least performance. The increase in time can be attributed to increased data read from disk as the number of queries increase. In comparing, row oriented shared scans and column store scale well with the number of queries. When there is less number of queries, column store performances better than shared scan, since data read from disk for column format is significantly less. As the number of queries increase the shared scans and column format lines cross each other. With increase in queries, column format starts reading more data.
from disk, whereas shared scan read the same amount of data from disk. The lines cross over when the data read by column format is more than the data read by the shared scan.
Conclusion And Future Work
We introduced a system that allows for a dynamic user defined reprioritization of online aggregation queries. The need for an online aggregation system is increasing as the size of data to process is increasing. With this rise, the demand for interactive querying is also growing. We introduced a distributed execution engines that can consider user input, at runtime, and show instant change in query execution will be a valuable addition to the field of interactive querying. We make use of online aggregation and shared scans to implement an optimized priority aware system that can execute numerous queries in parallel to provide an interactive experience.
With the capabilities that the system has shown, there are several avenues of future work. Once such possibility is to integrate gestureGB [22] with this system. GestureDB proposes a new way of querying by making use of gestures that translate into queries. By integrating gestureGB with this system, the results can be visualized in an online manner. Gestures can be used to compute the priority of query. Since a gesture, for generating a query, involves a sequence of motions, priority will play an important role. When the user starts a gesture the priority of the probable query can be low. As the user moves through the sequence, the priority can increase, which results in faster execution of the query. This is also useful when moving from one gesture to the next. As the user transits
from the previous gesture to next one, the priority of the previous query can decrease and
the priority of the next probable query can increase. A lot of sudden and fast gestures can
lead to hysteresis, which our system is equipped to handle.
References
[22] Querying Without Keyboards, CIDR, 2013
|
{"Source-Url": "https://etd.ohiolink.edu/!etd.send_file?accession=osu1366475161&disposition=inline", "len_cl100k_base": 15659, "olmocr-version": "0.1.53", "pdf-total-pages": 75, "total-fallback-pages": 0, "total-input-tokens": 145887, "total-output-tokens": 19429, "length": "2e13", "weborganizer": {"__label__adult": 0.0003371238708496094, "__label__art_design": 0.0007123947143554688, "__label__crime_law": 0.00037169456481933594, "__label__education_jobs": 0.004119873046875, "__label__entertainment": 0.00020647048950195312, "__label__fashion_beauty": 0.0002149343490600586, "__label__finance_business": 0.0006055831909179688, "__label__food_dining": 0.0004529953002929687, "__label__games": 0.0008883476257324219, "__label__hardware": 0.0014677047729492188, "__label__health": 0.0005998611450195312, "__label__history": 0.0006103515625, "__label__home_hobbies": 0.00016605854034423828, "__label__industrial": 0.0006580352783203125, "__label__literature": 0.0004730224609375, "__label__politics": 0.00034308433532714844, "__label__religion": 0.0005183219909667969, "__label__science_tech": 0.271240234375, "__label__social_life": 0.00018262863159179688, "__label__software": 0.0244140625, "__label__software_dev": 0.68994140625, "__label__sports_fitness": 0.00026702880859375, "__label__transportation": 0.0006971359252929688, "__label__travel": 0.00027680397033691406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 80561, 0.02558]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 80561, 0.36968]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 80561, 0.92066]], "google_gemma-3-12b-it_contains_pii": [[0, 404, false], [404, 445, null], [445, 1495, null], [1495, 1534, null], [1534, 2867, null], [2867, 3540, null], [3540, 4462, null], [4462, 6929, null], [6929, 6929, null], [6929, 7038, null], [7038, 9030, null], [9030, 10553, null], [10553, 12019, null], [12019, 13513, null], [13513, 15114, null], [15114, 16535, null], [16535, 17807, null], [17807, 18511, null], [18511, 20056, null], [20056, 21676, null], [21676, 22922, null], [22922, 24257, null], [24257, 24923, null], [24923, 26274, null], [26274, 27607, null], [27607, 27984, null], [27984, 29617, null], [29617, 30896, null], [30896, 31757, null], [31757, 32607, null], [32607, 33140, null], [33140, 34684, null], [34684, 36345, null], [36345, 37641, null], [37641, 37900, null], [37900, 38165, null], [38165, 39623, null], [39623, 40875, null], [40875, 41916, null], [41916, 43598, null], [43598, 44905, null], [44905, 46368, null], [46368, 48004, null], [48004, 49526, null], [49526, 50661, null], [50661, 51372, null], [51372, 52855, null], [52855, 54159, null], [54159, 55410, null], [55410, 56047, null], [56047, 56371, null], [56371, 57494, null], [57494, 58226, null], [58226, 58863, null], [58863, 59870, null], [59870, 60962, null], [60962, 62369, null], [62369, 63500, null], [63500, 64211, null], [64211, 65602, null], [65602, 66911, null], [66911, 67388, null], [67388, 68995, null], [68995, 69815, null], [69815, 70760, null], [70760, 72338, null], [72338, 72878, null], [72878, 73527, null], [73527, 75244, null], [75244, 76011, null], [76011, 76186, null], [76186, 77670, null], [77670, 77913, null], [77913, 79210, null], [79210, 80561, null]], "google_gemma-3-12b-it_is_public_document": [[0, 404, true], [404, 445, null], [445, 1495, null], [1495, 1534, null], [1534, 2867, null], [2867, 3540, null], [3540, 4462, null], [4462, 6929, null], [6929, 6929, null], [6929, 7038, null], [7038, 9030, null], [9030, 10553, null], [10553, 12019, null], [12019, 13513, null], [13513, 15114, null], [15114, 16535, null], [16535, 17807, null], [17807, 18511, null], [18511, 20056, null], [20056, 21676, null], [21676, 22922, null], [22922, 24257, null], [24257, 24923, null], [24923, 26274, null], [26274, 27607, null], [27607, 27984, null], [27984, 29617, null], [29617, 30896, null], [30896, 31757, null], [31757, 32607, null], [32607, 33140, null], [33140, 34684, null], [34684, 36345, null], [36345, 37641, null], [37641, 37900, null], [37900, 38165, null], [38165, 39623, null], [39623, 40875, null], [40875, 41916, null], [41916, 43598, null], [43598, 44905, null], [44905, 46368, null], [46368, 48004, null], [48004, 49526, null], [49526, 50661, null], [50661, 51372, null], [51372, 52855, null], [52855, 54159, null], [54159, 55410, null], [55410, 56047, null], [56047, 56371, null], [56371, 57494, null], [57494, 58226, null], [58226, 58863, null], [58863, 59870, null], [59870, 60962, null], [60962, 62369, null], [62369, 63500, null], [63500, 64211, null], [64211, 65602, null], [65602, 66911, null], [66911, 67388, null], [67388, 68995, null], [68995, 69815, null], [69815, 70760, null], [70760, 72338, null], [72338, 72878, null], [72878, 73527, null], [73527, 75244, null], [75244, 76011, null], [76011, 76186, null], [76186, 77670, null], [77670, 77913, null], [77913, 79210, null], [79210, 80561, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 80561, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 80561, null]], "pdf_page_numbers": [[0, 404, 1], [404, 445, 2], [445, 1495, 3], [1495, 1534, 4], [1534, 2867, 5], [2867, 3540, 6], [3540, 4462, 7], [4462, 6929, 8], [6929, 6929, 9], [6929, 7038, 10], [7038, 9030, 11], [9030, 10553, 12], [10553, 12019, 13], [12019, 13513, 14], [13513, 15114, 15], [15114, 16535, 16], [16535, 17807, 17], [17807, 18511, 18], [18511, 20056, 19], [20056, 21676, 20], [21676, 22922, 21], [22922, 24257, 22], [24257, 24923, 23], [24923, 26274, 24], [26274, 27607, 25], [27607, 27984, 26], [27984, 29617, 27], [29617, 30896, 28], [30896, 31757, 29], [31757, 32607, 30], [32607, 33140, 31], [33140, 34684, 32], [34684, 36345, 33], [36345, 37641, 34], [37641, 37900, 35], [37900, 38165, 36], [38165, 39623, 37], [39623, 40875, 38], [40875, 41916, 39], [41916, 43598, 40], [43598, 44905, 41], [44905, 46368, 42], [46368, 48004, 43], [48004, 49526, 44], [49526, 50661, 45], [50661, 51372, 46], [51372, 52855, 47], [52855, 54159, 48], [54159, 55410, 49], [55410, 56047, 50], [56047, 56371, 51], [56371, 57494, 52], [57494, 58226, 53], [58226, 58863, 54], [58863, 59870, 55], [59870, 60962, 56], [60962, 62369, 57], [62369, 63500, 58], [63500, 64211, 59], [64211, 65602, 60], [65602, 66911, 61], [66911, 67388, 62], [67388, 68995, 63], [68995, 69815, 64], [69815, 70760, 65], [70760, 72338, 66], [72338, 72878, 67], [72878, 73527, 68], [73527, 75244, 69], [75244, 76011, 70], [76011, 76186, 71], [76186, 77670, 72], [77670, 77913, 73], [77913, 79210, 74], [79210, 80561, 75]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 80561, 0.03088]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
e1b3a09e29c888494c913f1fac4337e3cef715fc
|
[REMOVED]
|
{"Source-Url": "https://people.eecs.ku.edu/~hossein/Pub/Journal/2002-Saiedian-ASE.pdf", "len_cl100k_base": 13410, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 59716, "total-output-tokens": 17065, "length": "2e13", "weborganizer": {"__label__adult": 0.0003325939178466797, "__label__art_design": 0.0004916191101074219, "__label__crime_law": 0.0002472400665283203, "__label__education_jobs": 0.002529144287109375, "__label__entertainment": 0.00010317564010620116, "__label__fashion_beauty": 0.00016295909881591797, "__label__finance_business": 0.0012969970703125, "__label__food_dining": 0.0002601146697998047, "__label__games": 0.0005846023559570312, "__label__hardware": 0.0012378692626953125, "__label__health": 0.0003690719604492187, "__label__history": 0.0003173351287841797, "__label__home_hobbies": 0.00010246038436889648, "__label__industrial": 0.0005159378051757812, "__label__literature": 0.00025773048400878906, "__label__politics": 0.00026988983154296875, "__label__religion": 0.0004062652587890625, "__label__science_tech": 0.031341552734375, "__label__social_life": 8.618831634521484e-05, "__label__software": 0.010833740234375, "__label__software_dev": 0.947265625, "__label__sports_fitness": 0.00021755695343017575, "__label__transportation": 0.0005245208740234375, "__label__travel": 0.00021588802337646484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75729, 0.02826]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75729, 0.16821]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75729, 0.9208]], "google_gemma-3-12b-it_contains_pii": [[0, 2694, false], [2694, 5726, null], [5726, 8959, null], [8959, 11789, null], [11789, 14900, null], [14900, 17957, null], [17957, 20904, null], [20904, 23435, null], [23435, 26274, null], [26274, 29124, null], [29124, 32072, null], [32072, 34934, null], [34934, 39443, null], [39443, 42811, null], [42811, 45540, null], [45540, 46430, null], [46430, 48507, null], [48507, 50791, null], [50791, 53907, null], [53907, 56924, null], [56924, 60015, null], [60015, 62754, null], [62754, 65741, null], [65741, 68739, null], [68739, 72336, null], [72336, 75729, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2694, true], [2694, 5726, null], [5726, 8959, null], [8959, 11789, null], [11789, 14900, null], [14900, 17957, null], [17957, 20904, null], [20904, 23435, null], [23435, 26274, null], [26274, 29124, null], [29124, 32072, null], [32072, 34934, null], [34934, 39443, null], [39443, 42811, null], [42811, 45540, null], [45540, 46430, null], [46430, 48507, null], [48507, 50791, null], [50791, 53907, null], [53907, 56924, null], [56924, 60015, null], [60015, 62754, null], [62754, 65741, null], [65741, 68739, null], [68739, 72336, null], [72336, 75729, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75729, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75729, null]], "pdf_page_numbers": [[0, 2694, 1], [2694, 5726, 2], [5726, 8959, 3], [8959, 11789, 4], [11789, 14900, 5], [14900, 17957, 6], [17957, 20904, 7], [20904, 23435, 8], [23435, 26274, 9], [26274, 29124, 10], [29124, 32072, 11], [32072, 34934, 12], [34934, 39443, 13], [39443, 42811, 14], [42811, 45540, 15], [45540, 46430, 16], [46430, 48507, 17], [48507, 50791, 18], [50791, 53907, 19], [53907, 56924, 20], [56924, 60015, 21], [60015, 62754, 22], [62754, 65741, 23], [65741, 68739, 24], [68739, 72336, 25], [72336, 75729, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75729, 0.11798]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
a21bdc6bd35e4da33528d9dbf27b4f24b42a1e0e
|
Porting L4Ka::Pistachio to Mips32
Thomas Blattmann
Studienarbeit
Verantwortlicher Betreuer: Prof. Dr. Frank Bellosa
Betreuende Mitarbeiter: Dipl.-Inf. Uwe Dannowski
Hiermit erkläre ich, die vorliegende Arbeit selbständig verfaßt und keine anderen als die angegebenen Literaturhilfsmittel verwendet zu haben.
I hereby declare that this thesis is a work of my own, and that only cited sources have been used.
__________________________________
Thomas Blattmann
## Contents
1 Introduction 7
2 Background 7
2.1 The Mips32-4K Processor Core family 7
2.2 Register Set 8
2.3 Memory Management 9
2.3.1 Virtual Memory Segments 9
2.3.2 Translation Lookaside Buffer 10
2.3.3 Cache 10
2.3.4 Exception Handling 10
2.4 Simics Simulator 11
3 Major Design Decisions 12
3.1 Memory Management 12
3.1.1 Physical Memory Layout 12
3.1.2 Virtual Memory Layout 13
3.1.3 I/O-Ports 13
3.1.4 Address Spaces 13
3.1.5 Translation Lookaside Buffer 14
3.1.6 Mapping Database 14
3.2 Thread Control Blocks 14
3.3 Resource Management 15
3.4 Exception Handling 15
3.4.1 Interrupts 15
3.4.2 TLB-miss exception 16
3.4.3 Breakpoints 16
3.5 L4 API 17
3.5.1 Thread Control Registers 17
3.5.2 Exception Messages 17
3.5.3 System Calls 19
4 Implementation 19
4.1 Compiler and ABI 19
4.2 System Calls 19
4.2.1 Invocation in user mode 19
4.2.2 Handling in kernel mode 20
4.2.3 Return from Syscall 21
4.3 Context Switch and Notifications 21
4.4 Restrictions 22
5 Evaluation 23
6 Conclusion 23
6.1 Suggestions for future work 24
# A Systemcalls
A.1 KernelInterface .................................................. 27
A.2 Schedule .......................................................... 27
A.3 ExchangeRegisters ................................................. 28
A.4 SpaceControl ..................................................... 28
A.5 ThreadSwitch ....................................................... 29
A.6 Clock ............................................................... 29
A.7 Unmap ............................................................... 29
A.8 IPC ................................................................. 30
A.9 ThreadControl ..................................................... 30
1 Introduction
A microkernel is a type of kernel which provides a very simple abstraction over the hardware. Only a minimal set of security relevant services such as thread management, address spaces and interprocess communication are implemented. Other services that are commonly offered by monolithic kernels, including networking, device drivers and pages are implemented in user-space programs and are not part of the kernel itself. Microkernels aim at extracting as much policy out of the kernel as possible in order to make them suitable for different fields of applications and to keep them easily maintainable.
The L4Kα::Pistachio is the latest L4 Microkernel developed by the System Architecture Group at the University of Karlsruhe. The L4 kernel was originally designed and implemented by Jochen Liedtke (see [4] and [5]) and has become popular due to its outstanding IPC performance. Most architecture independent parts are written in C++ and ports for altogether eight architectures exist.
This work describes the major design decisions that were made when porting L4 to the Mips32 architecture. It also gives some illustrative code extractions. The last two chapters show the result of an IPC performance test and describe implementation alternatives.
The existing Mips64 port by Carl van Schaik served as a template for most design decisions. Some parts were simply adopted and adjusted accordingly. In general, it was tried to keep things as simple as possible while trying to get the most basic things run. Later optimizations (as e.g. described in Section 6) can still be done but were not part of this thesis.
The port made is for a Mips32-4Kc single processor system to which I'll therefore confine myself in the remainder of this document unless it is noted otherwise.
2 Background
This section gives a brief overview of the Mips32-4K architecture, including the Mips32-4Kc processor for which the port was made. Further Simics, a system level instruction set simulator on which all testing and development was done, is introduced.
2.1 The Mips32-4K Processor Core family
The Mips32-4K processor cores are high-performance, low-power, 32-bit RISC cores intended for custom system-on-chip applications. Although the cores implement a 32-bit architecture, many features (e.g. the MMU) are modeled after the ones that can be found in the 64-bit R4000 family. The 4K family has three members. The 4Kc contains a fully associative Translation Lookaside Buffer (TLB) based MMU and a pipelined multiply-divide unit (MDU). The TLB itself consists of three address translation buffers: a 16 dual-entry, fully associative Joint TLB (JTLB), a 3-entry instruction micro TLB (ITLB), and a
3-entry data micro TLB (DTLB). Both micro TLBs are hardware managed and inaccessible to the system programmer. The JTLB, however, is controlled and refilled solely by system software.
The 4Km and 4Kp processors use a fixed mapping mechanism instead of a TLB-based MMU, which performs a simple translation to get the physical from the virtual address. Unmapped segments are treated identically by all cores and are described in [2], Chapter 3. The simple translation takes part in the lower 2 GB of the virtual address space. For more details refer to [1], Chapter 3, "Memory Management". While the 4Km processor uses a pipelined MDU as in the 4Kc core, the 4Kp processor has a smaller non-pipelined MDU.
Optional data and instruction caches can be flexibly configured at processor built time for various sizes, organizations and set-associativities. A System Control Coprocessor (CP0) is responsible for virtual-to-physical address translation, cache protocols, the exception control system, operating mode selection, and the enabling/disabling of interrupts. It also provides configuration information such as cache size, TLB size and associativity. CP0 is part of each Mips CPU even though its name might suggest that it is not.
All cores execute the Mips32 instruction set architecture (ISA) containing all Mips II instructions as well as special multiply-accumulate, conditional move, prefetch, wait or zero/one detect instructions.
2.2 Register Set
The processor has 32 user accessible general-purpose registers. The hardware itself makes few rules, but conventions on the usage of the different registers exist. The register called zero is hard wired to zero. at is reserved for the assembler to translate pseudo instructions into actual instructions or sequences of instructions. It is commonly not used by the programmer. v0 and v1 are used to return values from functions. a0 to a3 contain the first four parameters that are passed to a function and pointers to them, respectively. t0 to t9 are for general purpose. They are not preserved through function calls. s0 to s8 are to be saved and restored by the callee so that the register content is the same as before when returning from a function call. fp is intended to be a frame pointer, gp a global pointer which the compiler can use to point into a static memory region for a faster (gp-relative) access. sp holds the current stack pointer and ra the return address from a function call. k0 and k1 are both reserved for the operating system. Their content can change any time to arbitrary values from a user application's point of view.
Coprocessor0 has 32 registers to be used by the operating system. That register set is only accessible in kernel mode.
General purpose registers are referred to as GP[name] hereafter. CP0[name/bits] denotes a Coprocessor0 register in which the optional 'bits' names a bitfield within a register.
2.3 Memory Management
2.3.1 Virtual Memory Segments
The 4 Gigabyte address space is divided into five areas as can be seen in Figure 1.
- **kuseg** The low 2 Gigabyte, denoted kuseg, are addresses permitted in user mode and kernel mode. The system maps all user mode references to kuseg through the TLB. Data and instructions in this segment can be cached once the cache is initialized. In kernel mode, the processor can be set up to map kuseg’s virtual addresses directly to the same physical addresses, or to use the TLB for translation.
- **kseg0** The 512MB of virtual memory in kseg0 are translated contiguously into the low 512MB of physical memory. This region is accessed through the cache. The main parts of the kernel are commonly loaded and executed in this segment.
- **kseg1** The next 512MB make up kseg1. They give a duplicate mapping of the first 512MB of physical memory. Accessing kseg1 will not involve the cache and is thus the only chunk of memory map that is guaranteed to behave properly from system reset. It is therefore used to access the initial program ROM.
- **kseg2/kseg3** Being in kernel mode, software has access to the entire address space including kseg2 and kseg3 with 512MB each. They are both translated through the TLB. The mapping of kseg3 changes if Debug mode is entered. In Debug mode, a special debug segment is mapped into kseg3.


**Figure 1: Virtual Memory Segments**
2.3.2 Translation Lookaside Buffer
The 4Kc core implements a 16 dual-entry, fully associative Joint TLB that maps 32 virtual pages. It is organized as pairs of even and odd entries to minimize the overall size. Each pair is tagged by an 8-bit Address Space Identifier (ASID) and translates two consecutive pages that can range from 4KB to 16MB. The ASID is compared to CP0[entryhi/asid] each time a translation proceeds. Entries whose ASID tag does not match CP0[entryhi/asid] are ignored. A global bit can be set for each double entry. If set, the ASID field is ignored on lookups and the pages are global to all address spaces.
Apart from a CP0 register that holds the current ASID, the TLB makes up the whole MMU hardware. The Operating System uses the TLB as a cache to a memory-resident page table. Thus, no particular format of page table is needed. When presented with an address it can’t translate, the TLB triggers a special exception to invoke a software routine. It is then up to system software to put the faulting address into the TLB or to handle the exception appropriately.
2.3.3 Cache
A 4Kc processor supports separate instruction and data caches, which allows instruction and data references to proceed simultaneously. Both caches are virtually indexed and physically tagged. This way, cache access and virtual-to-physical address translation can be done in parallel. As the physical address is used to tag each cache line, flushing the cache on a context switch should not be necessary in most cases. Each cache line is completed with valid bits for each data word cached as well as a locked bit to prevent cached data from getting replaced.
The write-through strategy eases things with respect to cache programming. Once the cache is initialized only little management effort should be necessary. The programmer has to be aware of possible timing delays for I/O register access caused by a write buffer. Further, the system software has to handle cache coherency issues within the memory hierarchy that can affect an additional memory master (e.g., a DMA controller). The OS’s memory management must also avoid cache aliases that can arise when the same physical address may be described by different virtual addresses of different threads.
2.3.4 Exception Handling
The processors receive exceptions from a number of sources, including TLB misses, arithmetic overflows, I/O interrupts, and system calls. Whenever the CPU detects an exception, the normal sequence of instructions is suspended and the processor enters kernel mode, disables interrupts and jumps to a software exception handler. Table 1 shows the most common exceptions along with their corresponding vectors. For a detailed description refer to [2 and 3].
On an exception, CP0[epc] contains the instruction pointer (IP) that points to the instruction where execution should be resumed after the exception. CP0[cause] is set up so that software can see the reason for the exception. On a TLB-miss
### Table 1: Exception Vectors
<table>
<thead>
<tr>
<th>Exception</th>
<th>Vector</th>
</tr>
</thead>
<tbody>
<tr>
<td>Reset, Soft Reset, NMI</td>
<td>0xbfc00000</td>
</tr>
<tr>
<td>TLB miss exception</td>
<td>0x80000000</td>
</tr>
<tr>
<td>TLB invalid exception</td>
<td>0x800000180</td>
</tr>
<tr>
<td>Interrupts</td>
<td>0x800000180</td>
</tr>
<tr>
<td>Breakpoints</td>
<td>0x800000180</td>
</tr>
<tr>
<td>All other exceptions</td>
<td>0x800000180</td>
</tr>
</tbody>
</table>
exception CP0[badvaddr] contains the faulting address. Other than that no registers are saved by hardware.
Mips exceptions are precise, meaning that all instructions preceding the exception victim in instruction sequence are completed; any work done on the victim and on any subsequent instructions (due to the pipeline) has no side effects the software needs to worry about.
### 2.4 Simics Simulator
Simics is a system level instruction set simulator supporting various target systems. It models the Mips32-4Kc processor with a limited set of devices from the Mips Malta development board. All development and testing has been done on version 2.2.19. Earlier versions contain bugs (e.g. movez instruction) and prevent the kernel from executing properly.
Unfortunately, there are a few limitations and features not yet supported by Simics/Mips. I state the ones with an immediate impact on what was implemented (confer to Section 4.4, Restrictions). Other limitations can be found in [6].
- There are a few instructions that have not yet been implemented. Other instructions are simply 'nops' and doing nothing. One of them is the 'cache' instruction, which is used for cache management. Another one is 'wait', used to enter standby mode.
- As no cache model has been connected to Simics/Mips, reads and writes to the corresponding control registers in CP0 have no effect at all.
- The simulator supports little-endian mode only.
- Simics/Mips doesn’t consider instruction hazards caused by the pipeline. A real Mips processor would need nops following some instructions to
Table 2: Memory mapped I/O-devices
<table>
<thead>
<tr>
<th>Address</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>0x00000000</td>
<td>128MB of RAM are mapped at address zero</td>
</tr>
<tr>
<td>0x18000070</td>
<td>Dallas Semiconductor DS12887 real-time clock (CMOS clock)</td>
</tr>
<tr>
<td>0x18000038</td>
<td>National Semiconductor PC16550 serial port controller (UART)</td>
</tr>
<tr>
<td>0x1f000000</td>
<td>Malta board specific LCD display</td>
</tr>
<tr>
<td>0x18000000</td>
<td>Intel 8259 interrupt controller</td>
</tr>
</tbody>
</table>
keep the pipeline happy. As a consequence, execution on Simics works but might fail on real Mips hardware
- No boot loader is available. Instead the kernel is loaded directly into Simics and no boot information is provided.
- It does not implement a floating-point unit.
As is common on the Mips architecture, all IO devices are memory mapped. Table 2 shows where in physical memory what devices are mapped in the Simics configuration that was used.
3 Major Design Decisions
This section describes the major design decisions made when porting L4 to the Mips32 architecture. It first gives details on memory management, continues with Thread Control Blocks, Resource Management and the exception handling mechanism and is closed with a description of the L4 API. The Mips64 port served as a template for many design decisions. Hence some design was simply adopted and adjusted accordingly.
3.1 Memory Management
3.1.1 Physical Memory Layout
The kernel ELF binary spans around 190KB and is loaded into memory starting at physical address 0x400. The area below contains entry points for exception handlers. The following 16MB are reserved for use by the kernel memory allocator. All remaining physical memory is registered in the KIP and made user accessible.
3.1.2 Virtual Memory Layout
The area from 0x00000000 to 0x80000000 (lower 2GB) is available for user applications. The whole kernel is linked into kseg1. kseg0 remains unused as result of the lacking cache simulation. The lower 8MB of kseg2 are reserved to establish a temporary mapping in an address space (communication window) on a Long IPC (cf. to [4]). The remainder of kseg2 and kseg3 contain the virtual array of Thread Control Blocks (see Section 3.2).
3.1.3 I/O-Ports
The physical memory area containing I/O-devices can be shared among various address spaces. It is put into the KIP with memory descriptors set to ’shared’.
3.1.4 Address Spaces
Each address space contains a page directory and an Address Space Identifier (ASID). The page table is organized hierarchically. One page directory per address space and up to 1024 pages can map up to 4GB virtual address space. For user address spaces the page tables need to be able to map the first 2GB and a communication window while kseg0/1 and most parts of kseg2/3 remain unused. Hence, parts of the page table that are not needed are used to store some address space management related data. The kernel address space on the other hand only has to map the TCB area. The lower half is unused.
There are no restrictions on how the page tables are organized in memory as the TLB is software loaded on a miss. Nevertheless, data in the page tables are stored so that they can be written into the TLB without further conversions. Page tables are allocated on demand. Each entry has 32bits. The provided Linear Page Table Walker was used for virtual-to-physical address translation as well as FlexPage mapping and unmapping. It was set up accordingly.
The processor uses an Address Space Identifier to keep TLB entries from different address spaces apart. Because the architecture supports only 512 ASIDs, an ASID engine that had already been used in some other L4 ports was taken. Whenever a thread in a certain address space is scheduled, it is checked whether a valid ASID is already assigned. If it’s not, an allocated ASID is preempted from another address space according to an LRU algorithm and assigned to the scheduled thread’s one after cleaning up the TLB.
3.1.5 Translation Lookaside Buffer
The Translation Lookaside Buffer (TLB) uses a simple LIFO replacement strategy as offered by the hardware. User translations are tagged with an Address Space Identifier. Consequently they do not need to be flushed on a context switch. Apart from the TCB area, the kernel’s code and data are located in memory segments that do not involve the TLB. TCB area translations are marked global when put into the TLB, implying that TCBs can be accessed in kernel mode independently of CP0[entryhi/asiid].
The cacheability flags are set for each TLB entry to indicate whether the data is cacheable or not. Writable and valid bits are used as provided by the hardware. There is no hardware dirty bit to indicate whether a translation was accessed or not, however.
One TLB dual entry is hard wired and set up to provide the translation of the currently running thread’s TCB. The reason for this is described in section 3.4.2.
3.1.6 Mapping Database
A mapping database is the kernel’s view of all address spaces, i.e. recursively mapped or granted FlexPages. Each mapping entry in the page table is supplied with an additional link to its mapping database entry and vice versa.
The Mapnode links for page table entries are located in an array appended to each user page table. In order to obtain the link, an offset of 4KB needs to be added to the address of the corresponding page table entry.
3.2 Thread Control Blocks
Two segments, kseg2 and kseg3 contain a virtual array of Thread Control Blocks (TCBs) with 4096 Bytes each. The size of this area limits the total number of active threads in the system to 254K. TCBs are mapped only in the kernel’s address space. No virtual area is shared among different address spaces, making any kind of synchronization superfluous.
A Thread Control Block contains some thread related data (like local/global id, state, pointer to UTCB) as well as a stack (see [4]) and is only accessible in kernel mode. The stack is used by threads running in kernel mode, i.e. whenever a thread switches from user to kernel mode its stack pointer is set to point to the kernel stack within its TCB. The user context is always stored at the very
3.3 Resource Management
The communication area for the temporary mapping during Long IPC is currently the single resource in use as no Floating Point Unit was available. The lower 8MB of the kseng2 segment are reserved to establish that mapping. There is one reserved area per address space. An existing mapping is saved on each Thread Switch and restored when switching back to the thread.
3.4 Exception Handling
Exceptions include interrupts, system calls, TLB misses, breakpoints, invalid operations or privileged operations performed in user mode. On an exception, the processor switches to kernel mode and continues execution at predefined locations within the exception vector area. Interrupts are turned off and the faulting thread’s context is stored on the kernel stack in its TCB. A global, kernel accessible variable always holds a pointer to the currently running thread’s kernel stack. Interrupts remain turned off in kernel mode and are not re-enabled until it is switched back to user mode or to the idle thread.
The kernel initializes exception vectors at system startup, i.e., exception code is copied to the proper addresses in physical memory. Since there are only 128 bytes available between different vectors, the copied code does nothing but jump to the actual exception handler routines.
Several exceptions share the same exception handler located at physical address 0x00000180. To be able to keep them apart, the exception code field in CP0[Cause] is set by hardware. This value is used as an index into a pointer array with pointers to the respective exception handler.
3.4.1 Interrupts
The architecture distinguishes eight different interrupts sources: Two software and six hardware interrupts. The timer interrupt is used by the kernel and cannot be forwarded to user applications. Software interrupts remain unused. The other five hardware interrupts are only acknowledged by the kernel but not used for internal purposes. User threads can register themselves to get notification whenever one of those interrupts occurs.
On interrupts, the whole user context is stored. The kernel uses a pointer
array, indexed by the interrupt number, to jump to the appropriate interrupt handler. This array is initially set up to let handle\_interrupt(), which delivers interrupt IPCs, be the default interrupt handler.
The interrupt exception handler checks the bits in CP0[cause] to find out the interrupt source. It starts with the highest bit that is occupied by the timer and continues with the next lower etc. This order defines the priority of each interrupt in cases in which multiple interrupts occur at the same time.
### 3.4.2 TLB-miss exception
A TLB-miss exception is initiated in user and kernel mode when a TLB-mapped virtual address is referenced and the translation is not available in the TLB. A higher-level C routine is responsible for looking up the faulting address and updates the TLB if a translation is found in the pagetable. Prior to invoking it, the interrupted thread’s context is stored on the thread’s kernel stack. A page fault (no matching translation found in page table) causes the routine to call the main L4 pagefault handler (space\_L::handle\_pagefault). On return, the missing mapping is looked up again in the page table and the translation is put in the TLB if available. The thread’s context is restored and execution continues with the faulting instruction.
A TLB-miss on the currently running thread’s TCB would result in a never-ending TLB-miss recursion. It arises when the kernel tries to store the faulting thread’s context on the kernel stack in the TCB. This access causes another TLB-miss before the first one could be handled successfully and so on. Therefore, the TCB translation for the current thread is hard-wired in the TLB and updated on a thread switch.
### 3.4.3 Breakpoints
The ‘break’ instruction is another way to enter the kernel and to continue execution at a predefined location, respectively. It is mainly used to enter the kernel debugger when one of the breakin functions (for debugging purposes) is invoked. It can also be used by user applications to perform ‘putc’ and ‘getc’ I/O functions.
3.5 L4 API
3.5.1 Thread Control Registers
Thread Control Registers (TCRs) are part of the User Thread Control Blocks (UTCB). The address of the current thread’s UTCB is the same as the thread’s local ID, and is thus immutable. The UTCB (and hence local ID) is made available in the GP[k0] register by the kernel. GP[k0] should be treated as read-only. If modified, the effects are undefined.
All **buffer registers** map to memory locations in the UTCB. BR[0] is at byte offset 320, BR[1] at byte offset 324, etc.
3.5.2 Exception Messages
The kernel handles some exceptions. A default exception handler exists for all other exceptions. If there is a user exception handler registered with the faulting thread, it generates and sends an exception message as shown in Figure 3. In reply, the handler thread can set the faulting thread’s IP, SP and user flags. If there is no handler thread registered, the kernel debugger, which is part of current L4 implementations, is entered.
The following is a table of values for the `ExceptionNo`:
<table>
<thead>
<tr>
<th>Exception</th>
<th>ExceptionNo</th>
<th>ErrorCode</th>
<th>Delivered</th>
</tr>
</thead>
<tbody>
<tr>
<td>Interrupt</td>
<td>0</td>
<td>-</td>
<td>No</td>
</tr>
<tr>
<td>TLB Write Denied</td>
<td>1</td>
<td>-</td>
<td>No</td>
</tr>
<tr>
<td>TLB Miss Load</td>
<td>2</td>
<td>-</td>
<td>No</td>
</tr>
<tr>
<td>TLB Miss Store</td>
<td>3</td>
<td>-</td>
<td>No</td>
</tr>
<tr>
<td>Address Error (load/execute)</td>
<td>4</td>
<td>BadVAddress</td>
<td>Yes</td>
</tr>
<tr>
<td>Address Error (store)</td>
<td>5</td>
<td>BadVAddress</td>
<td>Yes</td>
</tr>
<tr>
<td>Bus Error (instruction)</td>
<td>6</td>
<td>-</td>
<td>Yes</td>
</tr>
<tr>
<td>Bus Error (data)</td>
<td>7</td>
<td>-</td>
<td>Yes</td>
</tr>
<tr>
<td>System Call</td>
<td>8</td>
<td>-</td>
<td>v0 ≥ 0</td>
</tr>
<tr>
<td>Break Point</td>
<td>9</td>
<td>-</td>
<td>!(-104 ≥ AT ≥ -100)</td>
</tr>
<tr>
<td>Reserved Instruction</td>
<td>10</td>
<td>Instruction</td>
<td>AT ≠ 0x141fcall</td>
</tr>
<tr>
<td>Coprocessor Unavailable</td>
<td>11</td>
<td>Number</td>
<td>CP0, CP2, CP3</td>
</tr>
<tr>
<td>Arithmetic Overflow</td>
<td>12</td>
<td>-</td>
<td>Yes</td>
</tr>
<tr>
<td>Trap</td>
<td>13</td>
<td>-</td>
<td>Yes</td>
</tr>
<tr>
<td>Watch Point</td>
<td>23</td>
<td>-</td>
<td>Unless used by kdb</td>
</tr>
<tr>
<td>Machine Check</td>
<td>24</td>
<td>-</td>
<td>Yes</td>
</tr>
</tbody>
</table>
Note, not all of these exceptions will be delivered via exception IPC. Some will be handled by the kernel. Delivered exceptions are indicated in the last column of the table above.
3.5.3 System Calls
The system call entry code is located in the Kernel Interface Page area. Pointers within the KIP contain their absolute addresses. In general, it is tried to follow the o32 calling conventions whenever possible, i.e. parameters are passed in general-purpose registers (GP[a0]-GP[a4]) and results are returned in GP[v0]. This works out for system calls with less than five parameters and a single return value. Other system calls pass additional parameters in GP[s0] to GP[s3] in order not to rely on a valid user stack pointer. Additional return values are returned in GP registers as well. The kernel expects GP[v0] to contain a constant indicating which system call is to be performed.
Generally, registers accessible by user applications are not preserved across system calls but contain return values or are undefined. Appendix A shows for each implemented system call the register content before and after the 'syscall' invocation.
4 Implementation
This sections shows how syscalls and thread switches are done. Both transactions are explained along with code extractions. Finally, restrictions of the current implementation are stated.
4.1 Compiler and ABI
The port was made on an x86 machine using a mipsel-unlknown-linux-gnu gcc cross compiler version 3.4.2 with traditional Mips o32 calling conventions. A description of the o32 standard can be found in [1], Chapter 10, "C Programming on Mips".
4.2 System Calls
4.2.1 Invocation in user mode
A user application is provided a library that contains the actual kernel entry code. Prior to executing the syscall instruction, parameters and the syscall identifier constant are put into predefined GP registers. The kernel expects a valid syscall identifier in GP[v0] and parameters in GP[a0]-GP[a4] as well as GP[s0]-GP[s3] when needed. The following code illustrates what is done in
user mode to perform a L4_ThreadControl system call. It is assumed that all parameters have already been loaded into GP registers.
```asm
__asm__ __volatile__ (
"lw $2, _L4_ThreadControl
/n\" /* entry point in KIP (absolute) */
"subu $29, $29, 0x10
/n\t" /* space on the stack as by o32 */
"jalr $2
/n\t" /* jump */
"addu $29, $29, 0x10
/n\t" /* clean up stack */
"move %0, $2
/n\t" /* result */
: "r"(r_result)
: "r"(r_dest), "r"(r_space), "r"(r_schedule), "r"(r_pager), "r"(r_utcb)
);
```
The code located in the KIP area sets GP[v0] and performs the 'syscall' instruction:
```c
BEGIN_PROC(user_thread_control);
li v0, SYSCALL_thread_control; # syscall identifier
syscall;
ra;
END_PROC(user_thread_control);
```
The 'L4_KernelInterface' system call is an exception to the general proceeding since the KIP and the 'syscall' instruction are not used. Instead, an illegal instruction is executed to enter kernel mode after a magic value was placed in GP[at]. On an illegal instruction, the kernel compares GP[at] with that magic constant and executes the L4_KernelInterface system call if they match.
### 4.2.2 Handling in kernel mode
A 'syscall' instruction in user mode causes the processor to switch to kernel mode and to continue execution at a predefined location. Apart from some essential registers (e.g. Instruction Pointer, Stack Pointer) no user context is saved. The syscall handler puts all arguments that were passed in GP[s0]-GP[s3] on the stack as by the o32 calling conventions and jumps to higher level C routines.
```c
[...]
# save some user context on kernel stack
[...]
```
4.2.3 Return from Syscall
The kernel puts all returned values in GP registers, restores some user context and finally executes the `eret` instruction in order to continue execution in user mode.
4.3 Context Switch and Notifications
On a Thread Switch, the running thread stores its global pointer, frame pointer and return address on its kernel stack. The stack pointer is stored at a fixed location within the 'old' thread's TCB. The actual switch takes place in two steps after the hard-wired TLB entry was updated. First, the new ASID is put into CP0[entryhi]. Subsequently, the stack pointer is set to its new value. The new thread simply restores its switch context and returns.
The following code extraction illustrates this procedure. Before it is executed, an ASID for the target address spaces is determined and stored in the local variable 'new_asid'.
```
__asm__ __volatile__ (
/* execution of the old thread */
"addiu $29,$29,-20 \n\t" /* allocate switch frame */
"la $31,0f \n\t"
"sw $16,0($29) \n\t" /* save registers */
"sw $17,4($29) \n\t"
"sw $30,8($29) \n\t"
"sw $28,12($29) \n\t"
"sw $31,16($29) \n\t"
/* hard wire TCB translation */
```
As explained in section 3.4.2, the hard-wired TLB entry is updated on each thread switch. That code part was omitted in the extraction above. It is quite straightforward though: First it is checked, whether a valid translation is already available in the TLB. If not, the target TCB is simply touched to cause a TLB miss. Finally, the old hard-wired entry and the entry to be hard-wired are swapped in order to place the new one into the hard-wired area.
Notify functions enable the kernel to force a thread to execute specific kernel functions when scheduled before it continues execution normally. All such a function has to do now is to put a 20 byte switch stack on top of the interrupted threads kernel stack that contains the function to call, up to two arguments and the return address.
4.4 Restrictions
Even though the implementation runs flawlessly on Simics, there are limitations. The kernel in the current state won’t run on real hardware. The main reason is the cache management, which has been ignored. Another one are CP0 hazards that might arise even though nops were added according to [3]. It has never been tested on real hardware though. The missing boot loader (and thus memory
<table>
<thead>
<tr>
<th>untyped words sent</th>
<th>instructions counted</th>
<th>difference</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>918</td>
<td>-</td>
</tr>
<tr>
<td>1</td>
<td>992</td>
<td>+ 74</td>
</tr>
<tr>
<td>2</td>
<td>1014</td>
<td>+ 22</td>
</tr>
<tr>
<td>3</td>
<td>1036</td>
<td>+ 22</td>
</tr>
<tr>
<td>4</td>
<td>1058</td>
<td>+ 22</td>
</tr>
<tr>
<td>5</td>
<td>1080</td>
<td>+ 22</td>
</tr>
<tr>
<td>62</td>
<td>2552</td>
<td>-</td>
</tr>
<tr>
<td>63</td>
<td>2574</td>
<td>+ 22</td>
</tr>
</tbody>
</table>
Table 3: Short IPC (Inter-AS)
descriptors) made it necessary to hard code the entry point address of Sigma0, Sigma1 and the Roottask. As stated above Simics/Mips does not implement the 'wait' instruction that could have been used in the idletask to enter standby mode while waiting for interrupts. Instead, a global variable is set to indicate a timer interrupt. The idletask stays in a loop actively waiting for the variable to become one.
Two syscalls are unimplemented, that is ProcessorControl and MemoryControl. Finally, interrupts are not enabled during a Long IPC, delaying the context switch and potentially allowing the communicating threads an excessive time slice.
5 Evaluation
The Mips32 port described in this work targets the simulated Malta board with a Mips-4Kc processor. Since no real hardware was available, the performance is evaluated in Simics instructions. Table 3 shows the number of instructions that were counted for a Short Inter-AS IPC with different numbers of untyped words and no types words.
6 Conclusion
The L4 microkernel port that is described in this document was done in the context of my study thesis "Porting L4K: Pistachio to Mips32". It’s primary goal was to get a working port for the Mips32 core and little attention was given to optimizations.
The port was tested and developed on the Simics instruction set simulator (cf. Section 2.4). Test cases comprise an L4 test suite as well as some available user applications (including PingPong and GrabMem). Nevertheless there remain parts of the implementation that were not covered by any test cases. There is no guarantee that those parts and also the tested parts are free of errors.
Having basic knowledge of the L4 internals, a port to a new architecture can be done quite straightforwardly as a result of existing C++ template classes and methods. These templates compose a documented framework of the as yet unimplemented architecture dependent parts of the kernel that are called from somewhere within the architecture independent parts. Only those classes and methods are to be implemented while architecture independent parts can be thought of as a black box that you do not need to worry about. The templates do not impose any restrictions on design and implementation and give the programmer the freedom to create whatever is best suited to the underlying architecture.
The Mips32 port uses those templates and made no changes to architecture independent code necessary. Many design decisions as well as some source code could be easily adopted from the port of the related Mips64 architecture.
Apart from restrictions as stated in Section 4.4, L4/Mips32 works flawlessly when executed on Simics and passes all test cases.
### 6.1 Suggestions for future work
TLB miss handling could be implemented faster. As is, the whole user context is stored and the translation is looked up and inserted into the TLB in a higher level C routine. If a pointer to the page directory was stored at a fixed address or within an unused CP0 register (e.g. CP0[context/PTEbase]), the faulting address could be looked up and inserted into the TLB within a few cycles. A second, more powerful handler would only be invoked if no translation is found in the page table (pagefault).
What the Mips architects had in mind was a contiguous non-hierarchical virtual 2MB page table in kseg2 for each user address space. This, on the one hand, saves physical memory since the unused gap in the middle of the page table will never be referenced. On the other hand it provides an easy mechanism for remapping a new user page table when changing context. By simply changing the CP0[entryhi/asiid] value on a context switch, the pointer to the page table is automatically remapped onto the correct page table. A TLB-miss recursion, caused by TLB-misses within the kseg2 area, can be avoided by having a slower, more general handler routine that gets invoked on nested
exceptions. The Mips hardware supports such a kind of linear page table in form of the CP0[context] register. If the virtual page table starts at a 1MB boundary and CP0[entryhi/PTEbase] is set up with the high-order bits of the pagetables base, the Context register will automatically point to the address of the required translation on each user refill exception.
One would need to reserve 2MB in kseg2 for the virtual page table. The global bit for that area would not be set in order to have the page tables per address space. An additional 512 byte per address space within an unmapped section (e.g. kseg0) could be used as page table to translate that 2MB area.
A never-ending TLB-miss recursion as described in section 3.4.2 is avoided by using hard-wired entries. You could also provide an additional static kernel stack to handle nested miss exceptions. The static stack would be global to all threads and used on TLB-miss exceptions that arise when touching a thread’s kernel stack.
By using a fast TLB-miss handler (that does not save any context) as described above, one could even omit the hard wired TLB entry if it is guaranteed that the TCB is mapped in the page table on a miss.
References
A Systemcalls
A.1 Kernel Interface
| GP[at] | 0x141FCA11 | [id] |
| GP[v0,v1]| [ign] | [id] |
| GP[a0..a3]| [ign] | [id] |
| GP[t0] | [ign] | KIP base address |
| GP[t1] | [ign] | API Version |
| GP[t2] | [ign] | API Flags |
| GP[t3] | [ign] | opcode 0xF1000000 |
| GP[t4..t7]| [ign] | Kernel ID |
| GP[s0..s7]| [ign] | [id] |
| GP[t8,t9]| [ign] | [id] |
| GP[sp,sp]| [ign] | [id] |
| GP[r8] | [ign] | [id] |
| GP[ra] | [ign] | [id] |
A.2 Schedule
| GP[at] | [ign] | [inv] |
| GP[v0] | [ign] | result |
| GP[v1] | [ign] | [inv] |
| GP[a0] | dest | time control |
| GP[a1] | time control| [inv] |
| GP[a2] | processor control | [inv] |
| GP[a3] | priority | [inv] |
| GP[t0..t9]| [ign] | Schedule |
| GP[s0] | preemted control | [inv] |
| GP[s1..s7]| [ign] | → id |
| GP[sp] | [ign] | [id] |
| GP[r8] | [ign] | [id] |
| GP[ra] | [ign] | [id] |
### A.3 ExchangeRegisters
<table>
<thead>
<tr>
<th>GP[index]</th>
<th>Function</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>GP[at]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[v0]</td>
<td>[ign]</td>
<td>result</td>
</tr>
<tr>
<td>GP[v1]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a0]</td>
<td>dest</td>
<td>control</td>
</tr>
<tr>
<td>GP[a1]</td>
<td>control</td>
<td>SP</td>
</tr>
<tr>
<td>GP[a2]</td>
<td>SP</td>
<td>IP</td>
</tr>
<tr>
<td>GP[a3]</td>
<td>IP</td>
<td>flags</td>
</tr>
<tr>
<td>GP[t0]</td>
<td>[ign]</td>
<td>pager</td>
</tr>
<tr>
<td>GP[t1]</td>
<td>[ign]</td>
<td>userhandle</td>
</tr>
<tr>
<td>GP[t2..t9]</td>
<td>[ign]</td>
<td>ExchangeRegisters [inv]</td>
</tr>
<tr>
<td>GP[s0]</td>
<td>flags</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s1]</td>
<td>userhandle</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s2]</td>
<td>pager</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s3]</td>
<td>local</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s4..s7]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[gp]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[sp]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s8]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[ra]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
</tbody>
</table>
### A.4 SpaceControl
<table>
<thead>
<tr>
<th>GP[index]</th>
<th>Function</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>GP[at]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[v0]</td>
<td>[ign]</td>
<td>result</td>
</tr>
<tr>
<td>GP[v1]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a0]</td>
<td>space</td>
<td>control</td>
</tr>
<tr>
<td>GP[a1]</td>
<td>control</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a2]</td>
<td>kip</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a3]</td>
<td>utcb area</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[t0..t9]</td>
<td>[ign]</td>
<td>SpaceControl [inv]</td>
</tr>
<tr>
<td>GP[s0]</td>
<td>redirector</td>
<td>→ [id]</td>
</tr>
<tr>
<td>GP[s1..s7]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[gp]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[sp]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s8]</td>
<td>[ign]</td>
<td>[id]</td>
</tr>
<tr>
<td>GP[ra]</td>
<td>[ign]</td>
<td>[inv]</td>
</tr>
</tbody>
</table>
28
### A.5 ThreadSwitch
| GP[at] | [ign] | [inv] |
| GP[v0, v1] | [ign] | [inv] |
| GP[a0] | dest | [inv] |
| GP[a1..a3] | [ign] | [inv] |
| GP[t0..t9] | [ign] | ThreadSwitch | [inv] |
| GP[s0..s7] | [ign] | [id] |
| GP[gp] | [ign] | [inv] |
| GP[sp] | [ign] | [id] |
| GP[s8] | [ign] | [id] |
| GP[ra] | [ign] | [inv] |
### A.6 Clock
| GP[at] | [ign] | [inv] |
| GP[v0] | [ign] | ticks (low 32 bits) |
| GP[v1] | [ign] | ticks (high 32 bits) |
| GP[a0..a3] | [ign] | [inv] |
| GP[t0..t9] | [ign] | Clock | [inv] |
| GP[s0..s7] | [ign] | [id] |
| GP[gp] | [ign] | [inv] |
| GP[sp] | [ign] | [id] |
| GP[s8] | [ign] | [id] |
| GP[ra] | [ign] | [inv] |
### A.7 Unmap
| GP[at] | [ign] | [inv] |
| GP[v0,v1] | [ign] | [inv] |
| GP[a0] | control | [inv] |
| GP[a1..a3] | [ign] | [inv] |
| GP[t0..t9] | [ign] | Unmap | [inv] |
| GP[s0..s7] | [ign] | [id] |
| GP[gp] | [ign] | [inv] |
| GP[sp] | [ign] | [id] |
| GP[s8] | [ign] | [id] |
| GP[ra] | [ign] | [inv] |
### A.8 IPC
<table>
<thead>
<tr>
<th>Address</th>
<th>GP</th>
<th>Ign</th>
<th>Inv</th>
</tr>
</thead>
<tbody>
<tr>
<td>GP[a0]</td>
<td>[ign]</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[v0]</td>
<td>[ign]</td>
<td></td>
<td>result</td>
</tr>
<tr>
<td>GP[v1]</td>
<td>[ign]</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a1]</td>
<td>to</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a2]</td>
<td>from</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a3]</td>
<td>time</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[t0..t9]</td>
<td>[ign]</td>
<td>IPC</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[s0]</td>
<td>mr0</td>
<td>→</td>
<td>mr0</td>
</tr>
<tr>
<td>GP[s1]</td>
<td>mr1</td>
<td></td>
<td>mr1</td>
</tr>
<tr>
<td>GP[s2]</td>
<td>mr2</td>
<td></td>
<td>mr2</td>
</tr>
<tr>
<td>GP[s3]</td>
<td>mr3</td>
<td></td>
<td>mr3</td>
</tr>
<tr>
<td>GP[s4]</td>
<td>mr4</td>
<td></td>
<td>mr4</td>
</tr>
<tr>
<td>GP[s5]</td>
<td>mr5</td>
<td></td>
<td>mr5</td>
</tr>
<tr>
<td>GP[s6]</td>
<td>mr6</td>
<td></td>
<td>mr6</td>
</tr>
<tr>
<td>GP[s7]</td>
<td>mr7</td>
<td></td>
<td>mr7</td>
</tr>
<tr>
<td>GP[gp]</td>
<td>[ign]</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[sp]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s8]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[ra]</td>
<td>[ign]</td>
<td></td>
<td>[inv]</td>
</tr>
</tbody>
</table>
### A.9 ThreadControl
<table>
<thead>
<tr>
<th>Address</th>
<th>GP</th>
<th>Ign</th>
<th>Inv</th>
</tr>
</thead>
<tbody>
<tr>
<td>GP[a0]</td>
<td>dest</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a1]</td>
<td>space</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a2]</td>
<td>schedule</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[a3]</td>
<td>pager</td>
<td></td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[t0..t9]</td>
<td>[ign]</td>
<td>ThreadControl</td>
<td>[inv]</td>
</tr>
<tr>
<td>GP[s0]</td>
<td>utcbb</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s1..s7]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[gp]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[sp]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[s8]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
<tr>
<td>GP[ra]</td>
<td>[ign]</td>
<td></td>
<td>[id]</td>
</tr>
</tbody>
</table>
30
|
{"Source-Url": "https://os.itec.kit.edu/downloads/sa_2006_blattmann-thomas_porting-l4ka-pistachio-to-mips32.pdf", "len_cl100k_base": 12198, "olmocr-version": "0.1.49", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 111732, "total-output-tokens": 12802, "length": "2e13", "weborganizer": {"__label__adult": 0.0005612373352050781, "__label__art_design": 0.0007991790771484375, "__label__crime_law": 0.0003643035888671875, "__label__education_jobs": 0.0011472702026367188, "__label__entertainment": 0.0001455545425415039, "__label__fashion_beauty": 0.0002491474151611328, "__label__finance_business": 0.0003266334533691406, "__label__food_dining": 0.0004916191101074219, "__label__games": 0.001117706298828125, "__label__hardware": 0.0159454345703125, "__label__health": 0.0006012916564941406, "__label__history": 0.0006122589111328125, "__label__home_hobbies": 0.00022172927856445312, "__label__industrial": 0.001483917236328125, "__label__literature": 0.00035071372985839844, "__label__politics": 0.0003345012664794922, "__label__religion": 0.000934600830078125, "__label__science_tech": 0.1754150390625, "__label__social_life": 9.512901306152344e-05, "__label__software": 0.007476806640625, "__label__software_dev": 0.78955078125, "__label__sports_fitness": 0.0004954338073730469, "__label__transportation": 0.00119781494140625, "__label__travel": 0.00027561187744140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45096, 0.05899]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45096, 0.20903]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45096, 0.88574]], "google_gemma-3-12b-it_contains_pii": [[0, 185, false], [185, 185, null], [185, 513, null], [513, 513, null], [513, 1699, null], [1699, 2412, null], [2412, 5118, null], [5118, 8022, null], [8022, 9550, null], [9550, 12539, null], [12539, 14600, null], [14600, 16468, null], [16468, 18698, null], [18698, 20902, null], [20902, 23035, null], [23035, 25095, null], [25095, 26360, null], [26360, 27990, null], [27990, 29857, null], [29857, 31543, null], [31543, 32708, null], [32708, 33910, null], [33910, 35795, null], [35795, 38449, null], [38449, 39647, null], [39647, 40179, null], [40179, 41458, null], [41458, 42967, null], [42967, 43926, null], [43926, 45096, null]], "google_gemma-3-12b-it_is_public_document": [[0, 185, true], [185, 185, null], [185, 513, null], [513, 513, null], [513, 1699, null], [1699, 2412, null], [2412, 5118, null], [5118, 8022, null], [8022, 9550, null], [9550, 12539, null], [12539, 14600, null], [14600, 16468, null], [16468, 18698, null], [18698, 20902, null], [20902, 23035, null], [23035, 25095, null], [25095, 26360, null], [26360, 27990, null], [27990, 29857, null], [29857, 31543, null], [31543, 32708, null], [32708, 33910, null], [33910, 35795, null], [35795, 38449, null], [38449, 39647, null], [39647, 40179, null], [40179, 41458, null], [41458, 42967, null], [42967, 43926, null], [43926, 45096, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45096, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45096, null]], "pdf_page_numbers": [[0, 185, 1], [185, 185, 2], [185, 513, 3], [513, 513, 4], [513, 1699, 5], [1699, 2412, 6], [2412, 5118, 7], [5118, 8022, 8], [8022, 9550, 9], [9550, 12539, 10], [12539, 14600, 11], [14600, 16468, 12], [16468, 18698, 13], [18698, 20902, 14], [20902, 23035, 15], [23035, 25095, 16], [25095, 26360, 17], [26360, 27990, 18], [27990, 29857, 19], [29857, 31543, 20], [31543, 32708, 21], [32708, 33910, 22], [33910, 35795, 23], [35795, 38449, 24], [38449, 39647, 25], [39647, 40179, 26], [40179, 41458, 27], [41458, 42967, 28], [42967, 43926, 29], [43926, 45096, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45096, 0.39352]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
f637b3266eb1aaa5b795d52049a1a6703daeacb7
|
Alviano, Mario and Faber, Wolfgang
Properties of Answer Set Programming with Convex Generalized Atoms
Original Citation
This version is available at http://eprints.hud.ac.uk/21036/
The University Repository is a digital collection of the research output of the University, available on Open Access. Copyright and Moral Rights for the items on this site are retained by the individual author and/or other copyright owners. Users may access full items free of charge; copies of full text items generally can be reproduced, displayed or performed and given to third parties in any format or medium for personal research or study, educational or not-for-profit purposes without prior permission or charge, provided:
- The authors, title and full bibliographic details is credited in any copy;
- A hyperlink and/or URL is included for the original metadata page; and
- The content is not changed in any way.
For more information, including our policy and submission procedure, please contact the Repository Team at: E.mailbox@hud.ac.uk.
http://eprints.hud.ac.uk/
Properties of Answer Set Programming with Convex Generalized Atoms
Mario Alviano and Wolfgang Faber
Department of Mathematics and Computer Science
University of Calabria
87036 Rende (CS), Italy
\{alviano,faber\}@mat.unical.it
Abstract. In recent years, Answer Set Programming (ASP), logic programming under the stable model or answer set semantics, has seen several extensions by generalizing the notion of an atom in these programs: be it aggregate atoms, HEX atoms, generalized quantifiers, or abstract constraints, the idea is to have more complicated satisfaction patterns in the lattice of Herbrand interpretations than traditional, simple atoms. In this paper we refer to any of these constructs as generalized atoms. Several semantics with differing characteristics have been proposed for these extensions, rendering the big picture somewhat blurry. In this paper, we analyze the class of programs that have convex generalized atoms (originally proposed by Liu and Truszczynski in [10]) in rule bodies and show that for this class many of the proposed semantics coincide. This is an interesting result, since recently it has been shown that this class is the precise complexity boundary for the FLP semantics. We investigate whether similar results also hold for other semantics, and discuss the implications of our findings.
1 Introduction
Various extensions of the basic Answer Set Programming language have been proposed by allowing more general atoms in rule bodies, for example aggregate atoms, HEX atoms, dl-atoms, generalized quantifiers, or abstract constraints. A number of semantics have been proposed for such programs, most notably the FLP semantics [7] and a number of coinciding semantics that we will collectively refer to as PSP semantics (from Pelov, Son, and Pontelli) [13,17]. All of these semantics coincide with traditional ASP semantics when no generalized atoms are present. Moreover, they coincide on programs that have atomic rule heads and contain only monotonic generalized atoms. In [9] it is furthermore hinted that the semantics also coincide on programs that have atomic rule heads and contain only convex generalized atoms. However, no formal proof is available for this claim, and the informal explanation given in [9] is not as general as it could be, as we will show.
In this paper, we undertake a deeper investigation on the similarities and differences between the FLP and PSP semantics. In order to do this, we consider a simplified, yet expressive propositional language: sets of rules with atomic heads and bodies that are formed of a single “structure,” which are functions mapping interpretations to Boolean values\(^1\). Clearly, structures encompass atoms, literals, and conjunctions thereof, but can
---
\(^1\) Note that (apart from the name) there is no connection to structures in first-order logic.
represent any propositional formula, generalized atom, or conjunctions of generalized atoms. Each structure has an associated domain, which is the set of propositional atoms on which the structure’s truth valuation depends. We can then classify the structures by their semantic properties, in particular, we will focus on the class of convex structures, which have single contiguous areas of truth in the lattice of interpretations. Convex structures include atoms and literals, and they are closed under conjunction (but not under negation or disjunction).
We first formally prove the claim that the FLP and PSP semantics coincide on programs with convex structures, as originally reported in [9]. We will then move on to the main focus of this paper, trying to understand whether there is any larger class for which the semantics coincide. It is known that for programs with general structures all PSP answer sets are FLP answer sets, but not all FLP answer sets are PSP answer sets. The precise boundary for exhibiting the semantic difference is instead unknown.
We will approach this question using complexity arguments. Recently, we could show that convex structures form the precise boundary for a complexity jump in the polynomial hierarchy on cautious reasoning (but most other decision problems as well) for the FLP semantics. Cautious reasoning is $\Pi_2^p$-complete for the FLP semantics when allowing any non-convex structure and its variants (renaming atoms) in the input program, but it is $\text{coNP}$-complete for convex structures. When considering the PSP semantics, cautious reasoning is also $\Pi_2^p$-complete when allowing any kind of structures in the input. This follows from a result in [13], and we provide an alternative proof in this paper. Analyzing this proof, it becomes clear that there is a different source of complexity for PSP than for FLP.
We then show that this different source of complexity also yields a different shape of the boundary for the complexity jump in PSP. Indeed, we first show that for a simple non-convex structure, cautious reasoning is still in $\text{coNP}$ for the PSP semantics, while the problem is $\Pi_2^p$-hard in the presence of this structure for the FLP semantics. It turns out that the same argument works for many non-convex structures, in particular, for all structures with a domain size bounded by a constant. The domain size therefore serves as a parameter that simplifies the complexity of the problem for the PSP semantics (unless the polynomial hierarchy collapses to its first level). This also means that the complexity boundary for PSP has a non-uniform shape, in the sense that an infinite number of different non-convex structures must be available for obtaining $\Pi_2^p$-hardness for cautious reasoning. This is in contrast to the FLP semantics, where the presence of a single non-convex structure is sufficient.
2 Syntax and Semantics
In this section we first introduce the syntax used in the paper. This is mainly based on the notion of structures, i.e., functions mapping interpretations into Boolean truth values. Then, we introduce few semantic notions and in particular we characterize structures in terms of monotonicity. Finally, we define the two semantics analyzed in this paper, namely FLP and PSP.
2.1 Syntax
Let $\mathcal{U}$ be a fixed, countable set of propositional atoms. An interpretation $I$ is a subset of $\mathcal{U}$. A structure $S$ on $\mathcal{U}$ is a mapping of interpretations into Boolean truth values. Each structure $S$ has an associated, finite domain $D_S \subseteq \mathcal{U}$, indicating those atoms that are relevant to the structure.
Example 1. A structure $S_1$ modeling a conjunction $a_1, \ldots, a_n$ ($n \geq 0$) of propositional atoms is such that $D_{S_1} = \{a_1, \ldots, a_n\}$ and, for every interpretation $I$, $S_1$ maps $I$ to true if and only if $D_{S_1} \subseteq I$.
A structure $S_2$ modeling a conjunction $a_1, \ldots, a_m$, not $a_{m+1}, \ldots, a_n$ ($n \geq m \geq 0$) of literals, where $a_1, \ldots, a_n$ are propositional atoms and not denotes negation as failure, is such that $D_{S_2} = \{a_1, \ldots, a_m\}$ and, for every interpretation $I$, $S_2$ maps $I$ to true if and only if $\{a_1, \ldots, a_m\} \subseteq I$ and $\{a_{m+1}, \ldots, a_n\} \cap I = \emptyset$.
A structure $S_3$ modeling an aggregate $\text{COUNT}(\{a_1, \ldots, a_n\}) \neq k$ ($n \geq k \geq 0$), where $a_1, \ldots, a_n$ are propositional atoms, is such that $D_{S_3} = \{a_1, \ldots, a_n\}$ and, for every interpretation $I$, $S_3$ maps $I$ to true if and only if $|D_{S_3} \cap I| \neq k$.
A general rule $r$ is of the following form:
$$H(r) \leftarrow B(r)$$
where $H(r)$ is a propositional atom in $\mathcal{U}$ referred as the head of $r$, and $B(r)$ is a structure on $\mathcal{U}$ called the body of $r$. A general program $P$ is a set of general rules.
Example 2. Let $S_4$ map to true any interpretation $I$ such that $I \cap \{a, b\} \neq \{b\}$, and let $S_5$ map to true any interpretation $I$ such that $I \cap \{a, b\} \neq \{a\}$. Hence, program
$$P_1 = \{a \leftarrow \text{SUM}(\{a = 1, b = -1\}) \geq 0 \}$$
is equivalent to the following program with aggregates:
$$a \leftarrow \text{SUM}(\{a = 1, b = -1\}) \geq 0$$
Note that no particular assumption is made on the syntax of rule bodies; in the case of normal propositional logic programs these structures are conjunctions of literals. We assume that structures are closed under propositional variants, that is, if $S$ is a structure, for any bijection $\sigma : \mathcal{U} \rightarrow \mathcal{U}$, also $S \sigma$ is a structure, and the associated domain is $D_{S \sigma} = \{\sigma(a) \mid a \in D_S\}$.
Example 3. Consider $S_4$ and $S_5$ from Example 2, and a bijection $\sigma_1$ such that $\sigma_1(a) = b$. Hence, $S_5 = S_4 \sigma_1$ that is, $S_5$ is a variant of $S_4$.
Given a set of structures $S$, by datalog$^S$ we refer to the class of programs that may contain only the following rule bodies: structures corresponding to conjunctions of atoms, any structure $S \in S$, or any of its variants $S \sigma$.
Example 4. For every $n \geq m \geq 0$, let $S^{m,n}$ denote the structure $S_2$ from Example 1.
The class of normal datalog programs is datalog$^{S^{m,n}[n \geq m \geq 0]}$.
Note that this syntax does not explicitly allow for negated structures. One can, however, choose the complementary structure for simulating negation. This would be akin to the “negation as complement” interpretation of negated aggregates that is prevalent in the literature.
2.2 Semantics
Let $I \subseteq \mathcal{U}$ be an interpretation. $I$ is a model for a structure $S$, denoted $I \models S$, if $S$ maps $I$ to true. Otherwise, if $S$ maps $I$ to false, $I$ is not a model of $S$, denoted $I \not\models S$. We require that atoms outside the domain of $S$ are irrelevant for modelhood, that is, for any interpretation $I$ and $X \subseteq \mathcal{U} \setminus D_S$ it holds that $I \models S$ if and only if $I \cup X \models S$. Moreover, for any bijection $\sigma : \mathcal{U} \to \mathcal{U}$, let $I_\sigma = \{ \sigma(a) \mid a \in I \}$, and we require that $I_\sigma \models S$ if and only if $I \models \sigma$. $I$ is a model of a rule $r$ of the form (1), denoted $I \models r$, if $H(r) \models I$ whenever $I \models B(r)$. $I$ is a model of a program $P$, denoted $I \models P$, if $I \models r$ for every rule $r \in P$.
Example 5. Consider program $P_1$ from Example 2. It can be observed that $\emptyset \not\models P_1$ and $\{a, b\} \not\models P_1$ (both rules have true bodies but false heads), while $\{a\} \models P_1$ and $\{b\} \models P_1$.
Structures can be characterized in terms of monotonicity as follows.
Definition 1 (Monotone Structures). A structure $S$ is monotonic if for all pairs $X, Y$ of interpretations such that $X \subseteq Y$, $X \models S$ implies $Y \models S$.
Definition 2 (Antimonotone Structures). A structure $S$ is antimonotonic if for all pairs $Y, Z$ of interpretations such that $Y \subseteq Z$, $Z \models S$ implies $Y \models S$.
Definition 3 (Convex Structures). A structure $S$ is convex if for all triples $X, Y, Z$ of interpretations such that $X \subseteq Y \subseteq Z$, $X \models S$ and $Z \models S$ implies $Y \models S$.
Note that monotonic and antimonotonic structures are convex. Moreover, note that convex structures are closed under conjunction (but not under disjunction or negation).
Example 6. Structure $S_{m,n}$ from Example 4 is convex in general; it is monotonic if $m = n$, and antimonotonic if $m = 0$. Structure $S_{k,3}$ from Example 1 instead, is non-convex if $n > k > 0$; it is monotonic if $k = 0$, and antimonotonic if $n = k$.
We first describe a reduct-based semantics, usually referred to as FLP, which has been described and analyzed in [6,7].
Definition 4 (FLP Reduct). The FLP reduct $P^I$ of a program $P$ with respect to $I$ is defined as the set $\{ r \in P \mid I \models B(r) \}$.
Definition 5 (FLP Answer Sets). $I$ is an FLP answer set of $P$ if $I \models P^I$ and for each $J \subseteq I$ it holds that $J \not\models P^I$.
Example 7. Consider program $P_1$ from Example 2 and the interpretation $\{a\}$. The reduct $P^I_1$ is $\{ a \leftarrow S \}$. Since $\{a\}$ is a minimal model of the reduct, $\{a\}$ is an FLP answer set of $P_1$. Similarly, it can be observed that $\{b\}$ is another FLP answer set. Actually, these are the only FLP answer sets of the program.
We will next describe a different semantics, using the definition of [17], called “fix-point answer set” in that paper. Theorem 3 in [17] shows that it is actually equivalent to the two-valued fix-point of ultimate approximations of generalized atoms in [13] and therefore with stable models for ultimate approximations of aggregates as defined in [14]. We will refer to it as PSP to abbreviate Pelov/Son/Pontelli, the names most frequently associated with this semantics.
Definition 6 (Conditional Satisfaction). A structure $S$ on $U$ is conditionally satisfied by a pair of interpretations $(I, M)$, denoted $(I, M) \models S$, if $J \models S$ for each $J$ such that $I \subseteq J \subseteq M$.
Definition 7 (PSP Answer Sets). An interpretation $M$ is a PSP answer set if $M$ is the least fixpoint of the following operator:
$$K^P_M(I) = \{ H(r) \mid r \in P \land (I, M) \models B(r) \}. \quad (2)$$
Example 8. Consider program $P_1$ from Example 2 and the interpretation $\{a\}$. The least fixpoint of $K^P_\{a\}$ is $\{a\}$. In fact, $\emptyset \models S_3$ and $\{a\} \models S_4$, hence $(\emptyset, \{a\}) \models S_3$ while $\{a\} \not\models S_4$ and thus $(\emptyset, \{a\}) \not\models S_4$ and $(\{a\}, \{a\}) \not\models S_4$. Therefore, $\{a\}$ is a PSP answer set. Also $\{b\}$ is a PSP answer set.
On programs considered in this paper, PSP answer sets also coincide with “answer sets” defined in [18] (by virtue of Proposition 10 in [18]) and “well-justified FLP answer sets” of [15] (by virtue of Theorem 5 in [15]). The latter is particularly interesting, as it is defined by first forming the FLP reduct. Indeed, as shown in [15], the operator $K^P_M$ can be equivalently defined as follows:
$$K^P_M(I) = \{ H(r) \mid r \in P^M \land (I, M) \models B(r) \}. \quad (3)$$
There are several other semantic definitions on programs that have some restrictions on the admissible structures, which also coincide with the PSP semantics on programs as defined in this paper with the respective structure restriction. Examples are [12] for monotonic structures (that are also allowed to occur in rule heads in that paper), or [16] that allows for structures corresponding to cardinality and weight constraints and largely coincide with the PSP semantics (see [13] for a discussion on structures on which the semantics coincides).
In this paper we are mainly interested in cautious reasoning, defined next.
Definition 8 (Cautious Reasoning). A propositional atom $a$ is a cautious consequence of a program $P$ under FLP (resp. PSP) semantics, denoted $P \models^c_{FLP} a$ (resp. $P \models^c_{PSP} a$), if $a$ belongs to all FLP (resp. PSP) answer set of $P$.
Example 9. Consider program $P_1$ from Example 2. We have $P_1 \not\models^c_{FLP} a$ and $P_1 \not\models^c_{FLP} b$, and similar for PSP semantics. If we add $a \leftarrow b$ and $b \leftarrow a$ to the program, then there is only one FLP answer set, namely $\{a, b\}$, and no PSP answer sets. In this case $a$ and $b$ are cautious consequences of the program (under both semantics).
There is an even closer relationship, as the operator $K^P_M(I)$ of [17] coincides with $\phi^P_{agr, 1}(I, M)$ defined in [13], as shown in the appendix of [17].
3 Exploring the Relationship between the FLP and PSP Semantics
In this section, we examine in detail how the FLP and PSP semantics relate. We shall proceed in three steps. First, we formally prove that FLP and PSP semantics coincide on programs with convex structures in Section 3.1. Next, we turn towards complexity as a tool to understand whether there can be any larger class of coinciding programs. We start in Section 3.2 with a result that shows that programs without restrictions exhibit the same complexity under both FLP and PSP semantics. However, it is known that the semantics do not coincide for programs without restrictions, and we examine the complexity proofs to highlight the different complexity sources. These findings are then applied in Section 3.3 in order to identify programs with bounded non-convex structures, on which the complexities for FLP and PSP semantics differ. Under usual complexity assumptions, this also implies that programs with convex aggregates is the largest class of programs on which FLP and PSP coincide.
3.1 Unison: Convex Structures
In this section we show that for programs with convex aggregates the FLP and PSP semantics coincide. In [9] it is stated that many semantics (and in particular, FLP and PSP) “agree on [...] programs with convex aggregates” because “they can be regarded as special programs with monotone constraints.” However, the comment on regarding convex aggregates as monotone constraints relies on a transformation described in [10] that transforms convex structures into conjunctions of positive and negated monotone constraints. Since our language does not explicitly allow negation, and in particular since convex structures are not closed under negation, we next prove in a more direct manner that the FLP and PSP semantics coincide on convex structures.
One direction of the proof relies on the well-known more general fact that each PSP answer set is also an FLP answer set. This has been stated as Theorem 2 in [17] and Proposition 8.1 in [14].
**Theorem 1.** Let \( P \) be program whose body structures are convex, and let \( M \) be an interpretation. \( M \) is an FLP answer set of \( P \) if and only if \( M \) is an PSP answer set of \( P \).
**Proof.** The left implication follows from Theorem 2 in [17]. For the right implication, let \( M \) be an FLP answer set of \( P \). Let \( K_0 := \emptyset \), \( K_{i+1} := K_{i}^P(M) \) for \( i \geq 0 \), and let \( K \) be the fixpoint of this sequence. Since \( M \) is a minimal model of \( P^M \) by definition of FLP answer set, we can prove the claim by showing (i) \( K \models P^M \) and (ii) \( K \subseteq M \).
(i) Consider a rule \( r \in P^M \) such that \( K \models B(r) \). We have to show \( H(r) \in K \). Since \( r \in P^M, M \models B(r) \) holds. Thus, \( (K, M) \models B(r) \) and therefore \( H(r) \in K \).
(ii) We prove \( K_i \subseteq M \) for each \( i \geq 0 \). We use induction on \( i \). The base case is trivially true as \( K_0 = \emptyset \subseteq M \). Suppose \( K_i \subseteq M \) for some \( i \geq 0 \) in order to prove \( K_{i+1} \subseteq M \). By definition of \( K_i^P \), for each \( a \in K_{i+1} \) there is \( r \in P^M \) such that \( H(r) = a \) and \( (K_i, M) \models B(r) \). Thus, \( M \models B(r) \), which implies \( a \in M \). \( \square \)
Therefore, programs with convex structures form a class of programs for which the FLP and PSP semantics coincide. In the following, we will show that it is likely also the largest class for which this holds.
3.2 Consonance: Complexity of Unrestricted Structures
In this section we will examine the computational impact of allowing non-convex structures. We will limit ourselves to structures for which the truth value with respect to an interpretation can be determined in polynomial time. Moreover, we will focus on cautious reasoning, but similar considerations apply also to related problems such as brave reasoning, answer set existence, or answer set checking.
It is known that cautious reasoning over programs with arbitrary structures under the FLP semantics is $\Pi^p_2$-complete in general, as shown in [7]. Pelov has shown $\Sigma^p_3$-completeness for deciding the existence of PSP answer sets in [13], from which $\Pi^p_2$-completeness for cautious reasoning under the PSP semantics can be derived. We formally state this result now and provide a different proof than Pelov’s that will more directly lead to the subsequent considerations.
**Theorem 2.** Cautious reasoning under PSP semantics is $\Pi^p_2$-complete.
**Proof.** Membership follows by Corollary 1 of [17]. For the hardness, we provide a reduction from 2-QBF. Let $\Psi = \forall x_1 \ldots \forall x_m \exists y_1 \ldots \exists y_n \ E$, where $E$ is in 3CNF. Formula $\Psi$ is equivalent to $\neg \Psi'$, where $\Psi' = \exists x_1 \ldots \exists x_m \forall y_1 \ldots \forall y_n \ E'$, and $E'$ is a 3DNF equivalent to $\neg E$ and obtained by applying De Morgan’s laws. To prove the claim we construct a program $P_\Psi$ such that $P_\Psi \models^{PSP} w$ (w a fresh atom) if and only if $\Psi$ is valid, i.e., iff $\Psi'$ is invalid.
Let $E' = (l_{i,1} \land l_{i,2} \land l_{i,3}) \lor \cdots \lor (l_{k,1} \land l_{k,2} \land l_{k,3})$, for some $k \geq 1$. Program $P_\Psi$ is the following:
\[
\begin{align*}
x_i^T & \leftarrow \neg x_i^F & i \in \{1, \ldots, m\} \quad (4) \\
y_i^T & \leftarrow \neg y_i^F & i \in \{1, \ldots, n\} \quad (5) \\
y_i^T & \leftarrow \text{sat} & i \in \{1, \ldots, n\} \quad (6) \\
w & \leftarrow \neg \text{sat} \quad (7)
\end{align*}
\]
where $\mu$ is defined recursively as follows:
- $\mu(E') := (\mu(l_{i,1}) \land \mu(l_{i,2}) \land \mu(l_{i,3})) \lor \cdots \lor (\mu(l_{k,1}) \land \mu(l_{k,2}) \land \mu(l_{k,3}));$
- $\mu(x_i) := x_i^T$ and $\mu(\neg x_i) := x_i^F$ for all $i = 1, \ldots, m$;
- $\mu(y_i) := y_i^T$ and $\mu(\neg y_i) := y_i^F$ for all $i = 1, \ldots, n$.
Note that structure $\mu(E')$ can also be encoded by means of a sum aggregate as shown in (1).
Rules (4)–(6) force each PSP answer set of $P_\Psi$ to contain at least one of $x_i^T$, $x_i^F$ ($i \in \{1, \ldots, m\}$), and one of $y_j^T$, $y_j^F$ ($j \in \{1, \ldots, n\}$), respectively, encoding an assignment of the propositional variables in $\Psi'$. Rules (6) are used to simulate universality of the $y$ variables, as described later. Having an assignment, rule (7) derives sat if the assignment satisfies some disjunct of $E'$ (and hence also $E'$ itself). Finally, rule (8) derives $w$ if sat is false.
We first show that $\Psi$ not valid implies $P_\Psi \not\models^{PSP} w$. If $\Psi$ is not valid, $\Psi'$ is valid. Hence, there is an assignment $\nu$ for $x_1, \ldots, x_m$ such that no extension to $y_1, \ldots, y_n$ satisfies $E$, i.e., all these extensions satisfy $E'$. Let us consider the following interpretation
(which is also a model of $P_\psi$):
$$M = \{x_i^T | \nu(x_i) = 1, i = 1, \ldots, m\} \cup \{x_i^F | \nu(x_i) = 0, i = 1, \ldots, m\}$$
$$\cup \{y_i^T, y_i^F | i = 1, \ldots, n\} \cup \{sat\}$$
We claim that $M$ is a PSP answer set of $P_\psi$. In fact, $K_{M_\psi}(\emptyset) \supseteq \{x_i^T | \nu(x_i) = 1, i = 1, \ldots, m\} \cup \{x_i^F | \nu(x_i) = 0, i = 1, \ldots, m\}$ because of rules (4) in $P_M^\psi$. Since any assignment for the $y$s satisfies at least a disjunct of $E'$, from rule (7) we derive $sat \in K_{M_\psi}^P (K_{M_\psi}^P (\emptyset))$. Hence, rules (6) force all $y$ atoms to belong to $K_{M_\psi}^P (K_{M_\psi}^P (\emptyset))$, which is thus the least fixpoint of $K_{M_\psi}^P$ and coincides with $M$.
Now we show that $P_\psi \not\models_{c \text{-PSP}} w$ implies that $\Psi$ is not valid. To this end, let $M$ be a PSP answer set of $P_\psi$ such that $w \notin M$. Hence, by rule (6), we have that $M \models sat$. From $sat \in M$ and rules (6), we have $y_i^T, y_i^F \in M$ for all $i = 1, \ldots, n$. And $M$ contains either $x_i^T$ or $x_i^F$ for $i = 1, \ldots, m$ because of rules (4). Suppose by contradiction that $\Psi$ is valid. Thus, for all assignments of $x_1, \ldots, x_m$, there is an assignment for $y_1, \ldots, y_n$ such that $E$ is true, i.e., $E'$ is false. We can show that the least fixpoint of $K_{M_\psi}^P$ is $K_{M_\psi}^P (\emptyset) = \{x_i^T | \nu(x_i) = 1, i = 1, \ldots, m\} \cup \{x_i^F | \nu(x_i) = 0, i = 1, \ldots, m\}$. In fact, $sat$ cannot be derived because $K_{M_\psi}^P (\emptyset) \not\models \mu (E')$. We thus have a contradiction with the assumption that $M$ is a PSP answer set of $P_\psi$.
It is also known that the complexity drops to $\text{coNP}$ if structures in body rules are constrained to be convex. This appears to be “folklore” knowledge and can be argued to follow from results in [10]. An easy way to see membership in $\text{coNP}$ is that all convex structures can be decomposed into a conjunction of a monotonic and an antimonotonic structure, for which membership in $\text{coNP}$ has been shown in [7].
It is instructive to note a crucial difference between the $\Pi^P_2$-hardness proofs in [7] (and a similar one in [8]) and the proofs for Theorem 2 and the $\Sigma^P_2$ result for PSP in [13].
The fundamental tool in the FLP hardness proofs is the availability of structures $S_1, S_2$ that allow for encoding “need to have either atom $x^T$ or $x^F$, or both of them, but the latter only upon forcing the truth of both atoms.” $S_1, S_2$ have domains $D_{S_1} = D_{S_2} = \{x^T, x^F\}$ and the following satisfaction patterns:
$$\emptyset \models S_1 \quad \{x^T\} \models S_1 \quad \{x^F\} \not\models S_1 \quad \{x^T, x^F\} \models S_1$$
$$\emptyset \models S_2 \quad \{x^T\} \not\models S_2 \quad \{x^F\} \models S_2 \quad \{x^T, x^F\} \not\models S_2$$
The reductions then use these structures in a similar way than disjunction is used in the classic $\Sigma^P_2$-hardness proofs in [3]. In particular, the same structures are used for all instances to be reduced.
On the other hand, in the PSP hardness proofs, one dedicated structure is used for each instance of the problem reduced from (2QBF in Theorem 2). Indeed, a construction using structures $S_1, S_2$ as described earlier is not feasible for PSP, because $(\emptyset, \{x^T, x^F\}) \not\models S_1$ and $(\emptyset, \{x^T, x^F\}) \not\models S_2$. This is because there is one satisfaction “hole” between $\emptyset$ and $\{x^T, x^F\}$ for both $S_1$ and $S_2$. In the next section, we will exploit this difference.
3.3 Dissonance: Complexity of Non-convex Structures with Bounded Domains
In this section, we look more carefully at programs with non-convex structures and identify computational differences between the FLP and PSP semantics. In [2] it has been shown that any non-convex structure (plus all of its variants) can be used in order to implement $S_1$ and $S_2$. This result makes it clear that the presence of any non-convex structure that is closed under variants causes a complexity increase for the FLP semantics (unless the polynomial hierarchy collapses). From the above considerations, it is immediately clear that the same construction is not feasible for PSP. It turns out that also no alternative way exists to obtain a similar result, and that the difference in the $\Pi_2^p$-hardness proofs for FLP and PSP is intrinsic.
We start by considering a simple non-convex structure $\tilde{A}$ with $D_{\tilde{A}} = \{x, y\}$ and $I |\tilde{A}$ if and only if $|I \cap D_{\tilde{A}}| \neq 1$. Therefore, $\tilde{A}$ behaves like a cardinality constraint $\text{COUNT}(\{x, y\}) \neq 1$.
**Proposition 1.** Deciding whether an interpretation $M$ is a PSP answer set of a datalog $\{\tilde{A}\}$ program $P$ is feasible in polynomial time, in particular $\text{DTIME}(m^2)$, where $m$ is the number of rules in $P$.
**Proof.** For any interpretation, testing whether $(I, M) \models \tilde{A}\sigma$ (for a variant $\tilde{A}\sigma$ of $\tilde{A}$) can be done by examining $|I \cap D_{\tilde{A}\sigma}| = i$ and $|M \cap D_{\tilde{A}\sigma}| = j$ and returning false if either one of $i, j$ is 1, or if $i = 0$ and $j = 2$. Alternatively, in a less syntax dependent way, one can test whether $M \models \tilde{A}\sigma$ and $(I \cup J) \models \tilde{A}\sigma$ for each $J \subseteq (M \cap D_{\tilde{A}\sigma}) \setminus (I \cap D_{\tilde{A}\sigma})$. Since there are at most 4 different $J$ for each $I$, either method is feasible in constant time.
For determining whether $M$ is a PSP answer set of $P$, we can check whether it is the least fixpoint of $K_M^P$. Computing the least fixpoint takes at most $m$ applications of $K_M^P$ (where $m$ is the number of rules in $P$). Each application of $K_M^P$ involves in turn at most $m$ tests for $(I, M) \models \tilde{A}\sigma$. \hfill \Box
Given Proposition 1, it follows that cautious reasoning is still in $\text{coNP}$ for datalog $\{\tilde{A}\}$ programs under the PSP semantics.
**Proposition 2.** Given a datalog $\{\tilde{A}\}$ program $P$ and an atom $a$, deciding $P \models a^{\text{PSP}}$ is in $\text{coNP}$.
**Proof.** The complement has an immediate nondeterministic polynomial time algorithm: guess an interpretation $M$ and verify in polynomial time that $a \notin M$ and that $M$ is a PSP answer set of $P$ (by virtue of Proposition 1). \hfill \Box
It follows that for datalog $\{\tilde{A}\}$, cautious reasoning (and also answer set existence and brave reasoning) is more complex for the FLP semantics than for the PSP semantics (unless the polynomial hierarchy collapses to its first level).
Examining this result and its proof carefully, we can see that it depends on the fact that each $D_{\tilde{A}\sigma}$ contains 2 elements and therefore at most 4 satisfaction tests are needed to determine $(I, M) \models \tilde{A}\sigma$. Indeed, we can apply similar reasoning whenever the domains of involved structures are smaller than a given bound.
Theorem 3. Let \( P \) be a program. If \( k \) is an upper bound for the domain size of any structure occurring in \( P \), then checking whether a given interpretation \( M \) is a PSP answer set of \( P \) is decidable in \( \text{DTIME}(2^k m^2 p(n)) \), where \( m \) is the number of rules in \( P \) and \( p(n) \) is the polynomial function (in terms of the input size \( n \)) bounding determining satisfaction of any aggregate in \( P \).
Proof. We show that the least fixpoint of \( K^P_M \) can be computed in time \( O(2^k m^2 p(n)) \). In the worst case, each application of the operator derives at most one new atom, and thus the fixpoint is reached after at most \( m \) applications of the operator. Each application requires at most the evaluation of all rules of \( P \), and thus at most \( m^2 \) rule evaluations are sufficient. To evaluate a rule, the truth of the body has to be checked w.r.t. at most \( 2^k \) interpretations (similar to Proposition 1, in which \( k = 2 \)), each requiring \( p(n) \) time. We thus obtain the bound \( O(2^k m^2 p(n)) \). \( \square \)
This means that actually most languages with non-convex structures exhibit a complexity gap between the FLP and PSP semantics. There is a uniformity issue here, which we informally noted earlier when examining the \( \Pi_2^P \)-hardness proof for cautious reasoning under PSP. We can now formalize this, as it follows from Theorem 3 that we need an infinite number of inherently different non-convex structures in order to obtain \( \Pi_2^P \) hardness.
Corollary 1. Let \( S \) be any finite set of structures, possibly including non-convex structures. Cautious reasoning over datalog\(^S\) is in \( \text{coNP} \) under the PSP semantics.
This means that there is also a clear difference in uniformity between the complexity boundary of the FLP and the PSP semantics, respectively. It also means that it is impossible to simulate the FLP semantics in a compact way using the PSP semantics on the class of programs with bounded domain structures, unless the polynomial hierarchy collapses to its first level. The general picture of our complexity results is shown in Figure 1. We can see that the complexity transition from \( \text{coNP} \) to \( \Pi_2^P \) is different for the FLP and PSP semantics, respectively. The solid line between convex and non-convex structures denotes a crisp transition for FLP, while the dashed line between bounded non-convex and unbounded non-convex structures is a rougher transition.
4 Discussion
Looking at Figure 1 the transition from \( \text{coNP} \) to \( \Pi_2^P \) appears somewhat irregular for PSP, as the availability of single non-convex structures does not cause the transition, but only their union. However, in practice the availability of an infinite number of different structures is not unusual: indeed, if aggregates are considered, the presence of one aggregate function and suitable comparison relations usually gives rise to such an infinite repertoire of structures.
Example 10. Consider the availability of \( \text{COUNT} \) over any set of atoms and the comparison relation \( \neq \). The structures generated by aggregates of the form \( \text{COUNT}(S) \neq i \) do not have a bound on the domains of non-convex aggregates. Indeed, for any structure \( \text{COUNT}((a_1, \ldots, a_k)) \neq 1 \), which is non-convex and for which the domain size is \( k \),
one can formulate also $\text{COUNT}(\{a_1, \ldots, a_{k+1}\}) \neq 1$, which is also non-convex and has a larger domain.
However, as noted earlier, for expressing $\Pi_2^p$-hard problems, one needs a non-uniform approach for PSP, in the sense that a dedicated aggregate has to be formulated for each problem instance, whereas for FLP one can re-use the same aggregates for all problem instances.
In practical terms, our results imply that for programs containing only convex structures, techniques as those presented in [1] for FLP can be used for computing answer sets also for PSP, and techniques presented for PSP can be used for FLP in turn. It also means that this is the largest class for which this can be done with currently available methods in an efficient way. There are several examples for convex structures that are easy to identify syntactically: count aggregates with equality guards, sum aggregates with positive summands and equality guards, dl-atoms that do not involve $\cap$ and rely on a tractable Description Logic [4]. However many others are in general not convex, for example sum aggregates that involve both positive and negative summands, times aggregates that involve the factor 0, average aggregates, dl-atoms with $\cap$ and so on. It is still possible to find special cases of such structures that are convex, but that requires deeper analyses.
The results also immediately imply impossibility and possibility results for rewritability: unless the polynomial hierarchy collapses to its first level, it is not possible in the FLP semantics to rewrite a program with non-convex structures into one containing only convex structures (for example, a program not containing any generalized atoms), unless disjunction or similar constructs are allowed in rule heads. On the other hand, such rewritings are possible for the PSP semantics if the non-convex structures are guaranteed to have bounded domains. This seems to be most important for dl-programs, where such rewritings are sought after.
The semantics considered in this paper encompass several approaches suggested for programs that couple answer set programming with description logics. The approaches presented in [5] and [11] directly employ the FLP semantics, while the approach of [15]
is shown to be equivalent to the PSP semantics. There are other proposals, such as [4], which appears to be different from both FLP and PSP already on convex structure. In future work we plan to relate also these other semantics with FLP and PSP and attempt to identify the largest coinciding classes of programs.
References
|
{"Source-Url": "http://eprints.hud.ac.uk/21036/1/1312.6096v1.pdf", "len_cl100k_base": 10085, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 52315, "total-output-tokens": 12292, "length": "2e13", "weborganizer": {"__label__adult": 0.0004901885986328125, "__label__art_design": 0.0005211830139160156, "__label__crime_law": 0.0007901191711425781, "__label__education_jobs": 0.00281524658203125, "__label__entertainment": 0.00015544891357421875, "__label__fashion_beauty": 0.00028133392333984375, "__label__finance_business": 0.0005803108215332031, "__label__food_dining": 0.0007190704345703125, "__label__games": 0.0011873245239257812, "__label__hardware": 0.0010232925415039062, "__label__health": 0.001739501953125, "__label__history": 0.0004982948303222656, "__label__home_hobbies": 0.0002321004867553711, "__label__industrial": 0.0008554458618164062, "__label__literature": 0.0009822845458984375, "__label__politics": 0.0005702972412109375, "__label__religion": 0.000774383544921875, "__label__science_tech": 0.29052734375, "__label__social_life": 0.00019466876983642575, "__label__software": 0.0096588134765625, "__label__software_dev": 0.68359375, "__label__sports_fitness": 0.0003962516784667969, "__label__transportation": 0.0010128021240234375, "__label__travel": 0.0002586841583251953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40694, 0.02397]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40694, 0.64023]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40694, 0.86868]], "google_gemma-3-12b-it_contains_pii": [[0, 1300, false], [1300, 4162, null], [4162, 7461, null], [7461, 10755, null], [10755, 13674, null], [13674, 16907, null], [16907, 20465, null], [20465, 23801, null], [23801, 27394, null], [27394, 30821, null], [30821, 34247, null], [34247, 36527, null], [36527, 39995, null], [39995, 40694, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1300, true], [1300, 4162, null], [4162, 7461, null], [7461, 10755, null], [10755, 13674, null], [13674, 16907, null], [16907, 20465, null], [20465, 23801, null], [23801, 27394, null], [27394, 30821, null], [30821, 34247, null], [34247, 36527, null], [36527, 39995, null], [39995, 40694, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40694, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40694, null]], "pdf_page_numbers": [[0, 1300, 1], [1300, 4162, 2], [4162, 7461, 3], [7461, 10755, 4], [10755, 13674, 5], [13674, 16907, 6], [16907, 20465, 7], [20465, 23801, 8], [23801, 27394, 9], [27394, 30821, 10], [30821, 34247, 11], [34247, 36527, 12], [36527, 39995, 13], [39995, 40694, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40694, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
8728b3bd2cdf98747945736ca55372cd07dbce32
|
Hierarchical Distribution of Consistency-relevant Changes in a Collaborative Engineering Environment
1st Michael Alexander Tröls
Johannes Kepler University, Linz, Austria
michael.troels@jku.at
2nd Atif Mashkoor
Johannes Kepler University, Linz, Austria
atif.mashkoor@jku.at
3rd Alexander Egyed
Johannes Kepler University, Linz, Austria
alexander.egyed@jku.at
Abstract—Engineering is a collaborative process, incorporating a multitude of heterogeneous artifacts. These artifacts share interdependent properties, which must be kept consistent during the engineering process (e.g., code must correspond to architectural design documents). To address this circumstance, existing works propose the unification of heterogeneous artifacts in a single collaborative engineering environment where artifacts are analysed for consistency on the basis of their interdependent properties. The work presented in this paper expands the collaboration possibilities of such environments by adopting hierarchically organized work areas storing artifact changes. We discuss different implications such hierarchies have on the computation of consistency information and propose a mechanism of instantly distributing consistency-relevant change information throughout the collaborative engineering environment. This way, engineers are provided with a unique perspective on their engineering artifacts, which is immediately re-evaluated whenever new changes are made within the hierarchy. To evaluate this mechanism, we provide an experiment – motivating the instant distribution of change information – as well as a scenario simulation – testing our mechanism against an exhaustive set of possible inputs.
Index Terms—collaboration, engineering artifacts, consistency checking
I. INTRODUCTION
In modern engineering projects, many experts from various fields contribute a multitude of different engineering artifacts. These engineering artifacts, such as requirements, specifications or code, are highly interdependent. If such engineering artifacts change, all dependent artifacts must change with them. We refer to maintaining the consistency between heterogeneous, interdependent engineering artifacts as global consistency checking. This form of consistency checking can become very complex since many artifacts, which may not be intuitively related, are often implicitly dependent on each other. For example, specifications may have an impact on designs, which, in turn, may have an impact on code.
The research reported in this paper has been partly funded by the Austrian Science Fund (FWF) grants (P31989-N31 & I4744-N), the Austrian COMET K1-Centre Pro2Future and the Austrian COMET K2-Centre LCM funded by the Austrian Research Promotion Agency (FFG) in cooperation with the Austrian ministries BMVIT and BMDW and the province of Upper Austria, and the LIT Secure and Correct Systems Lab supported by the province of Upper Austria.
Various works have proposed ways of unifying engineering artifacts in collaborative engineering environments (CEE) (e.g., [20]–[23]). In such a CEE, engineering artifacts are synchronized from their respective tools and stored in a syntactically uniform representation. Contrary to currently established collaboration systems (e.g., versioning software like Git\(^1\) or SVN\(^2\)) this allows the engineers to natively store heterogeneous engineering artifacts. On this foundation, the artifact’s properties can be analysed by a consistency checking mechanism – making global consistency checking feasible.
However, a problem arises with regards to the iterative workflows common in modern engineering projects. A CEE with a single global artifact storage may be fit for integrating large milestones of a project and checking them in intervals of several weeks or months, but global consistency checking must meet the requirements of continuous integration. This requires the continuous analysis of the engineers’ artifact changes throughout the engineering process.
The work presented in this paper expands the concept of global consistency checking within a CEE by further differentiating the artifact storage and elaborating on the mechanisms necessary to keep consistency therein. We distinguish between public artifacts, which are generally available to engineers in a common repository, and private artifact changes that are adopted within separate, private storages. We define a change as a creation, update or removal of an artifact’s properties with regards to its public state. We organize private storages in a hierarchical structure, where the child’s changes always overrule the parent’s changes (respectively the public state of an artifact, which acts as a hierarchy root).
Both public artifacts and hierarchically ordered private changes in combination result in a specific perspective on the artifact storage. Every level in this hierarchy reveals a certain state of artifacts corresponding to a certain set of changes. Every set of changes has its own implications on the consistency of artifacts. We compute the consistency information concerning these changes before they are committed through
\(^1\)Git: https://git-scm.com
\(^2\)SVN: https://subversion.apache.org
the hierarchy. This requires us to continuously distribute all consistency-relevant change information (i.e., all changes that may affect the consistency state of a perspective) down the hierarchy for potential consistency re-evaluations, as some perspectives may become out-of-date. This distribution mechanism is the core novelty of this work. It contributes the possibility to provide consistency information concerning the perspectives on the artifact storage. An instant distribution is required, so engineers can continuously check their changes in relation to a collaborative state of engineering artifacts (stored in a higher level such as the public area) before they start merging their work.
The rest of this paper is structured as follows: In Section II, we describe a typical consistency checking scenario. In Section III, we outline the issues arising within the illustrative example. In Section IV, we present the data model of the CEE as the technical foundation for our mechanism of instantly distributing change information. The proposed mechanism is then discussed in Section V. We evaluate our work with an experiment and an exhaustive scenario simulation, which are discussed in Section VI. The related work is discussed in Section VII. The paper is concluded in Section VIII.
II. ILLUSTRATIVE EXAMPLE
To demonstrate the functionality and benefit of hierarchical work areas with instant distribution of consistency information, this section outlines an illustrative example. Assume the following scenario: A company is developing and deploying robot arms for the maintenance lines of various factories. Within this setup, three engineers: Alice, Bob and Carol, are working on separately developed but interdependent engineering artifacts. Alice is creating UML activity diagrams that guide the implementation of robot logic while Bob is setting up and maintaining hardware specifications for the entire engineering department. In his line of work, Bob is also responsible for maintaining various specification documents some of which are relevant to Alice’s work. Carol is implementing and maintaining the code based on the results of both Alice’s and Bob’s work. All engineers are using a CEE, which records individual artifact changes. The hierarchical order of work areas sees both Alice’s and Bob’s work joined in a private work area, directly subordinate to the public area. Carol’s private work area acts as an equal sibling to this joined private work area. This way, Alice’s and Bob’s committed changes are first considered privately before they become visible (public) to Carol. This setup is illustrated in Figure 1.
Imagine now the following adaptions: Bob receives a new hardware specification for the latest version of a robot arm. He does his necessary calculations and updates the corresponding specifications. He synchronizes his changes with the CEE as depicted in step 1 of Figure 1. In the meantime, Alice is working on an activity diagram which references hardware-related constants, as specified by Bob.
Bob commits his work from his private work area to the joined work area (step 2). At this point, his changes are only visible to him and Alice. They are not yet visible to Carol. Since Alice’s diagram still contains reference to the old operational distance of the robotic arm, she must now realize that her work is inconsistent. The corresponding consistency check is triggered instantly as the consistency-relevant change information (Bob’s adaptation of the specified operational distance of the robotic arm) becomes visible from Alice’s perspective on the artifact storage (step 3). Alice, now aware of Bob’s changes, can adapt her work (step 4), before committing it (step 5). The sooner she is aware of the changes, the less effort it will take to integrate them. Otherwise, at the time of the commit the inconsistency may have propagated into other parts of her work and may require substantial refactoring.
With Alice’s and Bob’s consistent changes committed to the joint work area, the said work area can be committed to the public area (step 6). After this commit, Carol will be aware of the new specification and the changed activity diagram (step 7). She can now adapt her implementation accordingly (step 8) and commit her work to the public area (step 9).
Alternatively, we could set this scenario up without the hierarchical structure of private work areas and immediately commit all changes into the public area; however, this may cause problems. Had either Alice or Bob committed an inconsistent state of their work, the issue would have been propagated into Carol’s work.
III. PROBLEM STATEMENT
Due to the delayed propagation of consistency information, various problems may arise.
- **Merging delays**: In many collaboration systems, conflict identification is tackled when the work of different engineers is brought together (e.g., while merging branches on Git). If a conflict is detected, the merging process is unnecessarily delayed. This may lead to organizational problems, as well as hasty resolutions or workarounds.
- **Extensive refactoring**: To tackle problems during merging, engineers must often carefully refactor portions of their work. This is a particular problem if conflicts are deeply rooted in the work that is about to be merged.
- **Tolerated inconsistencies**: During the engineering process, some temporary inconsistencies may be tolerated (e.g., between designs and implementation to guarantee a flexible workflow) [18]. However, in many cases the documentation of these inconsistencies is lacking. This potentially leads to flaws that are – if at all – recognized much later, which makes them harder to correct [19].
These problems could be avoided through the instant propagation of consistency information, gathered from consistency checks between heterogeneous artifacts. Delays during the merging phase can be countered through a simplified preparation of engineering artifacts, while they are still worked on. Counter-checked against the work of other engineers, engineering artifacts can be adapted to match before the merging process is started. Furthermore, they can be adapted in an ongoing manner, immediately when an inconsistency with the work of another engineer arises. This saves the engineers work with regards to refactoring. Tolerated inconsistencies can
be kept in check as consistency checking results are stored as a part of the propagated consistency information.
IV. DATA MODEL
In this work, we use a CEE to store engineering artifacts from different engineering tools. These tools are equipped with custom tool adapters, which synchronize the artifacts with the environment. Once synchronized, artifacts are stored in a unified representation. This representation can be analyzed, read or modified by engineers or supporting services such as a consistency checker (an exemplary synchronization can be seen in the supplementary material respectively online3).
Throughout the process of storing and analyzing engineering artifacts, the CEE provides a syntactic common ground. Its data model helps us implementing the instant distribution of consistency-relevant change information. In the following, we will re-iterate the data model’s elements, which can be seen in Figure 2. We distinguish between Artifact Storage Elements – data model elements concerned with the storage of engineering artifact information, Artifact Declaration Elements – data model elements concerned with the declaration of an artifacts structure, and Consistency Checking Elements – data model elements with both declarative and information storage purpose.
A. Artifact Storage Elements
Artifact Storage Elements are responsible for the storage of engineering artifact information. They represent concrete work results of the engineering process, respectively changes performed on fine-grained aspects thereof.
- **Artifacts:** An artifact represents a certain work result achieved during the engineering process. Such a work result could, for example, be code or requirements. To guarantee a certain structure, artifacts adhere to a certain type (e.g., Java Class Artifact or Requirements Artifact). Depending on the type, artifacts consist of specific properties.
- **Property:** Properties represent fine-grained aspects of a work result. Such fine-grained aspects may, for example, be methods within code or names of requirements.
3Exemplary synchronization: https://tinyurl.com/y7pny6ao
A property’s current value is determined by the latest change on the respective aspect. Earlier changes are part of a property’s change history. As such, the properties of an artifact describe an incrementally built sum of all changes on an engineer’s work results. Properties must adhere to a field declared within an artifact’s type.
- **Change**: A change represents a certain value of a named property at a certain time. It contains a timestamp as well as a change type – a property can either be created, updated or deleted. A change is always denoted as the product of exactly one work area (i.e., its origin). Every incremental change triggers a change event that is propagated through the engineering environment and read by potential listeners, e.g., a consistency checking mechanism.
- **Work area**: Work areas contain changes, which refer to properties, which, in turn, form artifacts. The latest change value represents the current value of a property. Work areas are organized in a hierarchy. The lowest work areas in this hierarchy only store the changes performed by a single, respective engineer. Only the engineer that created the work area can see its contents; therefore, we refer to it as a “Private Work Area” (PWA). When an engineer decides to make his or her changes visible to other engineers, these changes are committed into a higher work area. Every lower work area can access the contents of its parent. Subsequently, the contents of the highest work area are publicly available to every engineer. We refer to this work area as the “Public Area” (PA). Contrary to PWAs, which only store an engineer’s individual changes on properties, the PA contains the entire incremental change history of a property. If a PWA commits a property change, the change is added to the existing changes in its parent and eventually the PA. Every PWA must have exactly one parent. The advantage of this approach lies within the fact that every engineer, creating a PWA, can retrieve a certain individual perspective on the artifact storage. This perspective is dependent on the changes stored within the PWA hierarchy and the full artifact representation in the PA. It should be noted that changes in a PWA always overrule current changes in the PWA’s parents, respectively the PA. If, for example, we regard the simple work area hierarchy within Figure 3, we can see that for work area “PWA1” the artifact with ID 78 would retrieve “0.75m” for its property “length” whereas work area “PWA2” would retrieve “1.00m”. From the perspective of work area “PWA2” both “name” and “variant” have been changed. For “PWA1” these properties still appear as “Robot Arm” and “1.74_A”. The full representation of the artifact with ID 78 is different from the perspective of both PWA’s, respectively the tool adapters that utilize them. Further, work areas have a certain timestamp. The timestamp denotes the time of the work areas creation.
---
**Fig. 3.** An overview of an artifact as represented in the context of a work area hierarchy.
---
**B. Artifact Declaration Elements**
Artifact Declaration Elements are concerned with the definition of an artifact’s structure. They are defined by users through the tool adapters and can be instantiated as concrete artifacts.
- **Type**: A type defines the structure of an artifact in the form of fields. Types are automatically instantiated as artifacts when the tool adapters synchronize engineering artifacts to the CEE.
- **Field**: A field is part of a type and describes a property of an artifact. It defines the property’s primitive data type as well as its cardinality.
**C. Consistency Checking Elements**
Basic consistency checking in the cloud environment is realized as a service running in parallel to engineers modifying the artifact storage. It analyzes changes on engineering artifacts and notifies the respective engineer who issued the change. Consistency checking is always performed from the perspective of a certain work area. The checks themselves happen according to certain user-defined consistency rules. The consistency checker requires two kinds of information, which are stored as artifacts as well:
- **Consistency Rule Definition artifacts (CRD)**: These artifacts contain a defined rule for a certain artifact type (the “context” of a rule). For example, a rule definition for Java Class artifacts might define a naming convention on the classes’ methods. These methods may be stored as separate, linked artifacts. The defined rule, a simple string, then formalizes a way to navigate through the artifact storage from the class artifact to the method artifacts and their name properties. Consistency Rule Definitions are stored as artifacts so they can easily be retrieved from the perspective of a Consistency Rule Evaluation artifact.
- **Consistency Rule Evaluation artifacts (CRE)**: These artifacts realize a Consistency Rule Definition for a certain artifact instance (the “Context Element” (CE)). They contain a scope, which is a collection of all properties navigated through during a rule evaluation.
For the Java Class example, the scope would contain every property linking between the class artifact instance and the method artifact instances as well as the name properties of the method artifact instances. Should any of these scoped properties change, a re-evaluation of the respective Consistency Rule Evaluation artifact is triggered. Re-evaluation results are treated like any other artifact property. They can change on a work area basis. Keeping this information in the artifact storage, rather than in the inner logic of the consistency checker, has the advantage that it can easily be read by other services and re-used for further analysis.
As mentioned above, consistency rules are written as simple strings defining a navigation path through the artifact structure. In fact, they are a set of expressions connected through operations, which are executed on whatever values stand at the end of the navigation path. An operation could, for example, be a simple “equals”. Furthermore, these operations can be connected in conjunctions. Formalized, a rule can be expressed as follows:
\[
\text{Conjunction(Operator(\text{Expression}_A, \text{Expression}_B)^{1...})}
\]
A single expression is written in an object-access like manner, denoting properties of the artifacts that are navigated. For example, the expression
\[
\text{self.type.name}
\]
would navigate from a certain artifact instance (“self”) through a link to it’s type and retrieve the name of the said type artifact. In its basic implementation, the core functionality of the consistency checker is activated for the PA of the cloud engineering environment. It listens to artifact change events, which trigger the following normal course:
1) **Change analysis:** If the change concerns the creation of an artifact for whose type there is a CRD, the consistency checker automatically instantiates a corresponding CRE and continues with the “Data Gathering” process. If the change concerns a property that is part of a scope, the respective consistency rules must be re-evaluated. This is done by retrieving the associated CRE, which also initiates the “Data Gathering” process. All changes leading to this process are considered consistency-relevant.
2) **Data gathering:** During the data gathering process, the consistency checker first retrieves the concrete CRD through the CRE (see data model in Figure 2). From the CRD, the consistency rule is retrieved. The consistency checker then navigates through the artifact structure as it is described within the rule that is re-evaluated. Encountered values are stored for the evaluation.
3) **Rule evaluation:** During the evaluation, the expressions of the consistency rule are substituted with the stored values. The encapsulating operations are executed and the final logical conjunction is constructed.
4) **Storing results:** The final result is stored as a change on the CRE’s result property.
5) **Providing consistency feedback:** The consistency checking mechanism notifies the initiator of the change about the results. Writing the result into the CRE is another change event in the artifact storage, which can be handled by further mechanisms for additional analysis.
The computation of consistency information can be expanded to changes stored within a PWA. In practice, this means that certain changes in a PWA potentially trigger a consistency rule re-evaluation. Within this re-evaluation, the change is considered on top of whatever information is available in the PA. A new consistency checking result is computed and stored as a change in the PWA that triggered the re-evaluation. This effectively means that engineers can check their changes’ consistency with publicly available artifacts from the isolated perspective of a PWA. This has the major advantage that consistency information, necessary for the merging process of engineering artifacts, is available to engineers before the merging process is started. Furthermore, the consistency information is re-evaluated on every change and therefore always immediately available. An exemplary demonstration of consistency checking in the CEE can be seen in the supplementary material^4.
V. DISTRIBUTION OF CHANGE INFORMATION
Expanding global consistency checking to hierarchies of PWAs requires additional coordination in case of a commit. When an artifact is committed to a parent work area (PWA or PA), the consistency information in multiple child PWAs potentially becomes outdated. Our mechanism secures that consistency information is kept up-to-date at all times and that committed changes lead to according re-evaluations of affected PWAs. This requires special consideration of the commit procedure, respectively the distribution of change information, upon which certain re-evaluations must be triggered. As the core aspect of our mechanism, we discuss this commit procedure in the following.
A. Setup
Consistency information is stored next to regular artifact changes (in the form of CREs and CRDs). Therefore, a commit also transfers the PWA’s consistency information into the parent work area and overwrites the respective artifact values that may already reside there. This way, consistency information can be read, stored and expanded independently from the actual artifacts it refers to. However, this comes with the requirement that the consistency information of a PWA must be completely up-to-date at commits. Otherwise incorrect results may be published and the parent’s consistency information is no longer in sync with the artifacts it refers to. In our mechanism, this requirement is secured continuously after every change registered on the parent work area. Committing does not require a preliminary consistency check between the parent and the committing PWA.
^4Consistency Checking in the CEE: https://tinyurl.com/y4pz23s
B. Committing Changes
The process of committing changes can be split into different stages:
- Issuing a commit through the tool adapter
- Collecting and removing all changes from the PWA
- Transferring the collected changes to the respective properties in the parent work area
- Distributing change information to the rest of the engineering environment
- Consistency checker and other services reacting towards change information
When engineers wish to publish their work in the CEE, they must transfer their changes from their PWA to its parents, respectively the PA. From the perspective of the individual engineer, this means that they must issue a "commit" command on their PWA. This can be done through the CEE’s API, respectively the tool adapters using the said API. Generally commits can be done in two ways:
- Continuously: Changes are immediately committed to the parent work area once they are synchronized with the PWA. When changes are continuously checked out as well, this allows for live collaboration between tools that normally do not support such a workflow.
- Periodically: Changes are published in intervals. This way of committing the PWA is similar to traditional version control systems. While continuous commits are an automated process, periodic commits can happen manually.
How commits are issued within a tool is dependent on the implementation of the respective tool adapter.
When the tool adapter receives a "commit" command, it forwards the command to the CEE. The latest changes stored in the connected PWA must now be transferred to the parent work area. There, the cloud automatically appends every change to its corresponding property. In case of the PA, these changes eventually form a fine-grained change history for artifacts, respectively their properties.
Since both the PA and the hierarchy of PWAs form an engineer’s perspective on the artifact storage, new changes in a PWA’s parents require a re-evaluation within the PWA to keep this perspective’s consistency information correct.
The goal of our mechanism is to keep all consistency information in the CEE up-to-date at all times. If a commit happens, the committed consistency information must naturally be up-to-date as well. For this, we continuously re-evaluate a PWA’s consistency information, whenever a) something in the PWA changes (e.g., a tool synchronizes a change), or b) something in the PWA’s parent changes. A change in the parent can only happen whenever a commit is issued by a child PWA or a service modifies the contents of the parent. The consistency information of other child PWAs can then become out-dated. This can happen in the following scenarios SC1-7 (supporting illustrations for the scenarios can be found in the supplementary material available online):
- SC1 – Committed CRD creation: If a commit adds a new CRD to a parent work area, all child PWAs carrying changes on potential CEs are now outdated. Any artifact that "turns" into a CE is consistency-relevant and must always be accompanied by a corresponding CRE result. Therefore, when a new CRD is committed into the parent, such a CRE result must be added in the affected children. If the CE already existed in the parent before the commit, the corresponding CRE was created and committed together with the CRD. If the CE only exists within the child PWA, the corresponding CRE must be created in the said PWA.
- SC2 – Committed CE creation: If a regular artifact is committed to a parent work area, this artifact is not consistency-relevant. However, if a child PWA contains an uncommitted CRD referring to the type of this artifact, the consistency information of the respective child PWA is now incomplete. From the perspective of the child PWA, there is an artifact that requires a CRE. The corresponding CRE must be created in the child PWA to be committed with the CRD later (leading to SC 1).
- SC3 – Committed Scope Element creation: When a child PWA contains a CRE referencing a set of scope elements and the said set is manipulated in the parent, naturally the consistency result of the CRE is outdated. Subsequently, every newly committed scope element must trigger a re-evaluation of the corresponding CREs.
- SC4 – Committed CRD update: A CRD can be updated in two ways. Either the rule is updated or the context. In the earlier case, all corresponding CREs in child PWAs must be re-evaluated. If the context is updated, our mechanism treats it like the deletion of an old and the creation of a new CRD (i.e., first SC 6, then SC 1).
- SC5 – Committed CE or Scope Element update: When a context or a scope element is updated in a parent work area during a commit, a child PWA's consistency information can become outdated. This is up to two requirements: Firstly, the PWA must contain a corresponding CRE. Secondly, the PWA must not contain changes on the same context or scope element. If the latter is the case, these changes would have already produced their own consistency results, which overrule any of the parent’s consistency information.
- SC6 – Committed CRD deletion: When a CRD is deleted within a parent work area, all corresponding CREs, residing within the parent or child PWA’s, must be deleted as well. The only exception are child PWAs containing an update on the CRD. In this case, the updated CRD overrules the deleted CRD. Within such a PWA, correspondingly updated CREs are already present. None of these CREs are deleted.
- SC7 – Committed CE or Scope Element deletion: If a CE or a scope element is deleted in a parent work area during a commit, a child PWA’s consistency information is potentially outdated. For this to happen, the PWA must contain a CRE referring to either the scope or the CE.
5Supporting illustrations: https://tinyurl.com/y93lo8bk
this is the case, the corresponding CRE must be deleted (after CE deletion) or re-evaluated (after scope element deletion). The child PWA must not contain a change on the deleted scope or CE. Otherwise, its changes overrule the parent’s deletion.
To consider these scenarios, our mechanism makes use of a commit event fired after changes are appended in a work area. This commit event contains all transferred change information and is distributed to all child PWAs, except the one from which the commit originated. From the perspective of these PWAs the consistency checking mechanism can now interpret the distributed change information and act accordingly. From the scenarios above, we derive a set of post-conditions (P1-3), which must be fulfilled by the consistency checker:
- **P1**: At all times a CRD must be accompanied by all its corresponding CREs (i.e., all CREs must always exist in the same work area as the CRD). If a CRD is newly created in a PWA, this work area must also contain all CREs of CEs in its parents. This must be the case because these CEs are part of the PWA’s perspective on the artifact storage. Without the CREs the consistency information of the PWA would be incomplete. Naturally, when a CRD is committed, its CREs are committed alongside.
- **P2**: A CE must always be accompanied by its corresponding CREs. The exception are CEs that are not yet CEs from the perspective of the work area they are in. When a CE is part of a parent work area, but the CRD is in a child PWA, the corresponding CRE would reside in the said PWA. From the perspective of this PWA the potential CE is already treated as such. The CE only “publicly” becomes a CE once the CRD is committed, after which it is immediately accompanied by the corresponding CRE.
- **P3**: A CRD, as well as a CE, must always be retrievable from the work area in which a corresponding CRE exists. If there is a CRE in a child PWA (e.g., because of a changed scope element), the corresponding CE and CRD, must either reside in the same PWA, or in its hierarchy of parents.
With these post-conditions defined, our consistency checking mechanism can check all changes from the perspective of PWAs. Doing so, the mechanism filters consistency-relevant change information on a PWA basis, i.e., only if a change is actually relevant to the consistency information within the work area, the respective CREs are created or re-evaluated. This selective approach is done to avoid a full re-evaluation of all work areas after every commit. A depiction of the resulting algorithm can be seen in Listing 1.
```
switch(change, ChangeType)
case CREATE:
if (CRD is created)
foreach (CE in perspective)
if (corresponding CRE is NOT element of perspective)
create CRE for CE
else
retrieve CRE for CE
elseif (CE is created)
foreach (context—corresponding CRD in perspective)
if (corresponding CRE is NOT element of
```
Listing 1. Algorithm on the basis of which the consistency checking mechanism handles change information from the perspective of a PWA.
Since this algorithm is generally applicable to changes being observed from a certain PWA’s perspective, it is also valid for a regular change synchronization from a tool adapter (PWA changes). In other words, this algorithm can entirely replace the legacy event handling that was originally used in the CEE.
VI. EVALUATION
The evaluation of our mechanism is split into an experimental and a practical part. For the experimental part, we conducted an empirical study to illustrate the importance of the presented problems and to highlight the necessity for an automated solution. For the practical part, we checked an implementation of our mechanism against an exhaustive set of simulated input scenarios. These scenarios automatically test possible situations in which our mechanism must react. The results are checked against a pre-defined post-condition.
A. Empirical Case Study
In order to demonstrate the applicability of our mechanism and to underline the relevance of the addressed issue, we conducted an empirical study on the impact of instant inconsistency feedback during the engineering process [13]. The study was conducted with 36 bachelor-level computer science students at an mean age of 23.7 years. The average programming experience was two years. All subjects were familiar with Java and UML (one or more years of experience). The results from these subjects could be generalized for junior engineers. The subjects were given ten tasks each. The tasks were focused on the co-changing of code and UML models within two non-trivial systems. The first system was...
an open source game named “Matador”, featuring roughly 6000 lines of code across 37 Java classes. The code was documented by six UML diagrams with 661 model elements. The second system was a proprietary calendar application named “Calendarium”, featuring roughly 21000 lines of code across 150 Java classes. These were documented in 12 UML diagrams with 2843 model elements. The systems were chosen due to their size and the availability of both models and code. The goal was to reach a consistent state between UML models and code after certain changes were performed on one or the other. The results were graded as “correct” (all required changes were performed), “partially correct” (at least half of the required changes were performed) or “incorrect” (less than half of the required changes were performed). One half of the given task descriptions provided consistency-relevant change information, while the other one did not. We found that, given the change information, subjects were much more likely to solve their individual tasks correctly. The improvement of correctness in tasks with consistency information over those without was at a factor of 2.68 (see Table I - note that the discrepancy between the total amounts of tasks was the result of an odd number of tasks finished by the participants). This means that the success rate of solving tasks was more than twice as high than without consistency information. Furthermore, the amount of incorrect solutions was 51.5 percent lower when consistency information was present. There was no significant difference in partially correct solutions. This study gives us confidence that the instant distribution of consistency-relevant change information can drastically improve the engineering process and lower the risk of costly errors. It is therefore reasonable to assume that engineers can benefit greatly from our proposed mechanism.
**B. Exhaustive Scenario Simulation**
To validate the correctness of our mechanism – respectively the subsequent propagation of consistency information – we exhaustively simulate possible input scenarios that manipulate the artifact storage of the CEE. The results of these scenarios are counter-checked against a post-condition (as defined in Section V), which secures the correctness of the outcome. The evaluation is conducted on a CEE implementation with the features presented in Section IV.
1) **Procedure:** For this evaluation, we define an input scenario as a combination of valid input sequences a user can perform. These sequences are limited in the following ways:
- The user interface determines which inputs a user can enter. The possible inputs are a commit, the creation of an artifact, the modification of a property and the removal of an artifact (where removal is just a further modification of the “alive” property of an artifact).
- Certain inputs require specific preceding inputs. For example, an artifact can only be updated after creation. This leaves us with a set of rules that is determinant of valid input sequences.
- The consistency checking mechanism only reacts towards changes in consistency checking relevant artifacts – inputs irrelevant to consistency checking can be ignored.
- The propagation of consistency information is always handled in pairs of work areas, that is one child and one parent work area. If a parent has multiple children, propagation is handled for each child individually (i.e., again on the basis of one child and one parent).
The resulting input sequences are overlapping (e.g., sequence A creates an artifact while sequence B creates an artifact and then modifies it) and can be summarized in a graph structure. Such a graph can be traversed exhaustively. Each step (in combination with previous steps) of the traversal then represents a valid sequence of user inputs. These input sequences can be combined, exhausting all possible input sequences, respectively input scenarios. The limitations for input sequences, the generation of the graph as well as its traversal are discussed as following.
2) **Limitations:** To narrow down the amount of potential input sequences, this evaluation only considers user-manipulated artifact types relevant to the consistency checking mechanism. Such types are CRDs, CEs and Scope Elements. These artifacts can either be created, modified or committed, thus narrowing down the amount of potential input sequences further. It is important to note here that our evaluation considers the modification and the removal of an artifact equivalently.
Further, sequences of inputs underlie certain rules. They define which inputs must precede other inputs, so the sequence is valid. Two rules are critical in this regard. Firstly, the modification of an artifact is always preceded by the creation of the said artifact. Secondly, an artifact must be committed to be modified by a parent work area. Subsequently, the creation of a CRD must always precede its modification. The same is true for the CEs and Scope Elements. A valid input sequence could therefore look like the following:
\{Create: CE (child); Commit (child); Modify: CE (parent);\}
Given that a CRD exists, the mechanism must react with the creation of a CRE once the CE is created in the child work area. After committing, both CE and CRE are transferred to the parent work area. The modification of the CE must then again produce a CRE re-evaluation from the perspective of the parent work area. The result is then stored as a change on the previously committed CRE.
3) **Graph Building and Traversal:** With the limitations and rules for inputs defined, we can build a graph of valid input sequences. The input sequence from above could originate
<table>
<thead>
<tr>
<th>Correctness</th>
<th>Information</th>
<th>No Information</th>
<th>Performance</th>
</tr>
</thead>
<tbody>
<tr>
<td>Correct</td>
<td>59 (41.84%)</td>
<td>22 (15.71%)</td>
<td>268%</td>
</tr>
<tr>
<td>Partially Correct</td>
<td>49 (34.75%)</td>
<td>50 (35.71%)</td>
<td>0%</td>
</tr>
<tr>
<td>Incorrect</td>
<td>33 (23.4%)</td>
<td>68 (48.57%)</td>
<td>-51.5%</td>
</tr>
<tr>
<td>Tasks</td>
<td>141 (100%)</td>
<td>140 (100%)</td>
<td></td>
</tr>
</tbody>
</table>
from a graph structure as depicted in Figure 4. The nodes and edges in orange represent the exemplary input sequence. Note that every consecutive step of this sequence can also represent its own valid input sequence. Further, note that this graph structure is only a small example. A full graph considers all possible children for every individual node, leading into their own valid sequences. This means, “Create:CE” could be followed up by “Modify:CE” and then “Commit”. Such a sequence would be represented in its own sub-graph, branching off “Create:CE”. This is done to avoid a cyclic graph structure. Repetitions of the same node are not necessary since only the position of a node in the input sequence makes a difference for the consistency checking mechanism. Variations of these positions are already exhaustively covered by the combined input sequences.
4) Input Scenario Extraction and Combination: With a full graph structure built, we traverse the graph and extract every consecutive step in the traversal as its own valid input sequence. All combinations of different input sequences give us all input scenarios under the given limitations.
C. Counter-checking and Results
The input scenarios can now be executed automatically by sequentially forwarding every input of each scenario to the CEE. After every input we counter-check the state of the artifact storage against a post-condition. This tells us whether the consistency information, created through various inputs, is propagated correctly throughout the CEE. In total, we produce 2994 input scenarios. The end state of all these input scenarios satisfies the defined post-condition.
D. Threat to Validity
A scenario simulation may not pose a real-world utilization of our mechanism. However, in an exhaustive scenario simulation real-world input scenarios merely represent a subset of all scenarios. An exhaustive simulation poses as a holistic evaluation of the functionality of our mechanism and includes all input scenarios a regular user could perform. This is due to the fact that the set of possible inputs is determined by a limited interface. The combination of the inputs in a graph and its full traversal therefore results in a full coverage of potential user actions. We can, therefore, state that an exhaustive scenario simulation evaluates the correctness of our work in a representative way.
VII. RELATED WORK
Collaborative engineering approaches: Various works have been conducted in the field of collaborative engineering (e.g., [4], [8]–[11], [15], [17], [25]). The literature review of Bruneliet et al. [1] focuses on approaches that concern themselves with the unification, presentation and manipulation of different models within a singular environment.
Similar to the one presented in this paper, other works discuss the type structure of their underlying artifact basis (in the sense, whether meta-models can be unified within a single view), the management of consistency at run-time, and the possibilities to manipulate the artifact basis. Most notably EMF Views [2] Kitalpha [16], Model Join [3], and Viatra [6] share similarity with our work, since they all consider multiple meta-models (or engineering artifact types) within a single view, while giving the possibility to augment the model- respectively artifact-basis with enhancing information. Out of these approaches, only Viatra considers an incremental re-computation of consistency as our work does. For this, the Viatra framework performs model queries and the respective re-evaluations on a change basis. However, the framework does not natively implement additional infrastructure for a cloud execution of its features. As a result, the multi-user aspect of our work is not given within Viatra. An instant distribution of change information would therefore have to be handled in a different way, for example a separate infrastructure. Similar disparities can be identified with the Vitruvius [14] approach and ModelJoin, which use a combination of meta-models to establish flexible views on engineering artifacts. The latter of these approaches allows the presentation of heterogeneous artifacts in a non-intrusive way, by combining legacy meta-models into a single underlying model. In our work this operation is equivalently taken over by the tool adapters and can happen during runtime.
EMF Views takes a similar approach to the integration of different engineering artifacts. In this approach, meta-models are synchronized into a viewpoint, respectively a corresponding combination of several meta-models. The synchronized artifacts can then be complemented by links, which are themselves instances of a separate weaving model, i.e., a linking meta-model. Our work can equivalently produce links as engineering artifacts. These links are then described by corresponding artifact types. Such types can be customized at runtime. Beyond these similarities, incremental consistency checking has not been a major focus of EMF Views.
Kitalpha is a framework focused on system architecture and the creation of workbenches for Model-Based Engineering. Subsequently, the presentation of heterogeneous engineering artifacts plays a major role in this framework. Bridges between workbenches enable the bidirectional exchange of information. However, there is little focus on incremental consistency checks and the distribution of computed information towards stakeholders using workbenches.
An approach with stronger focus on collaboration is developed by Obeo\(^6\). This includes the Sirius project\(^7\) as well as commercial extensions built on top of it. These solutions offer the integration of engineering artifacts from both native and custom tools. Collaborative editing as well as conflict management between different engineering artifacts are all considered aspects of the Sirius project. However, it is largely built on an eclipse basis. This adds an additional layer of complexity with regards to the integration of custom tools in the collaboration environment.
Further, both Herzig et al. [12] and Vangheluwe [24] have focused on the unified representation of heterogeneous engineering artifacts. Both approaches rely on the application of directed graphs. These graphs represent artifacts through a triple consisting of an object, an attribute and a value. This is similar to our own work, where artifacts would be equivalent to objects, properties to attributes. Values would be expressed through references between artifacts. The direction of edges in a graph could be realized through link artifacts with corresponding properties. This also illustrates the versatility of a mapping based structure, as additional meta-information can be appended to regular engineering artifacts.
In their work Dávid et al. [5] explore the management of inconsistencies in virtual products by process enactment (execution and monitoring of processes) and tool interoperability. This work focuses less on the distinction between the private perspective of a stakeholder onto the end product and the public representation thereof. The distribution of consistency-relevant change information among stakeholders is only discussed very briefly.
Further research conducted by Egyed et al. [7] propose a unification of artifacts in a cloud environment for the purpose of analysis and manipulation. One such form of analysis is incremental consistency checking, which is studied in the context of an industrial experiment. However, these works do not further explore the intricacies of distributing change information and reacting accordingly from the perspective of individual work areas.
**Version control tools:** The concepts discussed in this work depend on the capabilities of the CEE. However, it should be noted, that any of these concepts can be transferred to other version-control tools, given that the respective APIs allow the implementation of the required plugins. Going by the example of Git, the branch of a repository contains the changes of one or many developers. This can be treated as an equivalent to the PWA and consistency checking can be performed on it globally, as long as the branch is a full representation of all artifacts in a project. However, this is not the case usually. This is due to the fact, that Git normally does not store heterogeneous engineering artifacts. It is mostly made for text-based artifacts such as code or XML files. This also has an effect on the applied mechanism when a branch is merged back into the master branch. Git applies a line-based merging mechanism, which sometimes requires manual corrections, while the CEE applies a property-based merging mechanism, where the last committed change is always the valid one. In principle these differences are not in conflict with the presented concepts on the distribution of consistency information. If one were to implement the presented concepts in Git, it would be possible and the described scenarios would still apply. When an artifact is added to the Git branch (e.g., in the form of a class file) it is treated as a CE, which requires the creation of a CRE within the branch (e.g., as an entry in a CRE file). If a CRD is added, CREs for all CEs are required, etc. The implementation would be different; however, the concepts stay the same. This makes our work not only applicable to a CEE, but also to various repository-based artifact storages.
**VIII. Conclusion**
In this work, we illustrate the problematic nature of collaborative engineering. We discuss issues arising with a lack of incremental consistency checking mechanisms and how delayed consistency checking information may lead to extensive refactoring phases. As a solution, we present how consistency checking can be realized within a CEE. We discuss a way of keeping consistency information up-to-date with the latest published state of engineering artifacts. The instant distribution of consistency information plays a critical role in this problem area. This is especially true when engineers commit changed engineering artifacts to a public repository, while concurrently modifying its contents in a hierarchy of private work areas. We illustrate different scenarios, which lead to out-of-date consistency information and present a way of circumventing this problem. In our proposed mechanism, a set of post-conditions must be fulfilled for every work area within the CEE after every commit. These post-conditions are realized within a presented algorithmic solution. We demonstrate the efficacy of our work with an experimental study and evaluate its correctness on the basis of exhaustively generated test scenarios. The paper is concluded after a discussion on related approaches. For future work, we would like to check consistency within groups of work areas, independently from any work area hierarchy. To achieve this, we plan to expand the data gathering mechanism of the CEE’s consistency checker.
**References**
---
\(^6\)Obeo: https://www.obeo.fr/en
\(^7\)Sirius: https://www.eclipse.org/sirius
|
{"Source-Url": "https://epub.jku.at/obvulioa/download/pdf/5907339?originalFilename=true", "len_cl100k_base": 10260, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35524, "total-output-tokens": 12555, "length": "2e13", "weborganizer": {"__label__adult": 0.0002853870391845703, "__label__art_design": 0.0007901191711425781, "__label__crime_law": 0.00026416778564453125, "__label__education_jobs": 0.002292633056640625, "__label__entertainment": 7.82012939453125e-05, "__label__fashion_beauty": 0.0001627206802368164, "__label__finance_business": 0.00028133392333984375, "__label__food_dining": 0.0003046989440917969, "__label__games": 0.0006265640258789062, "__label__hardware": 0.000903606414794922, "__label__health": 0.0003871917724609375, "__label__history": 0.00033926963806152344, "__label__home_hobbies": 0.00015604496002197266, "__label__industrial": 0.0005693435668945312, "__label__literature": 0.0003018379211425781, "__label__politics": 0.00017213821411132812, "__label__religion": 0.0004673004150390625, "__label__science_tech": 0.060577392578125, "__label__social_life": 0.00014972686767578125, "__label__software": 0.01493072509765625, "__label__software_dev": 0.9150390625, "__label__sports_fitness": 0.0002722740173339844, "__label__transportation": 0.0005059242248535156, "__label__travel": 0.00021326541900634768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57570, 0.01674]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57570, 0.63113]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57570, 0.92741]], "google_gemma-3-12b-it_contains_pii": [[0, 5232, false], [5232, 11611, null], [11611, 13734, null], [13734, 18829, null], [18829, 24684, null], [24684, 30469, null], [30469, 35157, null], [35157, 41247, null], [41247, 46702, null], [46702, 53337, null], [53337, 57570, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5232, true], [5232, 11611, null], [11611, 13734, null], [13734, 18829, null], [18829, 24684, null], [24684, 30469, null], [30469, 35157, null], [35157, 41247, null], [41247, 46702, null], [46702, 53337, null], [53337, 57570, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57570, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57570, null]], "pdf_page_numbers": [[0, 5232, 1], [5232, 11611, 2], [11611, 13734, 3], [13734, 18829, 4], [18829, 24684, 5], [24684, 30469, 6], [30469, 35157, 7], [35157, 41247, 8], [41247, 46702, 9], [46702, 53337, 10], [53337, 57570, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57570, 0.03109]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
d8471b62071d9b8199702ddf7b4940001c3bbbb6
|
Using Macros to Compute US Health Insurance Coverage Estimates for Insertion into a Web-based Table Generator
Michele Burlew, Episystems, Inc.
Peter Graven, Karen Turner, & Michel Boudreaux, University of Minnesota, Minneapolis, MN
ABSTRACT
SAS® macro programs were developed to estimate health insurance coverage in the US population annually based on responses to two federal surveys and to format the results for loading into the SHADAC (State Health Access Data Assistance Center) Data Center. The SHADAC Data Center is a web-based table generator tool. (www.shadac.org/datacenter) The macro programs prepare data for analysis using the DATA step and base SAS procedures, analyze the data with PROC SURVEYMEANS, combine ODS output data sets from PROC SURVEYMEANS, and create CSV files that are loaded into the web-based system.
The SHADAC Data Center provides a way for health policy analysts to create customized tables and graphs of health insurance coverage estimates within a pre-defined set of parameters. The coverage estimates are derived from statistical analyses of the US Current Population Survey’s Annual Social and Economic Supplement (CPS) and from the American Community Survey (ACS). These surveys are released annually in the fall.
The CPS analysis data set for one year contains approximately 200,000 observations. The ACS analysis data set for one year contains approximately 3 million observations. Both surveys are weighted to the population of the US. The SHADAC Data Center currently contains estimates for each year of CPS data from 1987 to 2009 and for ACS data from 2008 and 2009.
For each year and survey, macro programs code twenty-two classifications of the data such as age group, marital status, gender, and family income. The combinations of classifications generate almost 400 models for PROC SURVEYMEANS to analyze. Each model is processed nationally and by state.
On a PC with 4G of RAM using SAS 9.2, the 400 analyses for one year of the CPS data take approximately three hours, and the 400 analyses for one year of the ACS data take approximately 240 hours. Newly available to us is a Linux-based system that has SAS 9.2 where our testing shows that the ACS processing takes about one-third of the time that it does on a PC.
Several design considerations guided the development of the SHADAC Data Center SAS macros that can be applied when developing other similar applications. Writing code in a modular style and with the expectation that variable names and values will change over time make it easier to update code when changes in the data sources occur. When analyses generated by the macros take many hours to complete, defining macros that execute with minimal user intervention is necessary. Modifying code in steps of increasing complexity as output is verified and experience is gained ensures that the processing produces the required output. Saving all log and procedure output documents the processing for later review and archival purposes.
INTRODUCTION
The University of Minnesota's State Health Access Data Assistance Center (SHADAC) is funded by The Robert Wood Johnson Foundation to help states monitor rates of health insurance coverage, to understand factors associated with access to care, and to utilize data for implementation of health reform. SHADAC maintains an ongoing research agenda related to issues of health insurance coverage and access to care, data collection methods, and state health policy.
SHADAC began an effort in 2009 to build a data center where researchers and policy analysts could obtain tables and graphs of US and state health insurance coverage estimates from an online web-based table generator. The health insurance estimates are derived from two annual federal surveys. One survey is the US Current Population Survey’s Annual Social and Economic Supplement (CPS). The CPS is administered as a joint effort of the Bureau of Labor Statistics (BLS) and the Census Bureau. The second survey is the American Community Survey (ACS), and the Census Bureau administers the ACS.
Both surveys randomly select respondents in the United States. The surveys obtain information about households, families, and persons. The survey questions cover many topics including demographics, income, education, and health insurance coverage. Analysts at BLS and the Census Bureau weight the surveys so that the responses reflect the US population as a whole.
The CPS has annual health insurance data from 1988 forward while the ACS has annual health insurance data from 2008 forward. Both surveys release their data in the fall. Each survey’s federal web site has extensive tables and reports on various analyses of the data. The web sites also make the data and codebooks available by download so
that analysts can conduct their own studies. The CPS data released fall 2010 was obtained from surveys made in March 2010. The ACS data released fall 2010 was obtained in 2009.
The goal of the initial release of the Data Center in fall 2009 was to provide health insurance coverage estimates for each year of the CPS (starting in 1988), and for each year of the ACS (starting in 2008). Additionally, SHADAC combined the CPS annual results to calculate two-year and three-year estimates. In fall 2011, the ACS plans to release a three-year file with responses combined from 2008, 2009, and 2010.
An important goal is to analyze the CPS and the ACS data as quickly as possible after the data and codebooks are released. Therefore, if SHADAC staff define new classifications since the previous year’s release, these new classifications should be fully evaluated and the previous data releases completely re-analyzed before the fall release so that they can be incorporated in the upcoming fall release.
The SHADAC Data Center estimates up to nine different health insurance coverage types. Health insurance can be provided by public and private entities and some people have insurance from more than one source. The two surveys determine whether or not a person is covered by one or more sources. If a person is covered, the surveys determine whether the person’s coverage is public, private, or a combination of the two. The surveys also determine the general types of public and private coverage that the respondent has.
The surveys employ different sampling strategies and measurement designs and therefore their health insurance estimates differ. By providing data from both surveys, SHADAC gives Data Center users the opportunity to compare results from both surveys and to work with data most appropriate to their needs.
Over 2,300 unique users have accessed the SHADAC Data Center since its start. The report “Cover Michigan. The State of Health Care Coverage in Michigan” produced by the Center for Healthcare Research and Transformation is an example of a document that was prepared using estimates from the Data Center.
The screenshots in Appendix 1 show the general layout of the online table generator.
DATA SOURCES
The records in each annual CPS data file are classified hierarchically into three different record types: household, family, and person. The CPS assigns household IDs, family IDs, and person IDs. These IDs link records across record types.
The ACS survey also has a hierarchical structure. It is released in two files; one file contains household information and the other file contains person-level information. As with the CPS survey, IDs link data across record types. SHADAC researchers add variables that define families within households.
Both surveys can have multiple families per household and multiple persons per family. A household can fit the common definition of a dwelling where one or more families reside. A household can also be just one individual who lives in an institution or group quarters like dormitories or barracks.
The 2009 CPS data file has about 400,000 records with data from about 97,000 households, 89,000 families, and 210,000 persons. Surveys from years prior to 2009 have similar numbers of records. With each CPS release, SHADAC researchers combine information from the different record types to create an analysis file that is at the person-level. Variables from the linked household and family records are added to the person records. The CPS analysis data set then has about 200,000 observations per year and it is at the person-level of the hierarchy.
The ACS survey in 2009 contained about 1 million records in the household file and 3 million records in the person-level file. As with each release of the CPS survey, SHADAC researchers combine the two ACS files so that the ACS analysis data set is at the person-level. Household and family variables are added to the person-level records. The ACS analysis data set has about 3 million observations.
STATISTICAL ANALYSES NEEDED
The SAS SURVEYMEANS procedure computes the frequencies, percentages, and standard errors of the health insurance estimates. Because of the features of the SAS programming language, it was decided to develop the processing in SAS using a combination of procedures, DATA steps, macro programs, and ODS output data sets.
In order to produce a consistent time-series, SHADAC staff produced a new set of weights for the CPS for each year and harmonized responses across questionnaire changes using imputation. Health insurance coverage estimates based on the original data as released by the federal government and based on the data with the SHADAC enhancements are available through the SHADAC Data Center. Further discussion of the enhanced weights is beyond the scope of this paper and information about them can be found on the SHADAC web site.
VARIABLE CONSTRUCTION
The goal of the SHADAC Data Center is to provide health insurance estimates for different descriptive characteristics and combinations of characteristics in the US population. The variables that characterize the surveys were organized
into two groups. The first group of classification variables, the “filter variables”, provides Data Center users estimates based on subsets of the data. For example, a user may want to look at health insurance coverage in children only and not have the standard errors and percentages based on the population as a whole. The second group, the “row variables” provides detail within the population defined by the combination of filter variable values.
Some of the analyses were repeated. For example, the three age filter variables all have the same category of people 65 and older. Because of the requirements of the statistical analyses, it is not possible to omit the repeated analyses.
Table 1 lists the five filter variables as of the fall 2010 processing. The CPS and the ACS have the same set of filter variables. The acronyms were used to name the output data sets created by PROC SURVEYMEANS.
Table 1. SHADAC Data Center Filter Variables
<table>
<thead>
<tr>
<th>Measurement</th>
<th>Variable Name</th>
<th>Acronym</th>
<th>Number of Values: Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Age</td>
<td>AGEGRP2A</td>
<td>a2a</td>
<td>2: <65, 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEGRP3A</td>
<td>a3a</td>
<td>3: 0-17, 18-64, 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEGRP3B</td>
<td>a3b</td>
<td>3: 0-18, 19-64, 65+</td>
</tr>
<tr>
<td>Poverty Level Percentage</td>
<td>FPL2CATA</td>
<td>p2a</td>
<td>2: 0~<200, 200+</td>
</tr>
<tr>
<td>Poverty Level Percentage</td>
<td>FPL2CATB</td>
<td>p2b</td>
<td>2: 0~<139, 139+</td>
</tr>
</tbody>
</table>
Table 2 lists the row variables as of fall 2010. The HEALTHSTAT variable is unique to the CPS and it was first recorded in 1995. The CITIZENSHIP variable is unique to the ACS. The acronyms are used to name the output data sets created by PROC SURVEYMEANS.
Table 2. SHADAC Data Center Row Variables
<table>
<thead>
<tr>
<th>Measurement</th>
<th>Variable Name</th>
<th>Acronym</th>
<th>Number of Values: Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>Age</td>
<td>AGEROW2A</td>
<td>ar2a</td>
<td>2: <65, 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEROW3A</td>
<td>ar3a</td>
<td>3: 0-17; 18-64; 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEROW3B</td>
<td>ar3b</td>
<td>3: 0-18; 19-64; 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEROW8A</td>
<td>ar8a</td>
<td>8: 0-5; 6-17; 18-24; 25-34; 35-44; 45-54; 55-64, 65+</td>
</tr>
<tr>
<td>Age</td>
<td>AGEROW8B</td>
<td>ar8b</td>
<td>8: 0-5; 6-18; 19-24; 25-34; 35-44; 45-54; 55-64, 65+</td>
</tr>
<tr>
<td>Poverty level percentage</td>
<td>FPL4ROWCATA</td>
<td>pr4a</td>
<td>2: 0~<139; 139+</td>
</tr>
<tr>
<td>Race and ethnicity</td>
<td>RACE</td>
<td>r</td>
<td>5: Hispanic; White, non-Hispanic; Black, non-Hispanic; Asian; Multiple, non-Hispanic</td>
</tr>
<tr>
<td>Family income</td>
<td>FTOTCAT</td>
<td>i</td>
<td>4: $0-$24,999; $25,000-$49,999; $50,000-$74,999; $75,000+</td>
</tr>
<tr>
<td>Gender</td>
<td>SEX</td>
<td>s</td>
<td>2: Male; Female</td>
</tr>
<tr>
<td>Marital status of the individual who is 18 years of age or older</td>
<td>MARRIED</td>
<td>ms</td>
<td>2: Married; Not Married</td>
</tr>
<tr>
<td>Marital status of the family or household of the individual</td>
<td>FMAR</td>
<td>mf</td>
<td>2: Married; Not Married</td>
</tr>
<tr>
<td>Marital status and children under 18 in the family or household of the individual</td>
<td>MARWCHILD</td>
<td>cf</td>
<td>4: Married with children < 18; Married, without children < 18; Not married, with children < 18; Not married, without children < 18</td>
</tr>
<tr>
<td>Work status of the individual who is 18 years of age or older</td>
<td>WORKPRYRFT</td>
<td>ws</td>
<td>3: Not working; Part-time; Full-time</td>
</tr>
<tr>
<td>Work status of the family or household of the individual</td>
<td>FWORKPRYR</td>
<td>wf</td>
<td>3: None working; At least one part-time worker; At least one full-time worker</td>
</tr>
<tr>
<td>Education status of the individual who is 18 years of age or older</td>
<td>EDUCCAT</td>
<td>es</td>
<td>4: < High school; High-school; Some college; College or more</td>
</tr>
<tr>
<td>Highest education level in the family or household of the individual</td>
<td>FEDUCMAX</td>
<td>ef</td>
<td>4: < High school; High-school; Some college; College or more</td>
</tr>
<tr>
<td>Health Status (CPS only, starting in 1995)</td>
<td>HEALTHSTAT</td>
<td>h</td>
<td>2: Good/Very Good/Excellent; Poor/Very Poor</td>
</tr>
<tr>
<td>Citizenship (ACS only)</td>
<td>CITIZENSHIP</td>
<td>cz</td>
<td>2: Citizen; Non-citizen</td>
</tr>
</tbody>
</table>
The CPS also requires auxiliary data sources. One of these external sources is a poverty level lookup reference data set that identifies the poverty level for each year of the CPS based on ages and family size in the household. The other data sources needed by the CPS analyses are files of the revised weights that had been derived by SHADAC.
These revised weights provide an alternative to the weights that were supplied by the original release of the CPS. See the SHADAC Data Center web site for more information on these revised weights.
**SAS PROGRAMMING DESIGN CONSIDERATIONS**
Several design considerations guided the development of the SHADAC Data Center SAS code. The code was developed in a modular style because variable names and values can change over time. A modular style makes it easier to add and remove row and filter variables and to update the values of these variables when changes in the CPS or the ACS are made. Since the analyses take many hours to complete, and it is important to complete the analyses as quickly as possible, it was necessary to write the code so that it would execute with minimal intervention. Parameters to the macro programs were defined that kept these factors in mind. Because the Data Center would be widely available to researchers, saving all log and procedure output was necessary to document the processing.
Three major processing steps were identified for each year and survey type:
1. Prepare models and submit them to PROC SURVEYMEANS. Produce one ODS output data set from each call to PROC SURVEYMEANS.
2. Combine all the output data sets from PROC SURVEYMEANS and post-process the data.
3. Create a CSV file from the output data set created in Step 2 in a form that the vendor can load into the web-based system.
After determining these three major processing steps, code was developed separately for each step. Because of the large number of output files, folder structures reflected these three steps. Acronyms and filename standards were devised that identified the models, output data sets, and contents of logs and output files.
**IDENTIFYING THE MODELS FOR SURVEYMEANS ANALYSES**
After determining the set of filter variables and the set of row variables, the valid analyses that combine these variables were identified. Four different classes of models were defined and the number of models that needed to be constructed was determined. Each unique model is submitted twice: once to analyze the entire US population and once to analyze each state using a BY STATE statement. The BY STATE analyses analyze the fifty states and the District of Columbia.
Table 3 lists the four classes of models and the number of models constructed and analyzed. The model acronyms are used to name the logs and output files generated during the PROC SURVEYMEANS analyses. The table shows that there are 191 unique models. Each unique model is submitted twice: once to analyze the US as a whole and second to analyze each state using BY-variable processing. Considering the US model, the fifty states and DC, the total number of models analyzed per year and survey type is almost 10,000.
Some combinations of filter variables and row variables were omitted from the processing. For example, the filter variable AGEGRP3A crossed with the row variable AGEROW3B was not analyzed because of the mismatch between the first age category definitions of the two variables. The first level in AGEGRP3A selects persons age 0-17 while the first level in AGEROW3B selects persons age 0-18. A filter on the first level in AGEGRP3A would not include 18 year olds as defined by the first level in AGEROW3B. Analyzing a model that used these two filter variables would produce an incorrect analysis.
**Table 3. SHADAC Data Center Model Categories and Types of Row Variables**
<table>
<thead>
<tr>
<th>Model Category</th>
<th>Acronym</th>
<th>Number of Unique Models Constructed</th>
<th>Total Models Analyzed Nationally and By State</th>
</tr>
</thead>
<tbody>
<tr>
<td>Overall</td>
<td>all</td>
<td>1</td>
<td>52</td>
</tr>
<tr>
<td>Row Variables</td>
<td>r</td>
<td>17</td>
<td>884</td>
</tr>
<tr>
<td>Filter Variables x Row Variables</td>
<td>fr</td>
<td>81</td>
<td>4,212</td>
</tr>
<tr>
<td>Filter Variables x Filter Variables x Row Variables</td>
<td>ffr</td>
<td>92</td>
<td>4,784</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td></td>
<td>191</td>
<td>9,932</td>
</tr>
</tbody>
</table>
With 191 models to construct and nearly 10,000 models to analyze on up to nine health insurance measures for each year and survey type, and because this processing would be repeated annually with each new survey release, it was necessary to devise a system of macros that would construct the models, submit the models, organize the output, and be reusable. Additionally, the processing time for some of the models can be several hours or days because of the size of the analysis data sets and complexity of the analyses. This time-consuming effort meant that it is necessary to operate this system of macros with minimal user intervention and to have the ability to review output at a later time to discover any problems in the processing. The code saves SAS logs and output in external files for later review and for archival purposes.
Before any processing begins, it is necessary to have a reference data set available that has an entry for all valid models and a second reference data set that has all possible combinations of the values produced by the valid models. These reference data sets only had to be created when there was a structural change in any of the filter or row variable definitions.
These reference data sets are used to ensure that all the required models are analyzed. Further, the vendor who manages the online data warehouse requires that the file produced for each year and survey type that they receive have one row for every possible combination of the values from the valid models. Some of the combinations might not actually occur in the survey data so this reference data set was used as a template on which to overlay the actual results. When a combination of the filter and row variables did not exist, the reference data set supplied a row of zeroes and missing values as appropriate. An example of a combination that would not actually occur in the data, but was required to be in the file sent to the vendor is when the age filter 0-18 is selected and the row value for age is 65+.
DATA CENTER PROCESSING STEP 1
The first step prepares the data for analysis, and constructs and submits the PROC SURVEYMEANS steps.
DATA CENTER PROCESSING STEP 2
The second step combines into one data set the nearly 400 output data sets per year and survey type that PROC SURVEYMEANS generates. (The fifty states plus DC are saved in one data set because of the use of the BY STATE statement. The US population results are saved in a second data set. Therefore, there are 191*2=382 output data sets per year and survey type.) The three filter variables for age are recoded into one variable as are the two filter variables for poverty. Similarly, the five row variables for age are recoded into one variable. After these recodes are made, PROC SORT with the NODUPREC option removes identical results. As mentioned in a previous section, for statistical reasons, it is necessary to fully specify a model even if part of it had already been analyzed.
Using the NODUPREC option instead of the NODUPKEY option was a way to ensure that there were no statistical result differences in models that analyzed different variables, but had some category definitions in common.
DATA CENTER PROCESSING STEP 3
The third step processes the data set created by the second step and creates a CSV file for the vendor to load into the Data Center data warehouse. Before outputting to the CSV, code sets statistic values to missing where the unweighted count for a combination is below a specific value. A DATA step merges this revised data set with the reference data set that contains all possible combinations of the data as described above.
DETERMINING THE SAS PROGRAM STRUCTURE
A similar set of macro programs was developed to analyze each of the two data sources. Although an overlap exists in how the filter variables and row variables are defined, the structures of the CPS and the ACS data sets is different enough that it was decided that it would be easier to maintain two different sets of programs, one for each of the two data sources.
FEATURES OF THE SAS PROGRAMS IN STEP 1
The program that completes Step 1 contains several macro program definitions. One of the macro programs initiates and manages the processing. This macro program defines several named parameters so that processing requests can be customized. The first actions in this driver macro program check the validity of the macro parameter values.
Several %LET statements at the beginning of the program define global macro variables whose values are paths for input and output. These macro variables are referenced throughout the processing.
The parameters to the driver macro program include:
- the range in years to process
- whether to analyze models for the entire US and/or for each state
- a list of specific filter variables to use in the analyses
- a list of specific row variables to use in the analyses
- the types of models to execute, such as “overall” or “row only”
- the platform on which to execute the models. The two choices are a PC or a Linux-based system.
The coding of the filter variables and row variables was done in a modular fashion with usually one macro program per variable. Variable names and variable values as assigned by the surveys tend to be the same over time. However, since these items might not remain consistent, the recoding macro programs started with statements that assigned data set variable names to macro variables. These macro variable names were then resolved in SAS language statements. The macro programs also might contain macro language statements to control processing based on the year of the survey.
An example of a recoding macro follows in Figure 1. Macro program SEX_RECODE codes the row variable SEX in the CPS. (Variable SEX_1 is needed to complete the model specification in PROC SURVEYMEANS.)
The calculations to compute the set of family variables is complex and requires several PROC and DATA steps to complete. Once the program completes coding the filter variables and row variables, table output can optionally be generated to verify the new variables.
The driver macro program then begins managing the submission of the models for analysis. One macro variable, FILTERVARS, stores the names of the variables that are specified as filter variables for the current execution of the driver macro program. Similarly, a second macro variable, ROWVARS, stores the names of the variables that are specified as row variables for the current execution. If the call to the driver macro program specifies only some of the filter and row variables, then code executes to manage the processing of these subsets of variables.
The model submission part of the driver macro program is organized by the four main categories listed in Table 3. The acronyms in Table 3 are used to name the logs and output files. There was one log file and one output file for each of the four categories of models. PROC PRINTTO directs the SAS log to an external file. Because of the volume of output, the listing destination is closed and output is sent solely to a PDF file.
The driver macro program constructs elements of the PROC SURVEYMEANS step by iterating through the names of the variables saved in macro variables FILTERVARS and ROWVARS. It skips over combinations that form invalid models. After defining several macro variables to insert into components of the PROC SURVEYMEANS step, it calls a macro program that finishes construction of the PROC SURVEYMEANS step and submits the step. Once the PROC SURVEYMEANS step and post-processing of the ODS output data set finish, control returns to the driver macro program to prepare the next submission to PROC SURVEYMEANS.
When the analyses for each model type finishes, PROC PRINTTO closes the log file and ODS closes the PDF output file associated with the model type.
Figure 2 shows an example of a PROC SURVEYMEANS step that analyzes 2009 CPS data by state. This step analyzes the subpopulations in each state that are defined by the two filter variables AGEGRP3A and FPL2CATA and the one row variable AGEROW8A. Acronyms in the name of the PDF file and in the name of the ODS output data set identify the analysis.
Appendix 2 shows excerpts of macro code. The first excerpt is from the driver macro program that constructs the elements of the PROC SURVEYMEANS step and calls the macro program that executes the PROC SURVEYMEANS step and processes its ODS output data set. The second excerpt is from the macro program that constructs the statements of the PROC SURVEYMEANS call.
**Figure 2. Example of a PROC SURVEYMEANS Step**
```sas
ods pdf nobackground file="p:\data center\cps\results\2009\02 surveymeans\cps_sm_FFR_2009_20101111_abcl.pdf";
ods output domain=domainst_Fa3a_Fp2a_Rar8a;
proc surveymeans data=work.cps2009 stacking mean nobs stderr sum;
title "Processing CPS 2009";
title2 "Filter AGEGRP3A X Filter FPL2CATA X Row AGEROW8A by State Model";
by state;
domain AGEGRP3A*FPL2CATA*AGEROW8A AGEGRP3A*FPL2CATA*AGEROW8A_I;
cluster h_seq;
strata geocode;
var notcovered covered private empbased individual public medicaid medicare military;
weight marsupwt;
label AGEGRP3A= ' ' FPL2CATA= ' ' AGEROW8A= ' ';
run;
```
**FEATURES OF THE SHADAC DATA CENTER PROGRAMS IN STEP 2**
When the processing for a survey type and a year finishes, the output data sets from PROC SURVEYMEANS are combined into one data set. This step executes quickly in a few minutes. A macro program obtains the names of the
SURVEYMEANS output data sets in the folder for the survey type and year by referencing the MEMBERS dictionary table in PROC SQL. The macro program uses %DO loops to concatenate the nearly 400 data sets into one data set for the survey type and year.
Once the full data set has been created, another macro program runs checks on the contents of the full data set. A PROC COMPARE step executes that compares the models present in the full data set to those in the template reference data set. Since the reference data set contains an observation for each model that should be analyzed, the PROC COMPARE step determines if output for a model is not present in the full data set. This data checking macro program also produces a report that lists counts that reflect specific checks of the full data set.
FEATURES OF THE SHADAC DATA CENTER PROGRAMS IN STEP 3
The last major step in the SHADAC Data Center processing creates a CSV file with PROC EXPORT for each year and survey type. The vendor who manages the Data Center data warehouse expects that the CSV file have a specific structure.
Before writing out the observations, this step rounds the percentages and standard errors. When counts are below a defined value, code sets the statistics to missing. This action prevents information that could potentially identify individuals from being displayed by the Data Center. The actual data is merged with the template reference data set so that an observation is present in the CSV file for all valid combinations of the filter and row variable values for each year and survey type.
PROCESSING TIME REQUIREMENTS
On a PC with 4G of RAM using SAS 9.2, the approximately 400 calls to PROC SURVEYMEANS for a full year’s analysis took about 3 hours. As of the date of this paper, the processing for the ACS was split between the PC and a Linux-based system at the Minnesota Supercomputer Institute (MSI). The full analysis for the ACS took about 10 days of continuous processing. Newly available to SHADAC is a new Linux-based computer at MSI that has SAS 9.2 where our testing shows that the processing takes about one-third of the time.
CONCLUSION
Following the design guidelines of writing code in a modular style and developing it and testing it thoroughly in steps of increasing complexity can make it easier to write, maintain, and execute a complex system of programs. By following this path, SHADAC has been successful in achieving the goal of promptly estimating US health insurance coverage based on data from the CPS and the ACS soon after their annual survey data are released.
REFERENCES
ACS web site: http://www.census.gov/acs/www/
CPS web site: http://www.bls.gov/cps/
SHADAC Data Center web site: http://www.shadac.org/datacenter
SHADAC web site: http://www.shadac.org/
ACKNOWLEDGEMENTS
The SHADAC Data Center is funded by a grant from the Robert Wood Johnson Foundation.
Data processing to prepare the estimates for SHADAC's Data Center is conducted at the Minnesota Supercomputing Institute for Advanced Computational Research. (www.msi.umn.edu)
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. © indicates USA registration.
CONTACT INFORMATION
Your comments and questions are valued and encouraged.
For SAS code questions, contact: Michele Burlew
email: mmburlew@comcast.net
For SHADAC Data Center questions, contact: SHADAC
2221 University Ave SE
Minneapolis, MN 55414
Phone: 612-624-4802 Fax: 612-624-1493
email: shadac@umn.edu
APPENDIX 1
SCREEN SHOTS OF DATA CENTER
The following three screen shots show how SHADAC Data Center users can specify tables of health insurance estimates. These screen shots select tables of health insurance coverage estimates nationally in 2009 from the CPS for people less than 65 years of age and all poverty levels with detail by family income and by individual education level.
The first SHADAC Data Center screen presents options to select the survey type, the geography, the year, and any age or poverty filter selections.
The second SHADAC Data Center screen presents options to select the detail for the tables that contain the data specified in the first screen. One or more selections of the row variables can be made.
The third SHADAC Data Center screen shows the tables of results. The output can be saved to a CSV or PDF file.
**APPENDIX 2**
**CODE EXCERPT FROM DRIVER MACRO PROGRAM USED IN STEP 1**
This section of code processes the filter variable by row variable models. It directs the log and output to external files. It cycles through the list of filter variables (FILTERVARS) and row variables (ROWVARS) that are to be analyzed and creates macro variables to hold the elements of the PROC SURVEYMEANS step. It skips over combinations of filter and row variables that form invalid models.
This section of code calls macro program DOCPSSTATS. The next code excerpt presents some of the code from DOCPSSTATS.
```%******************************************************;
%* Do one filter variable by one row variable (doubles);
%******************************************************;
%double:
%if &dofr=NO %then %goto triple;
proc printto new
log="&dcpath\cps &cpsdataset\results\&cpsyear\02 surveymeans\
cps&cpsdataset.sm&modellevel_FR_cpsyear._%sysfunc(today()),ymmdn8.}&inits..log";
run;
ods pdf
file="&dcpath\cps &cpsdataset\results\&cpsyear\02 surveymeans\
cps&cpsdataset.sm&modellevel_FR_cpsyear._%sysfunc(today()),ymmdn8.}&inits..pdf"
style=minimal;
%let starttime=%sysfunc(datetime());
%let domainlist=;
%let domainmisslist=;
%let domainfilterlist=;
%let domainstmt=;
%let dsname=;
%let smtitle=;
%do f=1 %to &nfiltervars;
%do r=1 %to &nrowvars;
%let ffilter=%scan(&filtervars,&f);
%let rowvar=%scan(&rowvars,&r);
%if &cpsyear le 1995 and &rowvar=HEALTHSTAT %then %goto skiprowfr;
%let domainlist=&ffilter &rowvar;
%let domainmisslist=%scan(&filtermissvars,&f) %scan(&rowmissvars,&r);
%if not(&ffilter=AGEGRP3A and &rowvar # AGEROW3B AGEROW2A) and
not(&ffilter=AGEGRP3B and &rowvar # AGEROW3A AGEROW2A) %then %do;
%let domainstmt=&ffilter*&rowvar &ffilter*%scan(&rowmissvars,&r);
%let dsname=F%scan(&filtercodes,&f)_R%scan(&rowcodes,&r);
%let smtitle=Filter &ffilter X Row &rowvar;
%docpsstats
%end;
%else %put ******** Filter &ffilter X Row &rowvar skipped ********;
%skiprowfr:
%end;
%end;
%let endtime=%sysfunc(datetime());
%let duration=%sysfunc(intck(minute,&starttime,&endtime));
%put ** Started, Finished filter X row processing:
%left(%sysfunc(putn(&starttime,datetime25.)));
%left(%sysfunc(putn(&endtime,datetime25.)));
%put ** Duration &duration minutes;
proc printto;
run;
ods pdf close;
%put ** Started, Finished filter X row processing:
%left(%sysfunc(putn(&starttime,datetime25.)))
%left(%sysfunc(putn(&endtime,datetime25.)));
%put ** Duration &duration minutes;
** CODE EXCERPT FROM MACRO PROGRAM THAT CONSTRUCTS PROC SURVEYMEANS STEP **
Following is part of the code from macro program DOCPSSSTATS that the driver macro program calls when processing the CPS. Before it calls DOCPSTATS, the driver macro program defines many of the elements that go into the PROC SURVEYMEANS step. These elements include items such as:
- the year of the analyses (macro variable CPSYEAR)
- name of output data set (macro variable DSNAME)
- whether to do national and state models (macro variable BYSTATE)
- the list of variables that go on the DOMA IN statement (macro variable DOMAINSTMT).
The %DO SMLOOP loop executes once or twice depending on whether national analyses only, state analyses only, or both types of analyses were specified on the invocation of the driver macro program.
%macro docpsstats;
%if &cpsyear ge 1996 %then %do;
%let hivars=notcovered covered private empbased individual public medicaid medicare military;
%else %if &cpsyear ge 1988 and &cpsyear le 1995 %then %do;
%let hivars=notcovered covered private public medicaid medicare military;
%end;
%if &bystate=YES %then %do;
%let startloop=1;
%let smloops=2;
%end;
%else %if &bystate=NO %then %do;
%let startloop=1;
%let smloops=1;
%end;
%else %if &bystate=ONLY %then %do;
%let startloop=2;
%let smloops=2;
%end;
%* Second time through do it by states if BYSTATE=YES or ONLY;
%do smloop=&startloop %to &smloops;
%if &smloop=1 %then %let dsname=us_&dsname;
%else %if &smloop=2 %then %do;
%if %upcase(%substr(&dsname,1,2))=US %then %let dsname=st_%substr(&dsname,4);
%end;
%if %quote(&domainstmt) ne %then %do;
ods output domain=domain&dsname;
%end;
%else %do;
ods output statistics=domain&dsname;
%end;
proc surveymeans data=cps&cpsyear stacking mean nobs stderr sum;
title "Processing CPS &cpsdataset &cpsyear";
%if &smloop=1 %then %do;
title2 "&smtitle Model US";
%end;
%end;
%end;
%end;
%end;
%else %do;
title2'&smtitle by State Model';
by state;
%end;
%if %quote(&domainstmt) ne %then %do;
domain &domainstmt;
%end;
cluster h_seq;
strata geocode;
var &hivars;
weight &cpsweight;
%if %quote(&domainstmt) ne %then %do;
label
%let dv=1;
%let domainvar=%scan(&domainlist,&dv);
%do %until(&domainvar=)
&domainvar='
%let dv=%eval(&dv+1);
%let domainvar=%scan(&domainlist,&dv);
%end;
%end;
run;
%let fullmember=cps%substr(&cpsdataset,1,1)sm&cpsyear&dsname;
%let lfm=%length(&fullmember);
%if &lfm gt 32 %then %let fullmember=%sysfunc(compress(&fullmember,_));
%if &smloop=1 %then %do;
data dc&cpsyear..&fullmember(label="CPS SURVEYMEANS &cpsyear Type &dsname US");
%end;
%else %do;
data dc&cpsyear..&fullmember
(label="CPS SURVEYMEANS &cpsyear Type &dsname by state");
%end;
... DATA step code omitted ...
%end;
%mend docpsstats;
|
{"Source-Url": "http://support.sas.com/publishing/pdfs/Burlew_po05.pdf", "len_cl100k_base": 9231, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 27344, "total-output-tokens": 9717, "length": "2e13", "weborganizer": {"__label__adult": 0.0008816719055175781, "__label__art_design": 0.0008573532104492188, "__label__crime_law": 0.0018787384033203125, "__label__education_jobs": 0.0202484130859375, "__label__entertainment": 0.00022685527801513672, "__label__fashion_beauty": 0.0005793571472167969, "__label__finance_business": 0.11041259765625, "__label__food_dining": 0.0013799667358398438, "__label__games": 0.0012559890747070312, "__label__hardware": 0.0035247802734375, "__label__health": 0.037261962890625, "__label__history": 0.0009531974792480468, "__label__home_hobbies": 0.0006656646728515625, "__label__industrial": 0.0027561187744140625, "__label__literature": 0.0006480216979980469, "__label__politics": 0.0029010772705078125, "__label__religion": 0.0007958412170410156, "__label__science_tech": 0.32080078125, "__label__social_life": 0.0004878044128417969, "__label__software": 0.0970458984375, "__label__software_dev": 0.391357421875, "__label__sports_fitness": 0.0006465911865234375, "__label__transportation": 0.0016040802001953125, "__label__travel": 0.0007796287536621094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38427, 0.02151]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38427, 0.4018]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38427, 0.87798]], "google_gemma-3-12b-it_contains_pii": [[0, 4780, false], [4780, 9944, null], [9944, 14524, null], [14524, 20189, null], [20189, 24829, null], [24829, 28479, null], [28479, 32232, null], [32232, 32966, null], [32966, 33077, null], [33077, 35372, null], [35372, 37550, null], [37550, 38427, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4780, true], [4780, 9944, null], [9944, 14524, null], [14524, 20189, null], [20189, 24829, null], [24829, 28479, null], [28479, 32232, null], [32232, 32966, null], [32966, 33077, null], [33077, 35372, null], [35372, 37550, null], [37550, 38427, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38427, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38427, null]], "pdf_page_numbers": [[0, 4780, 1], [4780, 9944, 2], [9944, 14524, 3], [14524, 20189, 4], [20189, 24829, 5], [24829, 28479, 6], [28479, 32232, 7], [32232, 32966, 8], [32966, 33077, 9], [33077, 35372, 10], [35372, 37550, 11], [37550, 38427, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38427, 0.11111]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
aada7791e92a3ce6edf4eb036b3cb98462ee4a98
|
The Wrapper Facade design pattern encapsulates low-level functions and data structures within more concise, robust, portable, and maintainable object-oriented class interfaces.
Example
Consider you are developing a server for a distributed logging service that can handle multiple clients concurrently using a connection-oriented protocol like TCP [Ste90]. When a client wants to log data, it must first send a connection request. The logging server accepts connection requests using an acceptor factory, which listens on a network address known to clients.
When a connection request arrives from a client, the acceptor factory accepts the client’s connection and creates a socket handle that represents this client’s connection endpoint. This handle is passed up to the logging server, which spawns a thread and waits in this thread for logging requests to arrive on the connected socket handle. Once a client is connected, it can send logging requests to the server. The server receives these requests via the connected socket handles, processes the logging requests, and writes the requests to a log file.
A common way to develop the logging server is to use low-level C language functions and data structures for threading, synchronization, and network communication, for example by using Solaris threads [EKBF+92] and the socket [Ste97] network programming API.
However, if the logging server is expected to run on multiple platforms, such as Solaris and Win32, the data structures you need may differ in type, and the functions may differ in their syntax and seman-
tics. As a result, the implementation will contain code that handles the differences in the Solaris and Win32 operating system APIs for sockets, mutexes, and threads. For example, if written with C APIs, the logging server implementation and the logging handler function, which runs in its own thread, will likely contain many #ifdefs:
```c
#define _WIN32
#include <windows.h>
typed int ssize_t;
#if defined (_WIN32)
#include <thread.h>
#else
#include <thread.h>
#endif
#include <sys/socket.h>
#include <netinet/in.h>
#include <memory.h>
#endif /* _WIN32 */
```
```c
if defined (_WIN32)
#include <windows.h>
typed int ssize_t;
#endif /* _WIN32 */
```
```c
if defined (_WIN32)
#include <windows.h>
typed int ssize_t;
#else
#include <thread.h>
#endif /* _WIN32 */
```
```c
// Keep track of number of logging requests.
static int request_count;
#define /* _WIN32 */
// Lock to protect request_count.
#define _WIN32
#define /* _WIN32 */
// Maximum size of a logging record.
static const int LOG_RECORD_MAX = 1024;
#define /* _WIN32 */
```
```c
// Port number to listen on for requests.
static const int logging_port = 10000;
```
```c
// Entry point that writes logging records.
int write_record (char log_record[], int len) {
/* ... */
return 0;
}
```
```c
// Entry point that processes logging records for
// one client connection.
if defined (_WIN32)
long long
#else
#endif /* _WIN32 */
```
```c
// Handle UNIX/Win32 portability.
#define /* _WIN32 */
```
```c
// Create a local endpoint of communication.
acceptor = socket (PF_INET, SOCK_STREAM, 0);
```
```c
// Handle UNIX/Win32 portability.
#define /* _WIN32 */
```
```c
// Main driver function for the server.
int main (int argc, char *argv[]) {
```
23.04.1999 Wrapper-Facade.pub.doc
Even moving platform-specific declarations into separate configuration header files does not resolve the problems. For example, #ifdefs that separate the use of platform-specific APIs, such as the thread creation calls, still pollute application code. Likewise, #ifdefs may also be required to work around compiler bugs or lack of features in certain compilers. The problems with different semantics of these APIs also remain. Moreover, adding a new platform still requires application developers to modify and update the platform-specific declarations, whether they are included directly into application code or separated into configuration files.
**Context** Applications that access services provided by low-level functions and data structures.
**Problem** Applications are often written using low-level operating system functions and data structures, such as for networking and threading, or other libraries, such as for user interface or database programming. Although this is common practice, it causes problems for application developers by failing to resolve the following problems:
- **Verbose, non-robust programs.** Application developers who program directly to low-level functions and data structures must repeatedly rewrite a great deal of tedious software logic. In general, code that is tedious to write and maintain often contains subtle and pernicious errors.
➤ The code for creating and initializing an acceptor socket in the `main()` function of our logging server example is prone to errors. Common errors include failing to zero-out the `sock_addr` or not using `htons` on the `logging_port` number [Sch92]. In particular, note how the lock will not be released if the `write_record()` function returns -1.
- **Lack of portability.** Software written using low-level functions and data structures is often non-portable between different operating systems and compilers. Moreover, it is often not even portable to program to low-level functions across different versions of the same operating system or compiler due to the lack of release-to-release compatibility [Box97].
➤ Our logging server implementation has hard-coded dependencies on several non-portable native operating system threading and
network programming C APIs. For instance, \texttt{thr\_create()}, \texttt{mutex\_lock()} and \texttt{mutex\_unlock()} are not portable to Win32 platforms. Although the code is designed to be quasi-portable—it also compiles and runs on Win32 platforms—there are various subtle portability problems. In particular, there will be resource leaks on Win32 platforms since there is no equivalent to the Solaris \texttt{THR\_DETACHED} feature, which spawns a ‘detached’ thread whose exit status is not stored by the threading library.
- **High maintenance effort.** C and C++ developers typically achieve portability by explicitly adding conditional compilation directives into their application source code using \#ifdefs. However, using conditional compilation to address platform-specific variations at all points of use makes it hard to maintain and extend the application. In particular, the physical design complexity [Lak95] of the application software becomes very high since platform-specific implementation details are scattered throughout the application source files.
➤ The readability and maintainability of the code in our logging server example is impeded by the \#ifdefs that handle Win32 and Solaris portability. For instance, several \#ifdefs are required to handle differences in the type of a socket on Win32 and Solaris. In general, developers who program to low-level C APIs like these must have intimate knowledge of many operating system idiosyncrasies to write and maintain their code.
- **Lack of cohesion.** Low-level functions and data structures are not encapsulated into cohesive modules supported by programming language features, such as classes, namespaces, or packages. This lack of cohesion makes it unnecessarily hard to understand the ‘scope’ of the low-level APIs, which increases the effort required to learn the underlying abstraction.
➤ The Socket API is particularly hard to learn since the several dozen functions in the Socket library lack a uniform naming convention. Non-uniform naming makes it hard to determine the scope of the Socket API. In particular, it is not immediately obvious that \texttt{socket()}, \texttt{bind()}, \texttt{listen()}, \texttt{connect()}, and \texttt{accept()} are related. Other low-level network programming APIs address this problem by prepending a common prefix before each function, such as the \texttt{t\_} prefixed before each function in the TLI API.
As a result of these drawbacks, developing applications by programming directly to low-level functions and data structures is rarely an effective design choice for non-trivial application or system software.
**Solution**
Avoid accessing low-level functions and data structures directly. For each set of related low-level functions and data structures, create one or more *wrapper facade* classes that encapsulate these functions and data structures within more concise, robust, portable, and maintainable methods provided by the wrapper facade interface.
**Structure**
There are two participants in the Wrapper Facade pattern.
Functions are existing low-level functions and data structures that provide a cohesive service.
A wrapper facade is a set of one or more classes that encapsulate the functions and their associated data structures. These class(es) export a cohesive abstraction, that is they provide a specific kind of functionality, with each class representing a specific role in this abstraction. Application code can use the wrapper facade class(es) to access low-level functions and data structures correctly and uniformly.
<table>
<thead>
<tr>
<th>Class</th>
<th>Collaborator</th>
<th>Class</th>
<th>Collaborator</th>
</tr>
</thead>
<tbody>
<tr>
<td>Wrapper Facade</td>
<td>• Functions</td>
<td>Function</td>
<td></td>
</tr>
<tr>
<td><strong>Responsibility</strong></td>
<td>• Encapsulates low-level functions and data-structures into a cohesive abstraction</td>
<td><strong>Responsibility</strong></td>
<td>• Provides a single low-level service</td>
</tr>
</tbody>
</table>
The methods in the wrapper facade class(es) generally forward client invocations to one or more of the low-level functions, passing the data structures as parameters. The data structures are typically hidden within the private portion of the wrapper facade and are not accessible to application code. The encapsulation of data types within strongly typed wrapper facade interfaces allows compilers to enforce type-safety.
The following UML class diagram illustrates the structure of Wrapper Facade.
**Dynamics** Collaborations in the Wrapper Facade pattern are straightforward:
- The application code invokes a method via an instance of the wrapper facade.
- The wrapper facade method forwards the request to one or more of the underlying functions that it encapsulates, passing along any internal data structures needed by the function(s).
**Implementation** This section describes how to implement the Wrapper Facade pattern in C++. The implementation described below is influenced by the reusable wrapper facade components provided in the ACE communication software framework [Sch97]. The Wrapper Facade pattern can be implemented in four steps:
1. **Identify the cohesive abstractions and relationships among existing functions.** Conventional APIs like Win32, POSIX, or X Windows that are implemented as individual functions and data structures provide many cohesive abstractions, such as mechanisms for network programming, synchronization and threading, and GUI event loop management. Due to the lack of data abstraction support in low-level languages like C, however, it is often not immediately obvious how these existing functions and data structures are related to each other.
The first step in applying the Wrapper Facade pattern, therefore, is to identify the cohesive abstractions and relationships among the lower
level functions and data structures in an existing API. In other words, we first define an ‘object model’ by clustering the existing low-level API functions and data structures into one or more classes, which hide the data representation from clients.
In our logging server example, we start by carefully examining our original implementation. This implementation uses many low-level functions that actually provide several cohesive services, such as synchronization and network communication. For instance, the Solaris mutex_lock() and mutex_unlock() functions are associated with a mutex synchronization abstraction. Likewise, the socket(), bind(), listen(), and accept() functions play various roles in a network programming abstraction.
2 Cluster cohesive groups of functions into wrapper facade classes and methods. This step can be decomposed into the following substeps:
2.1 Create cohesive classes. We start by defining one or more wrapper facade classes for each group of functions and data structures that are related to a particular abstraction. Several common criteria used to create cohesive classes include the following:
• Coalesce functions and data structures with high cohesion into individual classes, while minimizing unnecessary coupling between classes. Common examples of cohesive functions are ones that manipulate a common data structure, such as a socket, a file, or a signal set [Ste97].
• Determine the common and variable aspects [Cope98] in the underlying functions and data structures. Common variable aspects include synchronization mechanisms, memory managers, addressing formats, and operating system platform APIs. Whenever possible, variation in functions and data structures should be abstracted into classes that isolate the variation behind a uniform interface.
In general, if the original API contains a wide range of related functions it may be necessary to create several wrapper facade classes to properly separate concerns.
2.2 Coalesce multiple individual functions into methods defined together in a class. In addition to grouping existing functions into classes, it is often beneficial to combine multiple individual functions into a small-
er number of methods in each wrapper facade class. This coalescing can be used to ensure that a group of low-level functions are called in the appropriate order.
2.3 Select the level of indirection. Most wrapper facade classes simply forward their method calls directly to the underlying low-level functions. Thus, if the wrapper facade methods are inlined there may be no indirection overhead compared to invoking the low-level functions directly. To enhance extensibility, it is also possible to add another level of indirection by dispatching wrapper facade method implementations dynamically using virtual functions or some other form of polymorphism. In this case, the wrapper facade classes play the role of the abstraction class in the Bridge pattern [GHJV95].
2.4 Determine where to encapsulate platform-specific variation. Minimizing platform-specific application code is an important benefit of using the Wrapper Facade pattern. Thus, although wrapper facade class method implementations may differ across different operating system platforms they should provide uniform, platform-independent interfaces. There are two general strategies for determining how to encapsulate platform-specific implementation variation:
• One is to use conditional compilation to #ifdef the wrapper facade class method implementations. The use of #ifdefs is inelegant and tedious when littered throughout application code. It may be appropriate, however, if it's localized to a small number of platform-specific wrapper facade classes or files that are not visible to application developers. Moreover, when conditional compilation is used in conjunction with auto-configuration tools, such as GNU autoconf, platform-independent wrapper facades can be created with a single source file. As long as the number of variations supported in this file does not become unwieldy, the #ifdef strategy actually helps to localize the maintenance effort.
• A strategy for avoiding or minimizing #ifdefs altogether is to factor out different wrapper facade class implementations into separate directories, for example, one per platform. Language processing tools then can be configured to include the appropriate wrapper facade class into applications at compile-time. For example, each operating system platform can have its own directory containing implementations of platform-specific wrapper facades. To obtain a different implementation, a different include path could
be provided to the compiler. This strategy avoids the problems with #ifdefs described above because it physically decouples the various alternative implementations into separate directories.
Choosing a particular strategy depends largely on how frequently the wrapper facade interfaces and implementations change. For instance, if changes occur frequently, it is tedious to update the #ifdefs for each platform. Likewise, all files that depend on this file may need to be recompiled, even if the change is only necessary for one platform. Therefore, the larger the number of different APIs that must be supported, the less desirable the use of condition compilation.
Regardless of which strategy is selected, the burden of maintaining the wrapper facade implementations becomes the responsibility of the wrapper facade developers, rather than the application developers.
For our logging server example, we define wrapper facade classes for mutexes, sockets, and threads to illustrate how each of the issues outlined above can be addressed.
**Mutex wrapper facades.** We first define a Thread_MUTEX abstraction that encapsulates the Solaris mutex functions in a uniform and portable class interface:
```cpp
class Thread_Mutex {
public:
Thread_Mutex (void) { mutex_init (&mutex_, 0, 0); }
-Thread_Mutex (void) { mutex_destroy (&mutex_); }
int acquire (void) { return mutex_lock (&mutex_); }
int release (void) { return mutex_unlock (&mutex_); }
private:
// Solaris-specific Mutex mechanism.
mutex_t mutex_;
// Disallow copying and assignment.
Thread_Mutex (const Thread_Mutex &);
void operator= (const Thread_Mutex &);
};
```
By defining a Thread_MUTEX class interface, and then writing applications to use it, rather than the low-level native operating system C APIs, we can easily port our wrapper facade to other platforms. For
instance, the following Thread_Mutex implementation works on Win32:
```cpp
class Thread_Mutex {
public:
Thread_Mutex (void) { InitializeCriticalSection (&mutex_); }
~Thread_Mutex (void) { DeleteCriticalSection (&mutex_); }
int acquire (void) {
EnterCriticalSection (&mutex_);
return 0;
}
int release (void) {
LeaveCriticalSection (&mutex_);
return 0;
}
private:
// Win32-specific Mutex mechanism.
CRITICAL_SECTION mutex_;
// Disallow copying and assignment.
Thread_Mutex (const Thread_Mutex &);
void operator= (const Thread_Mutex &);
};
```
As described earlier, we can support multiple operating system platforms simultaneously by using conditional compilation and #ifdefs in the Thread_Mutex method implementations. If conditional compilation is unwieldy due to the number of platforms that must be supported, one alternative is to factor out the different Thread_Mutex implementations into separate directories. In this case, language processing tools, like compilers and preprocessors, can be instructed to include the appropriate platform variant into our application at compile-time.
In addition to improving portability, our Thread_Mutex wrapper facade provides a mutex interface that is less error-prone than programming directly to the low-level Solaris and Win32 functions and data structures. For instance, we can use the C++ private access control specifier to disallow copying and assignment of mutexes, which is an erroneous use case that the less strongly-typed C programming API does not prevent.
**Socket wrapper facades.** Our next wrapper facade encapsulates the Socket API. This API is much larger and more expressive than the Solaris mutex API [Sch92]. Thus, we must define a group of related
wrapper facade classes to encapsulate sockets. We start by defining a typedef that handles UNIX/Win32 portability differences:
```c
typedef int SOCKET;
#define INVALID_HANDLE_VALUE -1
```
Both SOCKET and INVALID_HANDLE_VALUE are defined in the Win32 API already. Naturally, we would either integrate this using #ifdefs or using separate platform-specific directories, as discussed earlier.
Next, we define an INET_Addr class that encapsulates the Internet domain address struct:
```c
class INET_Addr {
public:
INET_Addr (u_short port, long addr) {
// Set up the address to become a server.
memset (reinterpret_cast <void *> (&addr_), 0, sizeof addr_);
addr_.sin_family = AF_INET;
addr_.sin_port = htons (port);
addr_.sin_addr.s_addr = htonl (addr);
}
u_short get_port (void) const { return addr_.sin_port; }
long get_ip_addr (void) const { return addr_.sin_addr.s_addr; }
sockaddr *addr (void) const {
return reinterpret_cast <sockaddr *> (&addr_);
}
size_t size (void) const { return sizeof (addr_); }
private:
sockaddr_in addr_; };
```
Note how the INET_Addr constructor eliminates several common socket programming errors. For instance, it zeros-out the sockaddr_in field and ensures the port and IP address are converted into network byte order by automatically applying the ntohs() and ntohl() macros [Ste97].
The next wrapper facade class, SOCK_Stream, encapsulates the I/O operations, such as recv() and send(), that an application can invoke on a connected socket handle:
```c
class SOCK_Stream {
public:
// Default constructor.
SOCK_Stream (void) : handle_ (INVALID_HANDLE_VALUE){}
```
// Initialize from an existing HANDLE.
SOCK_Stream (SOCKET h): handle_ (h) {}
// Automatically close the handle on destruction.
~SOCK_Stream (void) { close (handle_); }
void set_handle (SOCKET h) { handle_ = h; }
SOCKET get_handle (void) const { return handle_; }
// I/O operations.
int recv (char *buf, size_t len, int flags = 0);
int send (const char *buf, size_t len, int flags = 0);
// ...
private:
// Handle for exchanging socket data.
SOCKET handle_;
Note how this class ensures that a socket handle is automatically closed when a SOCK_Stream object goes out of scope.
SOCK_Stream objects can be created by a connection factory, SOCK_Acceptor, which encapsulates passive connection establishment. The constructor of SOCK_Acceptor initializes the passive-mode acceptor socket to listen at the sock_addr address. Likewise, SOCK_Acceptor::accept() is a factory that initializes the SOCK_Stream parameter with the newly accepted connection:
class SOCK_Acceptor {
public:
SOCK_Acceptor (const INET_Addr &sock_addr) {
// Create a local endpoint of communication.
handle_ = socket (PF_INET, SOCK_STREAM, 0);
// Associate address with endpoint.
bind (handle_, sock_addr.addr (), sock_addr.size ());
// Make endpoint listen for connections.
listen (handle_, 5);
}
// Accept a connection and initialize the <stream>.
int accept (SOCK_Stream &s) {
s.set_handle (accept (handle_, 0, 0));
if (s.get_handle () == INVALID_HANDLE_VALUE)
return -1;
else
return 0;
}
private:
// Socket handle factory.
SOCKET handle_;
Note how the constructor for the SOCK_Acceptor ensures that the low-level socket(), bind(), and listen() functions are always called together and in the right order.
A complete set of wrapper facades for sockets [Sch97] would also include a SOCK_Connector, which encapsulates the active connection establishment logic. Both the SOCK_Acceptor and SOCK_Connector can be used to configure the generic acceptor and connector classes described in Acceptor-Connector pattern (145) with concrete IPC mechanisms for passive and active connection establishment.
Thread wrapper facade. Our final wrapper facade encapsulates the functions and data structures related to multi-threading. Many threading APIs are available on different operating system platforms, including Solaris threads, POSIX Pthreads, and Win32 threads. These APIs exhibit subtle syntactic and semantic differences, for example, Solaris and POSIX threads can be spawned in ‘detached’ mode, whereas Win32 threads cannot. It is possible, however, to provide a Thread_Manager wrapper facade that encapsulates these differences within a uniform API.
The following Thread_Manager wrapper facade illustrates the spawn method implemented for Solaris threads:
```cpp
class Thread_Manager {
public:
int spawn (void *(*entry_point) (void *),
void *arg,
long flags,
long stack_size = 0,
void *stack_pointer = 0,
thread_t *t_id = 0) {
thread_t t;
if (t_id == 0)
t_id = &t;
return thr_create (stack_size,
stack_pointer,
entry_point,
arg,
flags,
t_id);
}
// ... }
};
```
The Thread_Manager can also provide methods for joining and canceling threads, as well. All these methods can be ported to many other operating system platforms.
3 Determine an error handling mechanism. Low-level C function APIs typically use return values and integer codes, such as errno, that use thread-specific storage (119) to communicate errors back to their callers. This technique can be error-prone, however, if callers neglect to check the return status of their function calls. A more elegant way of reporting errors is to use exception handling. Many programming languages, such as C++ and Java, use exception handling as an error reporting mechanism. It is also used in some operating systems, such as Win32 [Cus93].
There are several benefits to using exception handling as the error handling mechanism for wrapper facade classes:
- It is extensible. Modern programming languages allow the extension of exception handling policies and mechanisms via features that have minimal intrusion on existing interfaces and usage. For instance, C++ and Java use inheritance to define hierarchies of exception classes.
- It cleanly decouples error handling from normal processing. For example, error handling information is not passed explicitly to an operation. Moreover, an application cannot accidentally ignore an exception by failing to check function return values.
- It can be type-safe. In languages like C++ and Java exceptions are thrown and caught in a strongly-typed manner to enhance the organization and correctness of error handling code. In contrast to checking a thread-specific error value like errno explicitly, the compiler ensures that the correct handler is executed for each type of exception.
However, there are several drawbacks to the use of exception handling for wrapper facade classes:
- It is not universally available. Not all languages provide exception handling. For instance, some C++ compilers do not implement exceptions. Likewise, operating systems like Windows NT that provide proprietary exception handling services [Cus93] that must be supported by language extensions, which can reduce the portability of applications that use these extensions.
• It complicates the use of multiple languages. Since languages implement exceptions in different ways, or do not implement exceptions at all, it can be hard to integrate components written in different languages when they throw exceptions. In contrast, reporting error information using integer values or structures provides a more universal solution.
• It complicates resource management. Resource management can be complicated if there are multiple exit paths from a block of C++ or Java code [Mue96]. Thus, if garbage collection is not supported by the language or programming environment, care must be taken to ensure that dynamically allocated objects are deleted when an exception is thrown.
• It is potentially time and/or space inefficient. Poor implements of exception handling incur time and/or space overhead even when exceptions are not thrown [Mue96]. This overhead can be particularly problematic for embedded systems that must be efficient and have small memory footprints.
The drawbacks of exception handling are particularly problematic for wrapper facades that encapsulate kernel-level device drivers or low-level native operating system APIs, such as the mutex, socket, and thread wrapper facades described above, that must run portably on many platforms [Sch92]. For these types of wrapper facades, a more portable, efficient, and thread-safe way to handle errors is to define an error handler abstraction that maintains information about the success or failure of operations explicitly.
One widely used error handling mechanism for the system-level wrapper facades is to use the Thread-Specific Storage pattern (119), in conjunction with errno. This solution is efficient and portable, which is why we use this approach for most of the wrapper facade use cases in this book.
4 Define related helper classes (optional). Once low-level functions and data structures are encapsulated within cohesive wrapper facade classes, it often becomes possible to create other helper classes that further simplify application development. The benefits of these helper classes is usually apparent only after the Wrapper Facade pattern has been applied to cluster low-level functions and their associated data into classes.
In our example, for instance, we can leverage the following `Guard` class that implements the C++ Scoped Locking idiom (141) [Str98], which ensures that a `Thread_Mutex` is released properly, regardless of how the method's flow of control exits a scope:
```cpp
template <class LOCK> class Guard {
public:
Guard (LOCK &lock): lock_ (lock) { lock_.acquire (); }
~Guard (void) { lock_.release (); }
// Other methods omitted...
private:
// Hold the lock by reference to avoid
// the use of the copy constructor...
LOCK &lock_;
}
```
The Guard class applies the C++ Scoped Locking idiom whereby a constructor acquires resources and the destructor releases them within a scope, as follows:
```cpp
{ // Constructor of <mon> automatically
// acquires the <mutex> lock.
Guard<Thread_Mutex> mon (mutex);
// ... operations that must be serialized.
// Destructor of <mon> automatically
// releases the <mutex> lock.
}
```
Since we use a class as the `Thread_Mutex` wrapper facade, we can easily substitute a different type of locking mechanism, while still reusing the Guard's automatic locking/unlocking protocol. For instance, we can replace the `Thread_Mutex` class with a `Process_Mutex` class:
```cpp
// Acquire a process-wide mutex.
Guard<Process_Mutex> mon (mutex);
```
It is much harder to achieve this degree of 'pluggability' if C functions and data structures are used instead of C++ classes.
Example Resolved
The code below illustrates the `logging_handler()` function of the logging server after it has been rewritten to use our wrapper facades for mutexes, sockets, and threads described in Implementation section. For comparison with the original code we present it in a two-col-
umn table with the original code from the example section in the left column, and the new code in the right column:
```c
#define WIN32
#include "windows.h"
typedef int ssize_t;
#else
// The following typedef is platform-specific.
typedef unsigned int UINT32;
#endif
#include <thread.h>
#include <csp/socket.h>
#include <netinet/in.h>
#include <memory.h>
#ifdef WIN32
// Keep track of number of logging requests.
static int request_count;
// Lock to protect request_count.
#define WIN32
static CRITICAL_SECTION lock;
#else
static mutex_t lock;
#endif
// Maximum size of a logging record.
static const int LOG_RECORD_MAX = 1024;
// Port number to listen on for requests.
static const int logging_port = 10000;
// Entry point that writes logging records.
int write_record(char log_record[], int len) {
/* ... */
return 0;
}
// Entry point that processes logging records for
// one client connection.
void *logging_handler(void *arg) {
SOCKET h = reinterpret_cast <SOCKET> (arg);
// Create a SOCK_Stream object.
SOCK_Stream stream(h);
for (;;) {
// Ensure a 32-bit quantity.
char log_record[LOG_RECORD_MAX];
// The first recv reads the length
// (stored as a 32-bit integer) of
// adjacent logging record. This code
// handles "short-receives".
ssize_t n = recv(h,
reinterpret_cast <char *> (&len),
sizeof len, 0);
// Bail out if we're shutdown or
// errors occur unexpectedly.
if (n <= sizeof len) break;
len = ntohl(len);
if (len > LOG_RECORD_MAX) break;
// The second recv reads len bytes to obtain the actual record.
// This code handles "short-receives".
for (int i = 0; i < len; i++) {
// Bail out if an error occurs.
if (n < 0) return 0;
}
}
return 0;
}
#endif /* _WIN32 */
```
Analogously to the `logging_handler()` function, we present a two-column table that compares the original code for the `main()` function with the new code using wrapper facades:
<table>
<thead>
<tr>
<th>Original Code</th>
<th>Wrapper Facade Code</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>EnterCriticalSection(&lock);</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>mutex_lock(&lock);</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>Count # of requests</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>if (write_record(log_record, len) == -1)</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>break;</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>closesocket(h);</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
<tr>
<td><code>return 0;</code></td>
<td><code>Guard<Thread_Mutex> mon(lock);</code></td>
</tr>
</tbody>
</table>
// Main driver function for the server.
int main(int argc, char* argv[])
{
// Handle UNIX/Win32 portability.
#if defined(_WIN32)
SOCKET acceptor;
#else
int acceptor;
#endif /* _WIN32 */
// Create a local endpoint of communication.
acceptor = socket(PF_INET, SOCK_STREAM, 0);
// Set up the address to become a server.
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(logging_port);
sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// Associate address with endpoint.
bind(acceptor, reinterpret_cast<struct sockaddr*>(&sock_addr), sizeof(sock_addr));
// Make endpoint listen for connections.
listen(acceptor, 5);
// Main server event loop.
for (;;) {
// Handle UNIX/Win32 portability.
#if defined(_WIN32)
SOCKET h;
#else
int h;
#endif /* _WIN32 */
// Block waiting for clients to connect.
h = accept(acceptor, 0, 0);
// Spawn a new thread that runs the server.
#if defined(_WIN32)
CreateThread(0, 0, LPTHREAD_START_ROUTINE(logging_handler), reinterpret_cast<void*>(h), 0, &t_id);
#else
thr_create(0, 0, logging_handler, reinterpret_cast<void*>(h), THR_DETACHED, &t_id);
#endif /* _WIN32 */
return 0;
}
}
Note how the code in the right column fixes the various problems with the code shown in the left column. For instance, the destructors of \texttt{SOCK\_Stream} and \texttt{Guard} will close down the socket handle and release the \texttt{Thread\_Mutex}, respectively, regardless of how the blocks of code are exited. Likewise, this code is easier to understand, maintain, and port since it is much more concise and uses no platform-specific APIs.
**Known Uses**
**Microsoft Foundation Classes (MFC).** MFC provides a set of wrapper facades that encapsulate most of the low-level C Win32 APIs, focusing largely on providing GUI components that implement the Microsoft Document/Template architecture, which is a synonym for the Document-View architecture described in [POSA1].
**The ACE framework.** The mutex, thread, and socket wrapper facades described in the \texttt{implementation} section are based on components in the ACE framework [Sch97], such as the \texttt{ACE\_Thread\_Mutex}, \texttt{ACE\_Thread\_Manager}, and \texttt{ACE\_SOCK* classes}, respectively.
**Rogue Wave class libraries.** Rogue Wave’s \texttt{Net.h++} and \texttt{Threads.h++} class libraries implement wrapper facades for sockets, threads, and synchronization mechanisms on a number of operating system platforms.
**ObjectSpace System<Toolkit>.** Wrapper facades for sockets, threads, and synchronization mechanisms are also provided by the ObjectSpace System<Toolkit>.
**Java Virtual Machine and Java class libraries.** The Java Virtual Machine (JVM) and various Java class libraries, such as AWT and Swing, provide a set of wrapper facades that encapsulate many low-level native operating system calls and GUI APIs.
**Siemens REFORM framework.** The REFORM framework for hot rolling mill process automation [BGHS98] uses the Wrapper Facade pattern to shield the object-oriented parts of the system, such as material tracking and setpoint transmission, from a neural network for the actual process control. This neural network is programmed in C due to its algorithmic nature: it contains mathematical models which describe the physics of the automation process. The wrapper facades provide the views that the object-oriented parts of the framework need onto these functional models.
Consequences
The Wrapper Facade pattern provides the following benefits:
Concise, cohesive, and robust programming interfaces. The Wrapper Facade pattern encapsulates many low-level functions and data structures within a more concise and cohesive set of object-oriented class methods. This reduces the tedium of developing applications, thereby decreasing the potential for programming errors. The use of encapsulation also eliminates a class of programming errors that occur when using untyped data structures, such as socket or file handles, incorrectly.
Portability and maintainability. Wrapper facade classes can be implemented to shield application developers from non-portable aspects of low-level functions and data structures. Moreover, the Wrapper Facade pattern improves software structure by replacing an application configuration strategy based on physical design entities, such as files and #ifdefs, with logical design entities, such as base classes, subclasses, and their relationships [Lak95]. It is generally easier to understand and maintain applications in terms of their logical design rather than their physical design.
Modularity, reusability, and configurability. The Wrapper Facade pattern creates cohesive reusable class components that can be ‘plugged’ in and out of other components in a wholesale fashion using object-oriented language features like inheritance and parameterized types. In contrast, it is much harder to replace groups of functions without resorting to coarse-grained operating system utilities, such as linkers or file systems.
The Wrapper Facade pattern has the following liability:
Additional indirection. The Wrapper Facade pattern can incur additional indirection compared with using low-level functions and data structures directly. However, languages that support inlining, such as C++, can implement this pattern with no significant overhead since compilers can inline the method calls used to implement the wrapper facades. Thus, the overhead is often the same as calling the low-level functions directly.
See Also
The Wrapper Facade pattern is similar to the Facade pattern [GHJV95]. The intent of the Facade pattern is to simplify the interface for a subsystem. The intent of the Wrapper Facade pattern is more specific: it provides concise, robust, portable, maintainable, and
cohesive class interfaces that encapsulate low-level functions and data structures, such as the native operating system mutex, socket, thread, and GUI C language APIs. In general, facades hide complex class relationships behind a simpler API, whereas wrapper facades hide complex function and data structure relationships behind a richer class API. Moreover, wrapper facades provide building block components that can be ‘plugged’ into higher-level components.
The Wrapper Facade pattern can be implemented with the Bridge pattern [GHJV95] if dynamic dispatching is used to implement wrapper facade methods that play the role of the abstraction participant in the Bridge pattern.
The Layers pattern [POSA1] helps with organizing multiple wrapper facades into a separate layer component. This layer resides directly atop the operating system and shields an application from all low-level APIs that it uses.
**Credits**
Thanks to Brad Appleton for extensive comments that greatly improved the form and content of the Wrapper Facade pattern description.
|
{"Source-Url": "http://laputan.org/pub/sag/wrapper-facade.pdf", "len_cl100k_base": 8500, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 48308, "total-output-tokens": 9655, "length": "2e13", "weborganizer": {"__label__adult": 0.0003414154052734375, "__label__art_design": 0.0002646446228027344, "__label__crime_law": 0.00024127960205078125, "__label__education_jobs": 0.00034332275390625, "__label__entertainment": 4.202127456665039e-05, "__label__fashion_beauty": 0.0001112818717956543, "__label__finance_business": 0.00013303756713867188, "__label__food_dining": 0.00029397010803222656, "__label__games": 0.00047898292541503906, "__label__hardware": 0.0007314682006835938, "__label__health": 0.0002149343490600586, "__label__history": 0.00018012523651123047, "__label__home_hobbies": 6.407499313354492e-05, "__label__industrial": 0.00030732154846191406, "__label__literature": 0.0001583099365234375, "__label__politics": 0.0002058744430541992, "__label__religion": 0.0003788471221923828, "__label__science_tech": 0.0026912689208984375, "__label__social_life": 5.227327346801758e-05, "__label__software": 0.0032405853271484375, "__label__software_dev": 0.98876953125, "__label__sports_fitness": 0.00022971630096435547, "__label__transportation": 0.0004754066467285156, "__label__travel": 0.00020754337310791016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40784, 0.01277]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40784, 0.72987]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40784, 0.82952]], "google_gemma-3-12b-it_contains_pii": [[0, 1577, false], [1577, 3423, null], [3423, 5658, null], [5658, 8092, null], [8092, 10029, null], [10029, 11440, null], [11440, 13635, null], [13635, 16089, null], [16089, 18019, null], [18019, 19813, null], [19813, 21503, null], [21503, 23140, null], [23140, 25018, null], [25018, 27213, null], [27213, 29448, null], [29448, 31184, null], [31184, 33100, null], [33100, 35119, null], [35119, 37387, null], [37387, 39729, null], [39729, 40784, null], [40784, 40784, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1577, true], [1577, 3423, null], [3423, 5658, null], [5658, 8092, null], [8092, 10029, null], [10029, 11440, null], [11440, 13635, null], [13635, 16089, null], [16089, 18019, null], [18019, 19813, null], [19813, 21503, null], [21503, 23140, null], [23140, 25018, null], [25018, 27213, null], [27213, 29448, null], [29448, 31184, null], [31184, 33100, null], [33100, 35119, null], [35119, 37387, null], [37387, 39729, null], [39729, 40784, null], [40784, 40784, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40784, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40784, null]], "pdf_page_numbers": [[0, 1577, 1], [1577, 3423, 2], [3423, 5658, 3], [5658, 8092, 4], [8092, 10029, 5], [10029, 11440, 6], [11440, 13635, 7], [13635, 16089, 8], [16089, 18019, 9], [18019, 19813, 10], [19813, 21503, 11], [21503, 23140, 12], [23140, 25018, 13], [25018, 27213, 14], [27213, 29448, 15], [29448, 31184, 16], [31184, 33100, 17], [33100, 35119, 18], [35119, 37387, 19], [37387, 39729, 20], [39729, 40784, 21], [40784, 40784, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40784, 0.02902]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
30198e97e85114cc28591529e870f7d3f5e8e308
|
Esta es la versión de autor de la comunicación de congreso publicada en:
This is an author produced version of a paper published in:
DOI: http://dx.doi.org/10.1016/j.intcom.2007.07.007
Copyright: © 2008 Elsevier B.V. All rights reserved
El acceso a la versión del editor puede requerir la suscripción del recurso
Access to the published version may require subscription
Customization of Web Applications through an Intelligent Environment Exploiting Logical Interface Descriptions
José A. Macías\textsuperscript{1}, Fabio Paternò
ISTI-CNR
Via G. Moruzzi 1
56124 Pisa, Italy
{Jose.Macias, Fabio.Paterno}@isti.cnr.it
Abstract
Customization of Web-based applications is often considered a designer skill rather than an end-user need. However, there is an ongoing shift to end-user-centred technology, and even users with poor or no skill in Web-based languages may feel the need to customize Web applications according to their preferences. Although Web authoring environments have an increasing number of features, the challenge of providing end-users with the ability to easily customize entire Web applications still remains unsolved. In this paper, we propose an intelligent approach to customizing Web-based applications. Customizations rules are automatically inferred by the system from changes that users supply as examples. They remain as long-term knowledge that can be applied to support future interactions, thus minimizing the amount of authoring that end-users need to do for this purpose. In order to better understand the implications of the user’s modifications, they are analysed using the logical descriptions of the corresponding Web pages.
Keywords
Human-Computer Interaction; End-User Development; Intelligent User Interfaces; Programming by Example; Model-Based User Interfaces; Web-based Nomadic Applications.
1. Introduction
As software products grow in terms of expressivity, there is also a growing need to allow people to customize, configure and also create their own software artefacts in order to accomplish their daily tasks properly. This is important, for example, for professionals such as engineers, scientists and freelance professionals having concrete domain skills but lacking programming abilities. Further support is needed in order to provide non-programmer professionals with easy-to-use mechanisms to customize software artefacts, avoiding the need for them to learn programming and specification languages that are usually deemed to be irrelevant to their daily work. In our view, customization can be regarded as the modification of interactive software in order to better match the user preferences.
Generally, the explicit customization of software applications is considered a cumbersome task that most non-computer-skilled end-users cannot afford. The
\textsuperscript{1} Permanent Address: EPS, Universidad Autónoma de Madrid. Ctra. de Colmenar, Km. 11. 28049 Madrid, Spain. E-mail: j.macias@uam.es
complexity of programming and specification languages discourages users even from attempting software customization. Although most applications do not provide much support for customization, some of them allow users to adapt partial aspects of the application to their own needs by selecting predefined options. However, this is clearly not enough. Desktop applications are usually complex and implemented in structured programming languages. This has traditionally made it difficult to provide easy-to-customize end-user approaches for them. Thus, the few existing approaches to this respect have been mainly focused on some domain-dependent support. Further, the traditional desktop customization process cannot be applied straightforward to Web environments, since they are based on an underlying specific mark-up language (i.e. XHTML). On the other hand, XHTML is easier to access and manipulate and enables the possibility of end-user development, in which users can customize their applications. However, customization of interactive Web applications still requires considerable skill in programming and Web technology. Some preliminary studies indicate that these limitations in end-user Web development activities are not due to lack of interest but rather to the difficulties inherent in interactive Web development (Rode et al., 2006). Commercial Web development tools already offer support for high-level functionality, but most of these tools are not aimed at non-programmers.
Providing users with real customization facilities is not yet as widespread as one would expect. Most existing approaches provide little support to end-users, and the ease of customization of commercial applications leaves much to be desired. However, some researchers have devoted considerable effort to bring design closer to users. This involves End-User Development (EUD) research (Lieberman et al., 2006), where the main concern is to enable users to easily modify and create software artefacts. Programming by Example (Cypher, 1993; Lieberman, 2001) is one of the more relevant approaches in EUD, which aims at obtaining a satisfactory trade-off between ease-of-specification and expressiveness. Programming by Example has the potential to allow users to customize their applications. Rather than writing a program in a programming language to automate a task, users simply demonstrate how to perform it.
Our research is aimed at leveraging these problems by providing automatic mechanisms to allow customization tasks easily. Therefore, the main problem we address here is how to provide intelligent automatic support for customising Web applications even for non-computer-skilled end-users. To face such a challenge, we leverage Model-Based User Interfaces Design (MBUID) approaches (Paternò, 1999) combined with customization techniques (Macias and Castells, 2004). The overall goal is natural development (Berti et al., 2006), which implies that people should be able to create or modify applications by working through familiar and immediately understandable representations to express relevant concepts. In this respect, our main contribution exploits Model-Based User Interface Design (Szekely, 1996) and End-User Development research, combining them by means of an intelligent environment that can infer meaningful information from the user’s modifications. Our approach is based on an expert system where the knowledge is built up progressively, increasing in every user session (i.e. evolutionary approach). According to the MBUID paradigm, we consider the different conceptual levels in which a user interface can be specified. We obtain a logical user interface description (UID), which provides a description of the main conceptual elements associated with the user interface without considering implementation details, from the reverse engineering transformation of XHTML pages. Automatically, our intelligent environment compares the logical description of the modified page with the original ones, reasoning about such changes by means of rules.
Therefore, the user only has to provide the system with examples of what s/he desires to modify, and the system identifies customization rules automatically by analyzing the user changes. To this end, our intelligent rule-based system exploits JESS, the Rule Engine for Java Platforms (JESS, 2006). Jess includes an enhanced version of the Rete algorithm (Forgy, 1982), an efficient pattern matching algorithm for implementing production rule systems. We use the Rete algorithm together with information regarding the page context in which the user change occurred, in order to reduce the implicit ambiguity in drawing inference from similar user changes. The possible page contexts are identified by analyzing the abstract descriptions of the corresponding pages. They are used to identify different user changes in similar situations, and so obtain more general domain-independent customization rules (Macías and Castells, 2005).
This paper is structured as follows. After the related work in Section 2, we describe the general approach proposed. Section 4 provides further detail and describes how the intelligent mechanism is structured. Next, we explain the process of extracting meaningful information from user customizations. Section 6 reports on a user test that has been carried out to provide empirical feedback on the approach proposed. The test results are useful to understand the feasibility of reducing the complexity of Web application customization. Lastly, Section 7 draws some conclusions and provides indications for future work.
2. Related Work
Traditionally, Programming by Example (PBE) research has adopted rule-based systems mostly due to the execution speed and simplicity they provide, compared with other complex machine-learning algorithms that often have a high error rate and low generalization in real-time interaction with users.
Some early PBE systems used rules to infer user intentions. For instance, Eager (Cyper, 1993) uses LISP implemented rules to complete specific repetitive tasks on behalf of the user. Eager is considered a predictive interface since it detects two consecutive occurrences of a repetitive task in a sequence of user actions. Eager automatically infers patterns by observing user actions. Typically, the actions that Eager infers are mostly based on textual operations that users carry out on the Apple-Macintosh HyperCard application. By contrast, in our system users are not monitored during the interaction, and we provide them with the freedom to use any authoring environment to modify Web applications. Moreover, in addition to syntactic changes our system also deals with semantics corresponding to changes in the logical structure (i.e. relations, grouping, hierarchical, navigational and other changes) that can be generalized from session to session, as the system is responsible for distinguishing between pending and permanent customization preferences in any Web application.
Inference Bear (Frank et al., 1995) is another PBE system that infers design choices from user-generated snapshots. Inference Bear generates a custom user interface by observing the behaviour of the interface designer. Like Eager, Inference Bear is based on a specific application- i.e. a graphical design tool that makes it possible to infer geometrical relationships from user actions. In our approach, we provide more general inference by supporting both semantic and syntactic changes, independently of the authoring tool used. We mean for semantic changes those that modify the logical structure of the user interface or the tasks supported by the interactive application. User preferences are captured by our system and they can be used later on to obtain further
information about customization that will be updated and refined in an evolutionary way from session to session.
Some early Myers’s tools such as Peridot (Myers, 1998) supported a rule-based approach. Peridot is more oriented to supporting user interface design. It uses about fifty hand-coded Interlisp-D rules to infer the graphical layout of the objects from the examples. The system allows the interface designer to draw a picture of what the user interface should look like using a special drawing package. This way, the system infers user interface groupings, geometrical dependences and spatial relationships, taking also into account the user’s input. This type of system is able to generalize only limited forms of behaviours. Additionally, it is mostly focused on static knowledge and can be considered domain-dependent. By contrast, our system proposes a dynamic knowledge approach together with an application-independent intelligent environment, in which a complete rule structure is proposed in order to consider different kinds of conceptual knowledge that can be updated from time to time through an evolutionary approach. Our system can be considered domain-independent since it is able to process any application written with XHTML. Indeed, the semantic structure is extracted and processed independently of the content type.
More recently, AgentSheets (Repenning and Ioannidou, 2006) is an example of a commercial EUD approach for building intelligent interfaces. AgentSheets is a simulation environment that allows users to create advance simulation scenarios by defining intelligent agents and behaviour separately. AgentSheets combines PBE with graphical rewrite rules into an end-user programming paradigm. Graphical rewrite rules are powerful languages to express the concept of change in a visual representation. Like AgentSheets, our approach applies semantic rules for dealing with high-level behaviour. As pointed out by the AgentSheets’ authors, a first step toward creating more usable and reusable rewrite rules is to move from syntactic rewrite rules to semantic ones, including semantic meta-information. The lack of semantics not only makes reuse difficult, but also involves significant problems for building new behaviours from scratch, reducing dramatically the scalability of a PBE approach as well. In this respect, in our approach we consider different levels of knowledge and behaviour. We accomplish this by dividing rules and facts into different conceptual levels that help to automatically achieve in-depth analysis and accurately infer the user’s preferences through an evolutionary approach, in which the knowledge increases proportionally with the number of user sessions considered.
The use of semantic knowledge has been a main concern in building intelligent inference systems. Lieberman’s work on Common Sense Reasoning (Lieberman et al., 2004) provides some evidence by using high-level knowledge bases to carry out automatic reasoning. In that work, mostly related to natural language-based interaction, the system tries to infer meaningful user definitions by using natural language (Lieberman and Liu, 2006). The authors assume that syntactical definitions are vague and imprecise, and so they need to be disambiguated using a semantic layer in the form of an ontology to obtain high-level information. In our approach, we deal with logical user interface descriptions to infer more specific user preferences. We reduce the ambiguity in analysing user changes by using both a more accurate inference algorithm and semantic knowledge extracted from the modified Web-based interface.
Another related work is DESK (Macías et al., 2006), which uses domain knowledge for characterizing changes from a dynamically generated interface, also making minimal assumptions about the end-user’s skills on programming and specification languages. DESK uses the PEGASUS specification based on domain ontologies in order to specify
explicit knowledge of both presentation and domain information separately. DESK is based on a client-server architecture that comprises two different applications. The client side is a front-end what-you-see-is-what-you-get (WYSIWYG) authoring tool, whereas the server side is a back-end application that infers and carries out the changes the user makes to the Web interface. DESK’s front-end tracks and records information about the user’s actions by building up a XML monitoring model. This information is sent to the back-end application, which in turn processes the monitoring model and applies different heuristics by using domain knowledge. DESK deals with modifications in the HTML code that are later processed to obtain meaningful information by means of fixed heuristics. Our approach improves DESK’s mechanisms by identifying customization rules automatically, comparing logical descriptions of the original and modified interfaces and with no need to have a specific authoring client application. This allows our environment to achieve domain independence. The logical user interface descriptions are specified in TERESA XML (Berti et al., 2004). We exploit the information provided by the logical interface description to obtain semantic information. Besides, the knowledge management is improved by defining different levels of knowledge that are applied to better characterize customizations and update the expert system for future inference.
More recently, Chickenfoot (Bolin et al., 2005) provides a programming environment embedded in the Firefox Web browser for automation and customization of Web pages. Our approach differs from it in many respects: it is not linked to any particular Web browser and, since we manage the customization rules at the server side, we can support customization even when different client devices (and browser) are used to access the same Web application. Additionally, in Chickenfoot the user is requested to introduce script code, whereas in our system we avoid users to program any code as changes to Web pages are made by WYSIWYG tools and are automatically detected and processed by our system independently of the specific authoring tool used.
3. Our Approach
Our environment aims to support Web interfaces for different platforms in order to allow users to access the application using one device from a set of different existing platforms (desktop computer, mobile, PDA). At any time, the user can provide the system with examples obtained by modifying the generated Web pages with any authoring environment. Reverse engineering techniques are applied in order to obtain logical descriptions of the modified Web pages, which are useful to analyse high-level information about the user’s modifications.
In particular, our approach supports the following steps (see Figure 1):
1) The end-user navigates through a desktop Web application and, at some point, s/he decides to modify something by using standard WYSIWYG Web authoring tools such as Microsoft FrontPage, Macromedia Dreamweaver and so on, where users can make sample changes in order to provide indications of their preferences. Such changes comprise deletion, addition, insertion, substitution, presentation-element re-arrangement, style-effect application, property changes, and so on.
2) Once the user has finished the changes, s/he sends the modified pages to the server, by using a specific Web application in which s/he first needs to login (see Figure 8).
3) The server receives the Web page and then starts the inference process to identify the user’s preferences.
a. First, the server transforms the modified page into a logical description stored in a XML file, using the reverse mechanism developed by our group (Bandelloni et al., 2007). The file contains the user interface specification of the page (i.e. UID on top-right corner of Figure 1), in terms of language-independent elements.
b. Then, the system compares the logical description corresponding to the modified page with the logical description of the previously generated page.
c. During the comparison process, the system generates high-level information to feed the expert system and identify general user preferences. This intelligent mechanism will be explained in detail later on.
d. At the end of the process, the system builds an End-User Profile taking into account all this high-level information inferred, as well as other previously generated, and containing customization preferences.
4) The End-User Profile is then used to regenerate the Web pages, taking into account the user’s preferences. The system stores an End-User Profile for each user and platform.
The End-User Profile must also contain the logical specification of the page modified by user. The information included in the Profile will be updated every time the user sends a modified Web page to the server. Thus, the End-User Profile is updated with new inference information and the interface logical descriptions are updated accordingly.
The most relevant information in the End-User Profile is the set of user interface customization rules. Such rules are inferred from the comparison of the logical descriptions and aim to reflect the knowledge acquired by the system from analysis of the user’s changes. Later on, the rules are used in the generation of the Web pages, customizing the Web presentation and navigation depending on the inferred preferences. All this explicit knowledge can be modelled by means of a knowledge base (i.e. an expert system) containing facts and sets of rules to be applied when new information about user modifications is identified.

The intelligent approach is implemented by using an ad-hoc expert system, where the knowledge can be suitably modelled and where the inference takes place efficiently. More specifically, we are mostly interested in production systems to implement a pattern recognition approach by means of rule languages. Such languages provide a framework able to deal with facts and rules, as well as the capability to populate the knowledge base with new information from time to time (evolutionary approach).
In our approach, the facts represent the information coming from the user’s modifications. This information is extracted by comparing the logical interface
descriptions of the modified and the original page (see Figure 2). The rules are ad-hoc conditions used to extract information from the facts, that is, from the changes the user makes to the presentation and from other high-level information available in the expert knowledge base. Since all the user information is stored in a user model (the user profile), the rules will reflect not only the user’s changes but information about the platform (Desktop, Mobile, and so on). This evolutionary approach, which continuously produces and modifies facts, aids the system to refine the user’s preferences and extracts accurate information as interaction evolves.
In order to improve precision and accuracy in the inference process, we use Rete as an efficient pattern matching algorithm for implementing rule-based (expert) systems. It was originally designed by Forgy at Carnegie Mellon University. A Rete-based expert system builds a network of nodes, where each node (except the root) corresponds to a pattern occurring on the left-hand-side of a rule. Each node has a memory of facts, which satisfy that pattern. As new facts are added or modified, they propagate along the network, causing nodes to be annotated when that fact matches that pattern. When a fact or combination of facts satisfies all patterns of a given rule, a leaf node is reached and the corresponding rule is triggered. The Rete algorithm is designed to sacrifice memory for increased speed.
4. User Interface Modelling and Intelligent Processing
In our approach, we want to identify the user’s preferences from the changes that s/he made to the Web pages. Furthermore, we want our environment to be able to take into account previous changes. Therefore, the idea was to develop an intelligent system capable of detecting changes through the analysis of the logical user interface specifications in TERESA XML (Berti et al., 2004). In this specification language, a user interface can be described at different abstraction levels. In particular, we considered the abstract and concrete levels. The abstract label is a logical description of the user interface independent of the platform. We mean for platform a group of devices that have similar interaction resources (i.e. desktop, PDA, mobile, etc.). By contrast, the concrete level is a platform-dependent description of a user interface, so it is a refinement for a specific platform. For example, at the abstract level we can have the specification of a selection object (without any indication whether the selection is performed in a graphical, vocal or gestural modality). A corresponding concrete element for the graphical platform would be a list or a radio-button or a pull-down menu, which are examples of objects that support selection in a graphical device. In both cases, the user interface is composed of interactors and composition operators indicating how to structure their composition.
While at the abstract level the various interactors are described with no reference to any particular interaction modality, at the concrete level the characterisation of each interactor depends on the type of platform and media available, with a number of attributes that define more concretely its appearance and behaviour. Examples of interactors at the abstract level are Description, Navigator, Text, Single Selection, etc., whereas examples of interactors at the concrete level are Image, Link, Text Field, Radio Button, List, etc.. There are different one to many relationships between interactors at the abstract and the concrete level (e.g. a navigator can be a text link, an image link, or a button), which indicate how an abstract interaction can be supported in a given platform at the concrete level.
The composition operators provide useful information in terms of how interactors are put together, the relation among them and the associated communication goal. At the abstract level, there are four different composition operators:
- Grouping: Indicates a set of interface elements logically connected to each other
- Ordering: Some kind of ordering among a set of elements can be highlighted
- Hierarchy: Different levels of importance can be defined among a set of elements
- Relation: Highlights a one-to-many relation among some elements, one element has some effects on a set of elements
By contrast, the concrete level indicates how each composition operator can be supported, for example a grouping can be obtained through a Fieldset (a rectangle including the grouped elements), or lining up the composed elements, and so on.

**Figure 3.** Mappings between Web-page components and concrete and abstract elements that are extracted from a Web page.
Figure 3 shows an example of a generated Web form and the structure of its corresponding abstract and concrete specifications. The concrete information is represented by concrete interactors (such as Textfield, Button and so on) and concrete composition operators (such as Form and FieldSet). It is worth looking at the mappings between abstract elements (on the left) and page components. The abstract elements provide the intelligent environment with the conceptual description of the interface design. This information consists of the types of composition operators (such as Relation, Grouping,) and different kinds of interactors (such as Description, Text Edit, Single Selection and so on). This knowledge is useful for identifying presentation contexts when changes to a Web page are analysed.
Modifications affecting the concrete level provide syntactical knowledge, while those that have effects on the abstract level provide semantic knowledge because they imply changes to the actual purpose of the interface elements. We consider both kinds of modifications in order to construct a knowledge structure to feed the expert system with
suitable facts and activate expert rules to produce user customizations efficiently. Additionally, we also want to consider both syntactic and semantic customization rules that may be fired more than once for different changes applied in the same page context. Semantic customization rules are used to deal with changes concerning interactors and composition operators at the abstract level. By contrast, syntactic customization rules are related to user preferences associated with user modifications that have an effect only on the concrete specification (e.g. changes concerning font size, colour, and other syntactical preferences). The knowledge obtained will be applied the next time that the application server generates the corresponding pages.
This conceptual separation helps to identify different kinds of rules as well as to build the knowledge progressively, according to the kind of fact that is produced and managed. In addition to rules, different sets of facts are generated at every level. In this sense, the relations among the different levels of knowledge can be represented as in Figure 4.
Regarding Figure 4, it is worth noting that there are dependences between the facts generated by each rule and the rules that process such facts. As we can see, base knowledge facts ($F_{BK}$) are processed by each kind of rule, whereas syntactic facts ($F_{Sy}$) are generated by the syntactic rules and processed only by the semantic ones. In contrast, the semantic facts ($F_{S}$) are generated by the semantic rules and processed by the expert ones. Moreover, expert rules generate expert facts ($F_{E}$) that reflect the meaningful information in terms of customization rules for future use. All the facts generated, as well as the rules, will remain as base-knowledge facts to be taken into account in later sessions.
The following steps are considered in defining the knowledge:
1) **Defining base knowledge** containing basic definition about user, platform and the previous knowledge inferred. This is the information that always remains in the expert system and is updated from session to session.
2) **Defining syntactic knowledge** that contains facts and rules triggered by syntactic modifications to presentation elements such as concrete interactors (for instance, in a graphical desktop system concrete interactors can be Radio Buttons, List Boxes, Textual Links, Buttons, Input Texts and so on) and concrete composition operators. The concrete composition operators implement the abstract operators (grouping, hierarchy, ordering and relation) through constructs such as Fieldset, Unordered List, Ordered List, Table, Form, and so on. An example of syntactical modification is when the value of an attribute of a
concrete interactor or a concrete composition operator is changed (e.g. when its colour, alignment, justification and so on are changed).
3) **Defining semantic knowledge** for dealing with semantic information by taking into account the syntactic information already created. The semantic level considers changes in the abstract (platform-independent) elements called interactors and composition operators. For instance, it identifies when an interactor is moved from a composition operator to another, or when it is deleted or removed, or also when the number of interactors in one possible composition (ordering, hierarchy relation or grouping) is changed. The semantic level also concerns presentation contexts, that is, high-level descriptions of the elements (and their relations) surrounding a change made in the graphical interface. Presentation contexts allow the creation of expert rules based on contextual information that can be applied more than once.
4) **Defining expert rules** for dealing with further semantic aspects and detecting user preferences. Expert rules utilize all the underlying information available in the expert system, and they can be regarded as the top (semantic) layer by which high-level preferences can be finally inferred. These rules can be hand-coded by experts to define both syntactic and semantic customization rules that will be deployed using the underlying knowledge available in order to further characterize user changes (e.g. when a same user has changed the navigational structure or the layout, or several users have made similar modifications). This can be inferred in a domain-independent way by analyzing the knowledge available in the expert system from previous sessions.
Knowledge is built up progressively from the lowest levels to the highest ones. The knowledge constructed at the lowest levels is basically composed of syntactic information automatically generated by the system. This information is inferred by comparing the concrete user interface specifications before and after the user’s changes, and is related to the elements the user implicitly manipulates when modifying a presentation. The system provides mechanisms to analyze user modifications and identify to what knowledge level they belong. For instance, when the user attempts to modify a form, s/he might decide to replace a Radio Button with a Selection List. This change will be considered as a syntactic one, since both interactors are under the same abstract category: *single selection interactor*, which identifies its main semantic effect. However, if the user decides to replace a Radio Button with a CheckBox, then a semantic change occurs, since Radio Button belongs to the *single selection interactor* abstract category and CheckBox to *multiple selection interactor*. In this case, even the task supported by the application changes because of such a user change.
In addition, for each user change the system extracts the corresponding presentation context, which is based on the abstract specification of the interface. This allows the definition of more general rules that can be associated with similar, though not exact, user modifications.
5. **Inferring Meaningful Information from User Modifications**
Expert Rules deal with information about user preferences from one session to another, taking into account the existing facts generated by the previous expert-knowledge layers. If these rules are often fired, then the customization rules corresponding to the user’s design preferences can be detected. Therefore, we can distinguish two different
kinds of rule activations in our system: those pending and the permanent ones. Pending customization rules are identified whenever the system detects a probable user attempt to customize an element or a group of elements in the presentation, whereas permanent customization rules correspond to pending rules that have been identified more than twice in the same context. This mechanism allows us to differentiate occasional user modifications from explicit and repetitive preferences. Permanent customizations will drive the customization of the application in future accesses, and they can be turned on and off by end-users using the NOTORIOUS environment (see Section 6.2).
Each customization rule (both pending and permanent) is associated with a reference context, which is useful to identify whether user changes are substantially similar. When a change is made to a page, the system analyses the page structure and the elements surrounding the change to define its context. Then, it checks whether there is a similarity with any of the presentation contexts of the identified customization rules.
The contextual presentation information is processed in two stages. The first stage extracts syntactic context from the comparison of the concrete interface specifications of the original and the modified page. The second stage operates at the semantic level, processing syntactic context and relating it to knowledge concerning abstract elements, with the aim of obtaining meaningful information that could be deployed to apply more general rules in similar contexts. This way, when differences are found through comparison of the concrete interface specifications, this new knowledge is added to the expert system in terms of facts (as explained in Figure 2), together with the syntactic context in which such changes take place. The location of the modifications is extracted from the concrete specification, which provides sufficient detail to accurately identify the objects surrounding a user’s change.
Figure 5 depicts how syntactic context is identified from a user’s change to the Web form in Figure 3. Such change consists of moving both the Reset and Submit buttons to the upper part of the form, between the page title and the personal data input fields. This change could be due to the fact that the user prefers such buttons to appear above the other form elements.
Figure 5. The process of building knowledge from detected user changes. The relations among the abstract and concrete elements of the interface involved in the user modifications are shown.
Figure 5 shows the structure of the logical specification of the original and the modified XHTML pages obtained by the reverse engineering tool developed in our group. The rectangles denote the modifications to the Reset and Submit buttons, involving moving the buttons originally contained in FieldSet3 into FieldSet1. This change can be regarded as a single one, since it involves a grouping of concrete interactors (in this case composed through a Fieldset element). Then, the system extracts information about the change and also about the syntactic context from the concrete presentation, identifying where the change has been performed.
In our system, all rules and facts are coded in LISP. In the paper, for the sake of readability, we provide a pseudo-code representation. In the example, the syntactic knowledge is updated by a syntactic rule fired whenever a Fieldset changes, associating the change to a specific user and platform and updating the existing information stored in our expert system:
```lisp
Rule
If change(FieldSet)
Then update(FieldSet, to, from, contains, above, below, user, platform)
```
While facts are automatically generated by the system, rules have to be defined by the expert system designer. However, the rules notation is flexible enough to allow for general specification based on logical interface descriptions, so they may fire for a great
deal of different elements and situations by defining them only once. In this example, the information that the system updates by means of the previous rule is:
```
Assert {
FieldSet(3) has changed its position
Context {
From Form(1) => FieldSet(3) 1
To Form(1) => FieldSet(1) 2
Contents (Button(1), Button(2)) 3
Above {FieldSet(2), FieldSet(1), Text(1), Image(1)} 4
Below {null} 5
}
(user (user_name)) 6
(platform (platform_name)) 7
}
```
This information refers mainly to the fact that a Fieldset has changed its position for a given user and platform, reflecting (1) which concrete composition operator is involved in the change (a FieldSet in a Form), (2) what concrete composition operators it has been changed to. Likewise, the fact indicates also the elements (3) inside the Fieldset: Button(1) which is the Reset button and Button(2) which is the Submit button, (4) the list of the concrete interactors positioned above before the change, (5) the list of the concrete interactors positioned below before the change (in this case there was nothing below), and finally the user (6) and the platform (7) involved in this change.
Semantic knowledge is also generated to reflect the presentation context of the change. This information will be generated by a specific rule, fired whenever a syntactic change occurs and the modification is updated in the expert system:
```
Rule {
If update(FieldSet)
Then generate_presentation_context(FieldSet)
}
```
This rule calls a function (generate_presentation_context) that extracts contextual information for the previously modelled syntactic change. One of the principal concerns here is to transform syntactic information already inferred into semantic information. To this end, the corresponding abstract elements are taken into account. This way, by analysing the previous information about the syntactical change on a Fieldset, the information that is finally generated by the previous function at the semantic level can be represented by the following presentation context:
```
Presentation_Context {
(Change_type (Movement))
(from (Relation(FORM), Grouping(FIELDSET))
(to (Relation(FORM), Grouping(FIELDSET))
(Contents (Activator(SUBBUT), Navigator(RESBUT))
(above (Grouping(FIELDSET), Grouping(FIELDSET), Text(TEXT), Description(IMAGE))
(below (null))
}
```
The presentation context is defined in terms of abstract elements that are taken from the abstract description of the page considered. To this end, a key concern is to identify interactors and composition interactors surrounding the change, as well as the relation with the concrete elements for further disambiguation. The function generate_presentation_context also detects (by using syntactic context) what kind of change is performed (movement, deletion, insertion). In this case, the
system has inferred a change that involves a movement from one grouping (the last one) to another one (the first one). The abstract elements moved are an activator and a navigator interactors, and the context (see above) is composed of different composition operators and interactors. This elicited high-level information is useful for the expert level to carry out generalizations that can be applied as customization rules more than once. In general, the semantic level attempts to construct the suitable knowledge for dealing with complex reasoning. In the example “the user seems to prefer the form buttons appearing on the top” can be carried out. This knowledge can be constructed by associating the contextual presentation information with the user change. In order to detect whether a user change corresponds to a certain context, a similarity percentage is calculated in the matching process. Thus, the semantic customization rules are associated with the corresponding presentation contexts.
We have a general function called ContextMatching, which identifies when two different presentation contexts are similar. Let $PC_1$ and $PC_2$ be two different presentation context sets (a set is composed of various interface elements that define the presentation context). $ContextMatching(PC_1,PC_2)$ can be defined as:
$$ContextMatching(\{PC_1,PC_2\}) = \begin{cases}
\text{true} & \text{if} \quad \frac{|PC_1 \cap PC_2| \times 100}{|PC_1 \cup PC_2|} \geq 70\% \\
\text{false} & \text{if} \quad \frac{|PC_1 \cap PC_2| \times 100}{|PC_1 \cup PC_2|} < 70\%
\end{cases}$$
In a nutshell, this heuristic calculates the number of presentation context elements (such as interactors, their positions and attributes) that show differences between one set ($PC_2$) and a reference set ($PC_1$). To this end, a percentage ratio is calculated and afterwards used as a comparative numerical value. We have determined that a 70% of similarity is enough to consider that the current presentation context matches the reference presentation one, which is associated with a customization rule. This is an empirical threshold that we have estimated by analyzing different examples and cases of use, and it has shown to work well in most of the cases that we have addressed. Initially, we considered a 50% threshold, which was quite a risky percentage for a great deal of the experiments we made.
Though it cannot be considered exhaustive, the matching operator provides a good heuristic in order to obtain a useful numerical result for comparing different contexts and identifying possible similarities.
Figure 6 shows an example, where two different presentation contexts ($PCA$ and $PCB$) are compared with a reference context ($RC$) which may be extracted from the knowledge base; presentation contexts can be stored in the knowledge base as any other knowledge and thus they can even be created by designers. The results from the comparison are 91% coincidence for the first case and 82% for the second, which is sufficient to state a similarity of contexts. The first example (on the left) is the example of a previously presented form. The second example (on the right) is another presentation containing a Web form with different object distribution. In this case, the reference for comparison is a form-like context that can be represented by the logical descriptions appearing inside the dotted-square (denoted by $RC$) in Figure 6. In comparing both presentation contexts, a set $\mathcal{I}$ is calculated. It represents the following information:
$$\mathcal{I} = \{ x \mid x \in PC_2 \lor x \not\in PC_1 \}$$
This set contains the elements of PC2 that are not in PC1. In the example in Figure 6, only one element differs significantly in the left Web form (Description(IMAGE)) and two in the right one (Description(IMAGE), Navigator(LINK)). This way, the results of the matching process for PCA and PCB with respect to the reference context RC is:
\[
\text{ContextMatching}(RC, PCA) = \text{true (91\%)}
\]
\[
\text{ContextMatching}(RC, PCB) = \text{true (82\%)}
\]
The results obtained for these presentation contexts (both above 80\% of similarity) imply that changes in moving buttons on the top of the form can be generalized and applied to both contexts by the same expert rule.
\[
\begin{align*}
|RC \cap PCA| &= 10 \text{ Elements} \\
10/100 &= 91\% \\
|RC \cup PCA| &= 11 \text{ Elements} \\
09/100 &= 82\% \\
\end{align*}
\]
Figure 6. Matching process for detecting presentation context similarities in two different presentations. The contexts to compare (PCA and PCB) are showed, as well as the process of identifying similarity.
All this knowledge can be used afterwards in order to define future semantic customization rules. This way, if a semantic customization rule is fired by the expert system a certain number of times (3 or more, in this case), this rule will be active whenever a form is generated for this user and for the platform s/he is using for navigating through the application. In order to apply the rule correctly, the contextual presentation information will be considered.
This way the semantic customization rule can be specified as:
```
Semantic_Customization_Rule(element, current_context) {
If Change(element)
And
```
16
This customization rule drives the modifications of the Web pages for future access. It is specified in the user profile and can be activated or deactivated by using the NOTORIOUS application.
The advantage of using presentation context becomes evident when expert rules, as the previously discussed, need to be defined. Since presentation contexts are constructed from the first levels of the knowledge structure, semantic customization rules can be defined using abstract and domain-independent concepts, mostly focusing on what the rule is expected to consider a concrete context:
\[
\text{IF} \quad \text{ChangeN Occurs In ContextM} \\
\text{THEN} \quad \text{Act like this: ...}
\]
Not all the expert rules need presentation context to be considered. Some syntactic customization rules can be constructed using only syntactical information, dealing with concrete interactors and concrete composition operators. They concern changes to attributes such as font colour, font size, background colour and so on. These changes will be modelled in the system as described above, but in this case, presentation context is no longer needed. This way we can define flexible syntactic customization rules, taking into account concrete user-interface information and syntactic context previously generated by the system:
\[
\text{Syntactic Customization Rule(element) } \{ \\
\quad \text{If} \quad \text{Change(element)} \\
\quad \text{Then} \\
\quad \quad \text{element will be considered for customizing future nomadic applications}
\}
\]
### 6. User Evaluation and Discussion
In order to receive some empirical feedback for the method proposed, we have carried out a user evaluation. Concretely, the principal objectives of the evaluation were:
- Test the system with real users.
- Evaluate the rules programmed and how they reacted.
- Analyse user interactions and detect meaningful customizations and expert rule activations.
- Populate the expert system with new knowledge to be considered in future user sessions.
In the test, we used an existing Web application generated by the TERESA tool (Mori et al., 2004). The application consisted of several pages about The Marble Museum of Carrara. We asked users to modify the museum application in order to express their preferences, and then analyse the response from our intelligent environment.
6.1 The example used
The Marble Museum of Carrara is a nomadic application. Different versions have been generated for different platforms (mobile, PDA, voice, desktop) through a model-based environment. Although our approach supports different platforms, we based our user test on evaluating the desktop version of the application as the most common platform used by end-users. On the other hand, the desktop platform allows end-users to carry out more expressive modifications, which can provide useful information for customization. The structure of the test Web site includes the typical navigation and presentation structure of many Web pages. The museum site is a large application with hundreds of pages, but during the test users needed to access only a part of it.
Figure 7 shows some screenshots of the museum application for a desktop platform. These pages include a great variety of interface components that can be used to infer syntactic and semantic changes and to automatically activate expert rules. Presentation elements and their corresponding types are described in Table 1.
<table>
<thead>
<tr>
<th>Abstract</th>
<th>Concrete</th>
</tr>
</thead>
<tbody>
<tr>
<td>Interactors</td>
<td></td>
</tr>
<tr>
<td>Descriptions</td>
<td>Images</td>
</tr>
<tr>
<td>Navigators</td>
<td>Links and Buttons</td>
</tr>
<tr>
<td>Texts</td>
<td>Files</td>
</tr>
<tr>
<td>Text and Numerical Edits</td>
<td>Text Fields</td>
</tr>
<tr>
<td>Single Selections</td>
<td>Radio Buttons and Lists</td>
</tr>
<tr>
<td>Activators</td>
<td>Reset Buttons</td>
</tr>
<tr>
<td>Composition Operators</td>
<td></td>
</tr>
<tr>
<td>Groupings</td>
<td>FieldSets and Columns</td>
</tr>
<tr>
<td>Relations</td>
<td>Forms</td>
</tr>
</tbody>
</table>
Table 1. Abstract and concrete elements included in the desktop museum application that are grouped into interactors and composition operators.
As indicated in previous sections, abstract and concrete elements are used to setup the knowledge base and create facts and rules that react to user modifications. Such different semantic levels are useful to distinguish between semantic and syntactical changes.
Figure 7. Some screenshots of the museum application used for the user evaluation.
Considering the application and, more concretely, the conceptual levels of the interface elements depicted in Table 1, the expert system contained different kinds of expert rules that can be divided into syntactic and semantic customization rules. In particular, the expert rules specified for the user evaluation can be summarized as follows:
- **Syntactic customization rules**
- Concrete interactors
- Detecting text font colour and size preferences
- Detecting image attribute preferences
- Detecting background colour preferences
- Detecting button attribute preferences
- Detecting attribute preferences on links and graphical links
- Concrete composition operators
- Detecting form attribute preferences
- Detecting Fieldset attribute preferences
- Detecting column attribute preferences
- **Semantic customization rules**
- Interactors
- Detecting transformations of different kinds of interactors
- Detecting deletions of interactors inside a grouping
- Detecting insertion of interactors inside a grouping
- Composition operators
- Detecting transformation of different kinds of composition operators
- Detecting movement of interactors from one composition operator into another
- Detecting hierarchy preferences
- Detecting ordering preferences
Detecting navigational preferences
The expert system included a total of 14 syntactic customization rules and 10 semantic ones that were activated according to the modifications achieved by end-users.
6.2 Experimental procedure
For this user test, we recruited 11 participants from our institute, all of them having heterogeneous scientific backgrounds. Post-study interviews revealed that only 3 participants had strong Web programming experience. The rest of the participants’ experience was limited to navigating, creating and modifying simple Web pages by using diverse Web authoring tools. Participants were 4 females and 7 males with ages between 25 and 40.
The test was individually performed by each participant in her/his office. It consisted of the following steps:
1) Initially, for about 5 minutes, each user received basic explanations on the system, test goals and the task to accomplish - i.e. providing sample modifications of the desktop version of the museum application in order to indicate their preferences.
2) Then, each user was provided with the URL of the museum application. All participants had unlimited time to navigate through the application and, using the preferred authoring tool available on their computers, made modifications to anything they thought it could be improved.
3) Next, each user uploaded the modified application pages using the NOTORIOUS (Nomadic TailORIng On an end-User Server) environment. A user profile for each user was previously created with the aim of recording the activity and the customization rules inferred. NOTORIOUS is a specialized Web environment through which the user can send modified (X)HTML pages and also access his personal profile to see the changes and manipulate high-level rules inferred by the system. To this end, the user must log in (see Figure 8, screenshot 1). Next, the system presents the personal information and the rules inferred (see Figure 8, screenshot 2). Internally, the back-end of NOTORIOUS generates the UIDs of the original and the modified page, compares them, provides the user with comprehensive feedback and populates the expert system with suitable information about the user’s modifications.
4) Lastly, each user was requested to fill in a questionnaire based on the Perceived Ease of Use (Davis, 1989).
After the user session, the system’s behaviour was analysed using the NOTORIOUS activity logs. In addition, the results from the questionnaire were also processed to compare the outcome of every user session with the user’s perception about the system.
6.3 Results and discussion
Since the test was carried out directly at the computer of each user, one interesting aspect was to see what kind of navigation and Web authoring tools each user used to navigate throughout the Web application and make modifications. Figure 10 shows the percentage rate of (a) navigation and (b) authoring tools used during the test.

**Figure 9.** Navigation (a) and authoring (b) tools used by every user to achieve the test. During the test, users had freedom enough to utilize the tools they preferred.
Some measurements of the duration of the user sessions are presented in Table 2. As shown, the average time was about 25 minutes. We initially estimated the individual total time needed to carry out the modifications in about 30 minutes. In general, the time taken by each user depended on the changes accomplished. While some users decided to
make some in-depth changes affecting the navigational Web structure or moving interactors from one page into another, others considered only some easy changes concerning syntactic modifications to style, colours and so forth.
<table>
<thead>
<tr>
<th></th>
<th>Time in Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Max</td>
<td>38</td>
</tr>
<tr>
<td>Min</td>
<td>16</td>
</tr>
<tr>
<td>Mean</td>
<td>25</td>
</tr>
<tr>
<td>Deviation</td>
<td>8</td>
</tr>
</tbody>
</table>
Table 2. Time spent by users in carrying out the test. Max, Min, Mean and Deviation values are provided in order to have an idea of the time consumed.
During the test, different system outputs were also observed, and a detailed report was additionally obtained from each user session. It was interesting to measure the number of changes made by each user, as well as the response of the expert system in terms of number of facts generated and the number of rules activated in response to the user’s changes. Figure 10 presents the correlation between the number of changes, the facts generated and the rules activated for each user. At first sight, it seems clear that the more changes made the more facts and rules activated. However, this correlation is not always as linear as one could expect, since it mostly depends on the complexity of the changes performed. In the case of user #2, one can see that the number of changes is lower with respect to other users, but the number of facts and rules activated is higher. This is due to the fact that user #2 made a total of 9 changes but all involving complex tasks, that is, moving interactors, changing the navigational structure of the page, transforming composition operators and so on. This produced a high number of facts that had to be specified in terms of syntactic information and semantic presentation context. In addition, the rules that had to deal with such changes were even more complex than trivial syntactic ones, so that a chain of rules was activated. By contrast, users #8 and #11 carried out a high number of changes (23 and 26, respectively) that generated a higher number of facts (57 and 72, respectively) created by the system, as well as a high rate of rule activations (32 and 42, respectively). In these cases, most changes were syntactical, so the response of the system was quite proportional to the type and number of changes carried out by these users. In conclusion, it is possible to affirm that the response of the system is linear as long as the user’s changes do not involve complex structural changes. Anyway, this aspect does not affect our system’s performance and throughput.
Figure 10. The system’s response to user changes. The number of changes, rules activated and facts created is shown for each user.
The activations showed in Figure 10 represent the total rule activations during the user sessions, which means that they include internal and permanent rule activations. Internal rules are those automatically fired by the system as a consequence of fact and rule chain activations and depend exclusively on the expert system. To have a clear idea about what kind of rules have been activated, it can be useful to compare for each user the number of both pending and permanent rule activations. Figure 11 shows such information, where internal rule activations have been omitted and only the ratios of pending and permanent expert rule activations have been considered. As explained in previous sections, the permanent rules are those that have been triggered more than twice, whereas the pending rules are those that have been identified at least once but less than three times. As explained, expert rules involve both syntactic and semantic customization rules. It is worth noting in Figure 10 that most expert rule activations correspond to pending syntactic customization rules associated with syntactical changes. These activations trigger permanent customization rules only when they are fired more than twice. Additionally, there were activations of pending semantic customization rules (for users #1 and #2, basically) that later were turned into permanent preferences.
All pending rules remain in the system as a basic knowledge that will be taken into account for future customization. That is a key point for the system in order to infer similar changes on similar context, which can be useful to detect the same changes on different presentations. In essence, Figure 11 reflects that, although some semantic customization rules have been activated as response to user actions, most user changes concern syntactic modifications that in some cases are transformed into permanent syntactic customizations later on.
Figure 11. Expert rule activation ratio for each user in terms of pending and permanent activations for both syntactic and semantic customization rules.
Figure 12. Number of occurrences of each syntactic customization rule and the kind of change carried out by users during the test for both pending and permanent rules.
Besides the rate of expert rule activations, we also measured the kinds of rules inferred for each user. Figure 12 shows the number of instances (pending and permanent ones) for each of the 14 syntactic customization rules. It is worth noting in Figure 12 that the rules most often activated were those concerning “text size” and “text style”. These two rules had a high rate of both pending and permanent instances. The number of permanent activations for some syntactic customization rules such as “Fieldset colour”, “text colour” and “text help addition” was higher than for the pending ones.
Figure 13. Number of activations of each semantic customization rule and the kind of change carried out by users during the test for both pending and permanent rule activation.
On the other hand, Figure 13 shows the activations for different semantic customization rules, which are less than the syntactic ones. In this case, the higher rate corresponds to the semantic customization rules concerning “grouping add-on”, used to detect when the user decides to insert or create new interactors in a grouping of interactors. Grouping transformations have also been detected by our system, in a lower rate. As shown in Figure 13, only a couple of pending semantic customization rules has been turned into permanent ones. As for the rest of the semantic customization rules, only pending activations have been detected.
Generally speaking, the number of syntactic customization rules greatly overcomes the number of semantic ones. This is due to the fact that syntactical aspects are easier to modify and have an immediate impact on the user’s perception. Concretely, this fact reflects that most changes made by users were related to syntactic modifications such as changing font style, size, colour, text justification, and so on. Figure 14 shows that 80% of activations corresponded to syntactic customization rules and only 20% to semantic ones. As for the syntactic customization rule activations, 64% were considered pending whereas only 36% were permanent. With respect to semantic customization rules, only 9% of activations were permanent and by contrast 91% were pending.
The results obtained from the system for each user helped us evaluate what changes were considered relevant as well as to detect meaningful preferences to populate the expert system with domain-independent customizations. In addition to these outcomes, the perception of the user was also considered in order to have feedback regarding the ease of use of the environment. To this end, we requested each user to fill in a questionnaire to evaluate the perceived ease of use of our system. The questionnaire consisted of 6 questions targeted at evaluating the ease of use. The range of the answers were from 1 to 7, that is, 1) Absolutely Disagree, 2) Disagree, 3) Not Very Agree, 4) Indifferent, 5) Agree, 6) Very Agree, 7) Absolutely Agree and NA (No Answer). Additionally, the questionnaire comprises a free-answer part where the user can freely express other issues related to the system and the test.
Table 3 summarizes the result obtained for the evaluation of the perceived ease of use of the system. In general terms, users found the explicit mechanisms simple in comparison to the support that the system provides. Opinions extracted from the questionnaire denoted how users perceived the implicit expressiveness in modifying a great deal of Web pages using any authoring tool available and then easily uploading them into a system that produces customizations automatically. Additionally, diverse opinions collected from the free-answer part of the questionnaire revealed useful areas of applications for the approach, suggesting the idea of applying the system to tedious daily user tasks such as automatically modifying Web sites and blogs just making minimal changes to a couple of pages. In this regard, end-users found useful the feature by which the system obtains meaningful preferences that will be applied automatically later on in the design of other similar applications.
Learning to operate the system would be easy for me
<table>
<thead>
<tr>
<th>Question</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>NA</th>
</tr>
</thead>
<tbody>
<tr>
<td>Learning to operate the system would be easy for me</td>
<td>0%</td>
<td>0%</td>
<td>0%</td>
<td>9%</td>
<td>27%</td>
<td>9%</td>
<td>55%</td>
<td>0%</td>
</tr>
<tr>
<td>I would find it easy to get the system to do what I want it to do</td>
<td>0%</td>
<td>0%</td>
<td>0%</td>
<td>27%</td>
<td>0%</td>
<td>55%</td>
<td>18%</td>
<td>0%</td>
</tr>
<tr>
<td>My interaction with the system would be clear and understandable</td>
<td>0%</td>
<td>0%</td>
<td>0%</td>
<td>10%</td>
<td>20%</td>
<td>30%</td>
<td>40%</td>
<td>0%</td>
</tr>
<tr>
<td>I would find the system to be flexible to interact with</td>
<td>0%</td>
<td>0%</td>
<td>9%</td>
<td>0%</td>
<td>27%</td>
<td>27%</td>
<td>37%</td>
<td>0%</td>
</tr>
<tr>
<td>It would be easy for me to become skilful at using the system</td>
<td>0%</td>
<td>0%</td>
<td>0%</td>
<td>9%</td>
<td>18%</td>
<td>36%</td>
<td>37%</td>
<td>0%</td>
</tr>
<tr>
<td>I would find the system easy to use</td>
<td>0%</td>
<td>0%</td>
<td>0%</td>
<td>9%</td>
<td>27%</td>
<td>27%</td>
<td>37%</td>
<td>0%</td>
</tr>
</tbody>
</table>
Table 3. The users’ perceived ease of use was analysed by taking into account the questionnaire filled in after the experiment. Answers ranged from 1 (absolutely disagree) to 7 (absolutely agree) and NA (no answer).
In essence, the results obtained from this questionnaire fulfil our expectations. They provided us with positive empirical feedback indicating that it is possible to reduce the complexity of customization and reach a trade-off between expressiveness and easy of use in end-user development mechanisms.
7. Conclusions
Customization of software artefacts is everyday more a common practice carried out by end-users in their daily activities (Klann, 2003). However, such practices require the accomplishment of tasks that are too difficult complex for most end-users. This is mainly due to the fact that authoring environments require manipulating programming languages and abstract specifications, as it occurs when customizing interactive applications.
An interesting study by Rode and Rosson (2003) revealed that although much progress has been made by commercial development tools, most of the tools that they reviewed did not lack functionality but rather ease of use. Rode and Rosson explored many different paths, including extensions to development tool s, finding the inflexibility in controlling the users’ workflow as the main hindrance to adopting these approaches. Currently, none of the commercial tools that they reviewed would work without major problems for the non-professional Web developer.
Commercial applications generally lack support to carry out customization of Web applications. Several researchers have sought to reduce the learning burden by creating design environments that do not require users to program per se. Rather, they design by instructing the machine to learn from examples (Lieberman, 2001) or by interacting with graphical micro worlds representing real domains. Our approach follows such guidelines and supports an easy mechanism based on Programming by Example techniques, where the user provides the system with changes (example of what s/he want to change) and the system generates customizations that will be applied automatically to the pages available for future access, thus minimizing the amount of authoring needed. Instead of enforcing end-users to make use of programming languages and complex specifications, our system carries out Web customization.
automatically by extracting meaningful information from the user’s changes that will be stored in a profile and used to support future sessions.
We populate the knowledge base using logical user interface descriptions that provide domain-independent information, which can be applied to other applications. Often, expert systems are traditionally used to work on concrete problems, since knowledge is created considering information of a specific domain. We overcome such limitation using different levels of knowledge, creating mappings between them and the conceptual levels associated with the user interface (Puerta and Eisenstein, 1999). This allows our intelligent environment to carry out inference at different levels of abstraction (syntactic, semantic), activating rules and populating the expert system with different knowledge depending on the changes that the user accomplishes.
We have carried out a first user test, which has provided us with useful information to analyse the real behaviour of the intelligent system. For example, it was interesting to observe that most of the users’ changes were syntactic, rather than semantic. However, semantic rules imply deeper modifications of the application, in particular to the tasks supported and how to accomplish them. Even if they may be less frequent than syntactic modifications, they can be very important for end users whenever they do not feel that the semantics of the application is satisfactory. Additionally, pending and permanent rule activations helped us check the suitability of the knowledge structure proposed for our intelligent approach, taking into account the user’s changes and analysing the way the system reacted to them. After the experiment, we informally presented the rules to the users with the aim of corroborating whether the inferred knowledge corresponds to their customization preferences or not. However, this knowledge was not applied to other Web applications, although the information reported, together with the questionnaire filled in by users, provided positive feedback regarding users’ expectation and ease of use.
Although the intelligent mechanism here proposed is general enough for any kind of platform, for this first user study only desktop applications were considered. Since desktop computers are likely to be available at the user’s commonplace work places, most end-users prefer desktop platforms to work and carry out authoring tasks. On the other hand, desktop authoring allows users to carry out far more expressive modifications that can provide further information regarding the authoring process. Nevertheless, modifying a mobile or PDA Web application by our system is certainly possible as long as there is an existing authoring tool to achieve such a task. The procedure is quite the same, since the user only has to make the changes and then send them to the server in order to be processed by our system. Modifying a mobile or PDA Web application from a desktop navigator is also possible, but probably this is such a less common task.
In our system, inferred information can be used to activate more general rules that can be triggered when the same modifications occur for more than one user. For example, it is possible to define general rules such as “If activation X is converted from pending into permanent for at least N users, then this rule can be included in every user profile as a general preference”. This information is easy to obtain by our approach, since the expert system can be regarded as a database where new knowledge can be added and queries can be executed in order to mine the desired information from the knowledge stored. Additionally, other expert rules can be defined to detect problems concerning page design. For instance, it is possible to specify rules for detecting whether a change to a concrete element is carried out many times by different users, which could imply that some design problem may exist.
With regard to future work, we expect to improve the front-end part of our tool (i.e. our user interface) further. So far, NOTORIOUS enables end-users to see changes and switch on and off rule activation with the aim of being applied (or not) in future sessions. However, pending rules are turned into permanent only by the system whenever they have been detected at least three times depending on user modifications. Users cannot control the inference directly. Instead, the system carries out the best inference possible. A new improvement could consist of making rather interactive the inference process with respect to the possibility of allowing users to explicitly control rule transformations. Additionally, we plan to improve the system to detect more sophisticated customization cases, using the information already available in our expert system. This way, we expect to create general rules able to identify complex design problems that can be fixed automatically. In addition, an interesting add-on would consist in providing a specific tool for allowing users to easily author rules in our knowledge base. We also plan to carry out more in-depth tests on other Web applications by exploiting the previous inferred knowledge and including users interacting with other platforms (PDA, mobile, etc.).
Acknowledgements
The work reported in this paper is supported by the European Training Network ADVISES (Analysis Design and Validation of Interactive Safety-critical and Error-tolerant Systems), funded through the European Commission. Project number EU HPRN-CT-2002-00288.
References
|
{"Source-Url": "https://repositorio.uam.es/bitstream/handle/10486/667452/customization_macias_IwC_2008_ps.pdf;jsessionid=F253B760AFE2BF2C7EB1D49E55A4C8A9?sequence=3", "len_cl100k_base": 14473, "olmocr-version": "0.1.49", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 108180, "total-output-tokens": 17015, "length": "2e13", "weborganizer": {"__label__adult": 0.0002727508544921875, "__label__art_design": 0.000934123992919922, "__label__crime_law": 0.0002061128616333008, "__label__education_jobs": 0.001931190490722656, "__label__entertainment": 8.243322372436523e-05, "__label__fashion_beauty": 0.00014734268188476562, "__label__finance_business": 0.0002052783966064453, "__label__food_dining": 0.0002503395080566406, "__label__games": 0.0004837512969970703, "__label__hardware": 0.0008440017700195312, "__label__health": 0.0003275871276855469, "__label__history": 0.000278472900390625, "__label__home_hobbies": 9.483098983764648e-05, "__label__industrial": 0.00029087066650390625, "__label__literature": 0.0003197193145751953, "__label__politics": 0.00014698505401611328, "__label__religion": 0.0003457069396972656, "__label__science_tech": 0.025787353515625, "__label__social_life": 7.164478302001953e-05, "__label__software": 0.01380157470703125, "__label__software_dev": 0.95263671875, "__label__sports_fitness": 0.00017058849334716797, "__label__transportation": 0.0003490447998046875, "__label__travel": 0.00017070770263671875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 77565, 0.0234]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 77565, 0.54524]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 77565, 0.91349]], "google_gemma-3-12b-it_contains_pii": [[0, 421, false], [421, 3008, null], [3008, 7067, null], [7067, 10792, null], [10792, 14768, null], [14768, 17532, null], [17532, 19056, null], [19056, 21154, null], [21154, 24896, null], [24896, 27040, null], [27040, 29787, null], [29787, 33392, null], [33392, 35778, null], [35778, 37357, null], [37357, 40279, null], [40279, 43895, null], [43895, 45560, null], [45560, 47911, null], [47911, 50150, null], [50150, 51564, null], [51564, 54135, null], [54135, 55062, null], [55062, 57636, null], [57636, 59692, null], [59692, 60611, null], [60611, 62191, null], [62191, 64083, null], [64083, 67347, null], [67347, 71317, null], [71317, 74723, null], [74723, 77565, null]], "google_gemma-3-12b-it_is_public_document": [[0, 421, true], [421, 3008, null], [3008, 7067, null], [7067, 10792, null], [10792, 14768, null], [14768, 17532, null], [17532, 19056, null], [19056, 21154, null], [21154, 24896, null], [24896, 27040, null], [27040, 29787, null], [29787, 33392, null], [33392, 35778, null], [35778, 37357, null], [37357, 40279, null], [40279, 43895, null], [43895, 45560, null], [45560, 47911, null], [47911, 50150, null], [50150, 51564, null], [51564, 54135, null], [54135, 55062, null], [55062, 57636, null], [57636, 59692, null], [59692, 60611, null], [60611, 62191, null], [62191, 64083, null], [64083, 67347, null], [67347, 71317, null], [71317, 74723, null], [74723, 77565, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 77565, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 77565, null]], "pdf_page_numbers": [[0, 421, 1], [421, 3008, 2], [3008, 7067, 3], [7067, 10792, 4], [10792, 14768, 5], [14768, 17532, 6], [17532, 19056, 7], [19056, 21154, 8], [21154, 24896, 9], [24896, 27040, 10], [27040, 29787, 11], [29787, 33392, 12], [33392, 35778, 13], [35778, 37357, 14], [37357, 40279, 15], [40279, 43895, 16], [43895, 45560, 17], [45560, 47911, 18], [47911, 50150, 19], [50150, 51564, 20], [51564, 54135, 21], [54135, 55062, 22], [55062, 57636, 23], [57636, 59692, 24], [59692, 60611, 25], [60611, 62191, 26], [62191, 64083, 27], [64083, 67347, 28], [67347, 71317, 29], [71317, 74723, 30], [74723, 77565, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 77565, 0.08414]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
0206945ca6b3b58627069cd507b430d4cda3f6fa
|
IMPROVING ISD AGILITY IN FAST-MOVING SOFTWARE ORGANIZATIONS
Research
Persson, John Stouby, Aalborg University, Aalborg, Denmark, john@cs.aau.dk
Nørbjerg, Jacob, Copenhagen Business School, Copenhagen, Denmark, jno.itm@cbs.dk
Nielsen, Peter Axel, Aalborg University, Aalborg, Denmark, pan@cs.aau.dk
Abstract
Fast-moving software organizations must respond quickly to changing technological options and market trends while delivering high-quality services at competitive prices. Improving agility of information systems development (ISD) may reconcile these inherent tensions, but previous research of agility predominantly focused separately on managing either the individual project or the organization. Limited research has investigated the management that ties the agility of individual projects with the company agility characterizing fast-moving organizations. This paper reports an action research study on how to improve ISD agility in a fast-moving software organization. The study maps central problems in the ISD management to direct improvements of agility. Our following intervention addressed method improvements in defining types of ISD by customer relations and integrating the method with the task management tool used by the organization. The paper discusses how the action research contributes to our understanding of ISD agility in fast-moving software organizations with a framework for mapping and evaluating improvements of agility. The action research specifically points out that project managers need to attend to the company’s agility in relating to customers, that company agility links to project agility, and that this requires light method and tool support.
Keywords: Agile ISD, action research, fast-moving software organizations
1 Introduction
Rapid changes in markets and technologies force software organizations to make frequent changes to what they do and how they do it. This is particularly prevalent in the hyper-competitive markets introduced with the Internet boom (Lyytinen et al. 2010). Such software organizations are constantly on the move – not because they find this behaviour particularly attractive, but because their existence depends on constant adaptions to turbulent environments (Holmberg and Mathiassen 2001). The constant adaptive behaviour may also be the organizational objective, conceptualized as strategic flexibility (Hitt et al. 1998), dynamic capabilities (Elsenhardt and Martin 2000), or response ability (Dove 2002). In short, software organizations need to adapt.
Matching the management process to the structure of the company is a central challenge in the small and mid-sized enterprise segment (Turner et al. 2010; Turner et al. 2012) that includes most fast-moving software organizations. Agile methods appear as a solution to information systems development (ISD) managers in fast-moving software organizations. An agile ISD method implies a continual readiness “to rapidly or inherently create change, proactively or reactively embrace change and learn from change while contributing to perceived customer value (economy, quality and simplicity) through its collective components and relationships with its environment” (Conboy 2009). The literature on agile development methods emerged with few links to the literature on organizational agility that characterizes fast-moving software organizations (Mathiassen and Pries-Heje 2006). Fast-moving software organizations with a large number of small diversified projects are, furthermore, at odds with the underlying assumption of ‘one team - one project’ found in agile methods (Larman 2004).
Research has so far focused on how to improve agility of either the project or the company. Limited research has focused on improving agility of the ISD management that ties the agility of individual projects with the organizational agility of the company. Furthermore, it is particularly prudent to help fast-moving software organizations balance their potential for significant economic growth against the persistent risk of failure resulting from constant adaptions. Against this backdrop, we report on an action research study of ISD agility in Adapt, a successful and fast-moving software organization that develops e-commerce solutions based on open-source software. Through action research (Mathiassen 2002) with Adapt, we address the research question:
How can ISD agility be improved in fast-moving software organizations?
We answer the research question based on an analysis of the challenges in our client organization Adapt that we collaboratively addressed, with the aim to improve ISD agility. Our interventions were evaluated with practitioner assessments of how well they addressed the challenges, and theoretically, whether and how the changes contributed to ISD agility. Based on our study, we contribute empirical knowledge on (1) the importance of understanding the company’s environment (2) the linkages between agility of the projects and the company; and (3) the lightness of methods and tools. The paper is structured as follows: The next section presents related research and the theoretical framing for the study. The following section summarizes our action research approach and subsequently, we present an analysis based on our improvement activities of ISD agility with Adapt. Three themes emerged from our analysis and we discuss how they contribute to our understanding of ISD agility in fast-moving software organizations.
2 Related Research
In the following, we present the theoretical foundation for explaining the fast-moving software organization and provide an overview of the research pertaining to ISD agility. The related research helped us understand, guide, and evaluate how the action research interventions contributed to ISD agility in the fast-moving software organization Adapt.
2.1 Fast-Moving Software Organizations
Holmberg and Mathiassen (2001) conceptualized the fast-moving software organization with their lessons on how to cope with a dynamic environment while simultaneously improving professional practices. They argued that from an organization’s attempts to deal effectively with its environment, a culture emerges (Schein 1985) that we need to understand in order to improve their practice. The fast-moving software organization can be understood as an agile enterprise that relates more generally to flexible organizations for fast-moving markets (Volberda 1997), strategic flexibility (Hitt et al. 1998), dynamic capabilities (Elsenhart and Martin 2000), and response ability (Dove 2002). In these organizations, agile operations are related to effectively responding to a changing environment while at the same time being productive. This concept of agility arose from flexible and lean manufacturing aiming for economy of scope rather than economy of scale (Dove 2002; Mathiassen and Pries-Heje 2006).
The software organizations in the age of the Internet that need to cope with rapid change (Baskerville et al. 2003; Pries-Heje et al. 2004) exemplify a demand for agility by a new scope of operations. The adoption of Internet technologies and cloud services by software organizations reflect a hyper-competitive environment demanding simultaneous and mutually complementary learning routines (Lyytinen et al. 2010). Baskerville et al. (2011) argue that dramatic changes in the market causes disruption of established practices, experimentation, and process adaptations followed by consolidation of lessons learnt into a new and once again relatively stable software development process. They historically situate early phenomena such as “Internet Speed” and “Internet Time” as pre-agility, which was an early form of agility that does not completely satisfy today’s taxonomies (Conboy 2009), but instead helped to shape them (Baskerville et al. 2011). Today, ISD agility is widely disseminated with references to the Agile Manifesto (Beck et al. 2001) and development methods such as Scrum (Schwaber and Beedle 2002) and Extreme Programming (Beck 1999). The Agile Manifesto (Beck et al. 2001) reflected a reaction to issues in software organizations of rigid processes and tools, comprehensive documentation, contract negotiation, and following a plan. Fast-moving software organizations inevitably put much more value in individuals and interactions, working software, customer collaboration, and responding to change. These organizations may have small and diversified projects with little room for institutionalizing processes (Babb et al. 2014a; Basri and O’Connor 2010; Coleman and O’Connor 2008; Lester et al. 2010; Pedreira et al. 2007; Staples et al. 2007).
Post-agility for ISD may result from the organizational issues created by the boundaries between agile development teams and plan-driven personnel (Baskerville et al. 2011). Post-agile ISD proactively pursue the dual goal of agility and alignment through a diversity of means, for example through method components, and software tools as well as via new ways of organizing, specializing, communicating, and managing relationships. Baskerville et al. (2011) suggests a deep incorporation of agility into all modes of software development such that agile and plan-driven cease to be distinguishable.
2.2 ISD Agility
The body of research into ISD agility focuses on the practices of software developers within agile software development projects (Conboy 2009; Molnar and Nandhakumar 2009; Stacey and Nandhakumar 2008). Several studies compared the recommendations and techniques suggested in an agile method, such as; e.g., Scrum or XP, to the actual practices of the software developers and their managers. The studies demonstrated how agile methods are adapted to local conditions and constraints (Conboy and Fitzgerald 2010), and that many practices such as; e.g., having a customer on site, are omitted or tailored due to the customer’s reluctance to commit the necessary effort or simply the absence of a identifiable customer (Conboy 2009; Hoda et al. 2011; Wang et al. 2012). Other practices such as daily meetings, retrospectives, or pair programming are also frequently omitted or adapted due to time constraints or management preferences (Babb et al. 2014b; Babb et al. 2014a; Hoda et al. 2013; Wang et al. 2012). Agile ISD will in practice mix and match elements from both agile and tradi-
tional methods (Boehm and Turner 2003; Conboy 2009). A project with fixed requirements may, for example, use Sprints and frequent releases to plan and control the project internally, while maintaining a phased and sequential process in the project’s interactions with the customer. The adaptations and adoptions of agile practices with elements from traditional software development methods motivated studies into the breadth and depth of an organization’s adoption of agile methods (Senapathi and Srinivasan 2012; Wang et al. 2012) as well as a debate about when local development and management practices cease to be agile (Conboy 2009; Lyytinen and Rose 2006). It is, however, problematic to assess agility of local practices through comparison with a specific method insofar different agile methods do not agree on which practices are important and may in fact contain contradictory advice (Conboy 2009). Instead, evaluation of the agility of a method, a practice, or a set of practices should be based on a clear definition of the term agility (Conboy 2009).
Based on a literature study of agility in areas other than ISD, Conboy proposes the following definition of ISD method agility emphasizing the core principles of agility of embracing change and providing customer value: “[T]he continual readiness of an ISD method to rapidly or inherently create change, proactively or reactively embrace change and learn from change while contributing to perceived customer value (economy, quality and simplicity) through its collective components and relationships with its environment” (Conboy 2009 p. 340). The definition is translated into a formative taxonomy of ISD Agility (see Table 1) that outlines the goals an ISD method or a part of it must achieve to be agile. The taxonomy has three parts: the first and second parts refer to handling change and contribution to value. The third part emphasizes that an agile method component should be readily available; i.e.: not take too much time to prepare and use. A project plan, for example, is not readily available if it takes too much time to prepare and/or change it.
| 1. To be agile, an ISD method component must contribute to one or more of the following: |
| (i) creation of change |
| (ii) proaction in advance of change |
| (iii) reaction to change |
| (iv) learning from change |
| 2. To be agile, an ISD method component must contribute to one or more of the following, and must not detract from any: |
| (i) perceived economy |
| (ii) perceived quality |
| (iii) perceived simplicity |
| 3. To be agile, an ISD method component must be continually ready, i.e., minimal time and cost to prepare the component for use. |
Conboy (2009) suggests that the taxonomy can be applied to (1) test agility of commercially labelled agile practices, (2) show a practice is not agile in every instance, and (3) identify new agile practices. In this paper, we want to evaluate the results of interventions into the ISD management practices in a fast-moving software organization. We, therefore, use the taxonomy to evaluate the agility of the ISD management improvements that resulted from our action research interventions.
### 3 Research Approach
The research design was based on action research. This is an appropriate research approach when the research question addresses how professional practitioners take action and improve their action in an organization (Davison et al. 2004; Kock 2007; McKay and Marshall 2001). Our action research effort had the purpose of improving ISD agility by addressing the ISD management challenges in a fast-
moving software organization. This was agreed with the client organization as part of establishing the collaboration. The specific action research approach was Collaborative Practice Research (Mathiassen 2002) that assists in connecting the need to understand current practices with the aim to improve them. Collaborative Practice Research was supplemented with six criteria for evaluating action research: roles, documentation, control, usefulness, frameworks, and transferability (Nielsen 2007). Our approach, therefore, covers the same aspects as canonical action research (Davison et al. 2004), but it is more specific on creating useful interventions for professional practitioners to improve practice.
There were three action researchers, all with a background in software development and management, and with documented action research experiences ranging from 8 to 30 years. The action researchers went into the collaboration with an initial knowledge interest to study the company’s agility and how that influenced ISD management. The company went into the collaboration with the researchers to attain an outside view on their current practices and to be assisted in overcoming some key problems they were facing. We conducted the action research over a period of six months through eight activities. These activities follow the structure laid out in (Iversen et al. 2004):
1. Establish agreement between the client organization and the actions researchers (Davison et al. 2004) and the organization of the collaboration (Mathiassen 2002).
2. Problem definition jointly with the client company (Nielsen and Persson 2010).
3. Appreciate the company’s current project management practice in its organizational context using open-ended qualitative interviews (Patton 2005) and analyze the company’s organizational culture (Cameron and Quinn 2011).
4. Diagnose the problems in detail and suggest actions to improve the current practice (Iversen et al. 1999).
5. Take actions to change current practice – these change actions should be iteratively organized to keep pace and direction with the agility of the company (Börjesson and Mathiassen 2005; Börjesson et al. 2006).
6. Evaluate the effects of the intervention against the understanding of the diagnosis and on the backdrop of the company’s agility (step 4).
7. Take supportive action and return to step 5 if the effects are not yet satisfactory.
8. Elicit lessons learned and evaluate against the six action research criteria (Iversen et al. 2004; Nielsen 2007).
All encounters between the action researchers and the company’s professional practitioners were documented through audio recordings, field notes and minutes. The minutes were sent to all participants for commenting. Following each encounter, a debriefing meeting (Spall 1998) was conducted among the action researchers. The premise, inference, and contribution of action research can be composed in different styles (Mathiassen et al. 2012). The premise style of this research is practical and not theoretical as we have investigated how practitioners in Adapt (a fast-moving software organization) can improve ISD agility. The inference style is inductive and not deductive as the arguments are based on data and evidence from the problem-solving where agility were worked with and then subsequently related more directly to a better understanding of the concepts from the research literature. The contribution style we seek is a field study that extends concepts in the literature about ISD agility and fast-moving software organizations.
4 Analysis
Adapt was established in 1998 and develops web-based solutions for both public and private organizations. It is a profitable company maintaining a top credit rating, and with 65 employees (as of March
2015). Their customers include Danish retail businesses of various sizes and companies for which online functionality and visibility is a central part of the business. Adapt has recently migrated from their own proprietary content management system to Drupal. The company considers itself a leader in this technology and is active in the Danish and international Drupal community contributing with code reviews and new modules. Thus, recruiting and keeping Drupal specialists are key priorities in their business strategy.
The software developers and project managers are organized into three functional groups: Project management headed by the chief project manager, back-end development headed by the chief technology officer, and front-end design and development headed by the chief design officer. Developers are divided into teams led by a project manager, and assigned to several projects. Teams are frequently reorganized in order to balance fluctuating resource demands among projects. Developers and architects are self-organizing all operational tasks. The chief project manager divides her time between managing her own projects, resource allocation across projects, and supporting the two less experienced project managers in e.g. weekly coaching sessions. The project managers all have a background in media and communications and had worked with web design prior to coming to Adapt. They had between 1 to 8 years total work experience and had worked between 2 months and 5 years at Adapt. They had general project management experience prior to coming to Adapt, and two of them are certified in project management according to the International Project Management Association Competence Baseline (IPMA ICB). They described their project management training at Adapt as “learning by doing” under the supervision of a more experienced project manager.
There had been several recent changes to the project management group. One experienced project manager had left Adapt in 2013 and two new had been hired between Summer 2013 and February 2014. A newly hired project manager had only been two months at Adapt. Another project manager decided to leave the company and a replacement was hired in the spring of 2014. Adapt has also made numerous movements in response to their market. Some years ago they moved to the Drupal platform and prior to the action research project in February 2014 they initiated other moves: From midsized to large clients; from fixed price projects to long-term time-and-material contracts; from project-orientation to client orientation; numerous new employees – especially among project managers; and creating a subsidiary company for mobile applications.
At the start of the action research project with Adapt, we met a strong, technically competent, and self-managed group of developers several of whom had long company experience. The developers were organized into teams, but the team structure was loose and fluid in order to maintain high group coherence and minimal internal competition among the developers (according to the Chief Technology Officer). The organization’s success and agility was founded on the competences of these developers. They had built the organization’s initial technical platform, but had also – supported by new hires – been key drivers in Adapt’s early and successful move to Drupal. The four project managers struggled with an increasing number of projects, customers, and frequent changes to project types and customer relations. We decided to focus the action research project on the problems of the project managers because they were clearly motivated to changes that would reduce the pressure upon them.
4.1 ISD Management Challenges in Adapt
During the problem diagnosis, we identified three major and current challenges faced by Adapt: (1) diverse project manager roles with different responsibilities, (2) diversified and changing project types, and (3) insufficient, dated, and redundant methods and tools for ISD management.
**Challenge 1:** The project managers were responsible for customer communication, project budget and planning, and task breakdown and completion. They would prioritize development tasks on projects and allocate them to developers on a weekly or bi-weekly basis. The task allocation became increasingly complex as the number of projects grew, and involved frequent negotiations and re-allocation of
developers between project managers. Furthermore, the chief project manager spent considerable time allocating and reallocating developers to projects. The project managers also reported that they were also expected to fill the roles of lead architect, test manager, and tester on projects. These tasks were not allocated to a specific function in Adapt and had, therefore, become part of the project manager’s responsibilities: “Testing is a developer responsibility but they don't do it properly. They need to learn.” (Project manager). The fluid borders between project management and development had worked well in the past, but the least experienced project managers and the chief project manager reported increasing time pressure, and delays: “I don't like tasks that are just lying around. Some were over two years old and nothing had been done because of lack of time. ... I am beginning to do the same. Tasks are allowed to sit.. one month, two months.” (Junior project manager).
**Challenge 2:** Adapt was going through changes to customer relations and project types. A transition from a waterfall type process model with fixed time and budget, towards agile projects in 2013 was accompanied by a general change in customer relations from individual projects towards long-term relationships based on a Service Level Agreement with each customer. The transitions were not completed – and probably will not be for a while because of differences in customer relationships and preferences – so projects could vary across process type (agile vs. waterfall) and customer relationship (project vs. Service Level Agreement) resulting in four different types of projects of varying sizes. The project managers were struggling to understand the differences between these four types and how best to manage each. “[The process] has been stable for several years. But the last year has been chaotic ... Every time I begin to describe the process, things change ... We grow so quickly and get so many new customers who want to work in a new way.” (Chief project manager)
**Challenge 3:** The chief project manager had revised the process descriptions in 2013, but her changes had already been made obsolete by the many changes in the company. “This is a description of Adapt's method. It was made 6 months ago and it is already outdated ” (Chief project manager). The 13-page method description tailored to the company featured checklists and a contingency-based selection of either a traditional or an agile approach. The chief project manager was working on a new process description but it had not been completed due to lack of time. The project managers, therefore, worked with the old descriptions, templates, and checklists in their own way, and there was no common project management practice in Adapt. The project managers used several reporting and support tools for planning, resource allocation, time reporting, and billing, including their own personal spreadsheets. The lack of tool integration resulted in redundant data entry and poor overview of project status and resource allocation. Adapt was beginning to use JIRA for task allocation and tracking, and intended to eventually use the system to support project and resource management – including time reporting – as well. Use of the system for project management was, however, not mandated, nor was there any common guidelines: “We were told to [use JIRA] in our own way ... How does that support the developers and the process? It is far too difficult for someone else to take over from me if I do everything my way instead of everyone doing it the same way.” (Junior project manager)
**JIRA** is an issue tracking system most commonly used for software bug tracking developed by Atlassian Corporation starting in 2002. Its advanced customization features make it suitable for other types of ticketing systems (work orders, help desks, etc.), and project management. These features make **JIRA** useful for managing even large-scale software development (Helming et al. 2009). **Adapt** used an extension for agile systems development (**JIRA Agile**) and described project tasks in terms of Epics and **User Stories**. A **User Story** is a requirement expressed in a few sentences and in a non-technical language (represented as an **Issue** in **JIRA**). An epic captures a large body of work that can be broken down into a number of smaller **User Stories**. The project managers used **JIRA** to manage the development tasks but not the management tasks.
4.2 Intervention at Adapt
Over the cause of the action research project, we came to consider challenges 1 and 2 as conditions for project management in Adapt since the market and environment for the company underwent major changes. The implication of this realization was that the project managers would have to improve their ability to adjust to changes in the company's environment by being flexible and agile. We therefore decided on a concerted effort to address challenge 3 by changing their methods and tools in such a way that they would better support the project managers in their diverse roles and in adapting quickly to changes in their environment, i.e., improve their agility.
On this background, we proposed to the project managers (1) to reformulate their method to better reflect their practice and environment, and (2) to integrate ISD planning and control into JIRA. As a particular thinking behind adapting to the environment, we suggested to define few and clearly distinct types of projects in order to better differentiate their processes to the needs of different customers. The intention was to improve agility by making their ISD management processes more externally oriented while still maintaining a contingency-based approach with a limited scope suitable for small and midsized enterprises. At the same time, they should increase brevity of the method presentation to cater for future changes to their methods in an agile manner. The integration of ISD planning and control into a tool, in this case JIRA, was proposed to consolidate understanding of their activities on a single platform. We specifically proposed they develop templates for ISD management activities for the different project types, and to integrate management tasks with the development tasks. The purpose was to improve agility by making ISD management processes more flexible and maintainable while aligning them with an existing IT infrastructure in the company. The rationality behind these suggestions can all be traced back to how we understand a fast-moving software organization and what agility is in a software company, cf. section 2.
In the action research project, the chief project manager was key in realizing the proposed changes. She stayed committed despite a tremendous growth of customers and employees, which put a very high workload on her shoulders during the intervention. To establish commitment to the changes, we (the action researchers) made a substantial effort in documenting and explaining the challenges in Adapt – not only to the chief project manager but also to all the project managers and to the company at large. In a seminar held with all project managers and the CEO, we illustrated how they could improve their ‘planning of planning’ by better distinguishing between customer relations (in types of ISD) and agile versus traditional ISD management in the method. Based on an analysis of features in JIRA we explained in detail, how to represent project types as templates with preloaded issues corresponding to the essential ISD management tasks. Each task would then contain checklists in the form of sub-tasks.
To initiate the improvement effort, the chief project manager rewrote their ISD management method based on our initial feedback and discussions with her. This new method description was then reviewed and feedback was provided in two iterations. The resulting method description was reduced from 13 to 6 pages. The generic ISD management model with an agile and a traditional variant was changed to three distinct models called Project (2 pages), Service Level Agreement (1 page), and Supporter (1 page). Each model contained a visualization of the process, descriptions of key activities, and a checklist. The remaining 2 pages were respectively an overview of the three approaches and definitions of the 9 roles as customer representative, project manager, lead (developer), developer, information architect, designer, hosting, quality assurance, and coordinator. The chief project manager also made changes to their use of JIRA concurrent with revising the ISD management method. She made specialized use for each of the three ISD types but had not implemented (only planned) templates and checklists at the time we made the final evaluation of the interventions. However, she started using JIRA for managing development resources in conjunction with the tasks, thus abandoning their previous resource management systems. Two out of the four teams made the transition to JIRA while the remaining two were planned to make the transition in the weeks following the evaluation.
4.3 Improving ISD agility
We evaluated the resulting changes at Adapt in two stages: In the first stage, we asked the practitioners at Adapt to assess how well the changes addressed the challenges they were facing. In the second stage, we used the taxonomy of ISD Agility (cf. Table 1) to analyze whether and how the changes contributed to agility in Adapt. We summarize our changes as: (1) define ISD management by customer relations and (2) integrate ISD management with a tool (JIRA).
Evaluation 1: The evaluation took place in an interview with the chief project manager and a seminar with the project managers and the CEO in June 2014. The chief project manager reflects on their preceding problems in relation to (1) define ISD management by customer relations. She points to the increasing technical competencies among their customers resulting in them taking larger management responsibility, which allows ISD to be more iterative and incremental: “We have been running our projects like we only had 15 people in the company and we are close to 60 ... Now we are making teams much more independent – plus we are establishing a shared method. We had a shared method in the past but it was divided in phases and was a regular waterfall. Now our customers have a completely different approach and they are much more competent in running projects. We are facing technical project managers – it is not just somebody from the marketing department running an IT project.” (Chief project manager)
The chief project manager further reflects on the second method improvement of integrating with JIRA. She emphasizes the importance of incrementally developing both their ISD management method and tool because of their fast-moving software company: “We need to develop both our method and its supporting tools. I have mistakenly tried to run with a method and then put in the tools. The problem is that we barely finish before there is a new direction. Now we are doing it leaner with a little bit of method concurrently with a little bit tool and so forth. That has proven to run better the preceding 6 months.” (Chief project manager)
The constantly changing organization made it difficult for project managers to communicate their processes among each other and to the developers in their teams. The scalability of method is thus important to a senior project manager because it can bring stability: “A lot of things are changing and we need to know what to communicate. I think we now have a method that is scalable enough to give us stability even though we continue the growth.” (Senior project manager)
The CEO also expressed satisfaction with the two method improvements in defining ISD management by customer relations and integrating ISD management with JIRA. In particular, he points to their changes in project management tool: “We are now in a position with the right organization and the right tool – and we are about to have the right processes. We didn’t have this earlier: we didn’t have the right organizational structure; we didn’t have the right tools; and thereby also some scruffy processes. The project managers ran their individual tracks with great frustration among many – especially the project participants. This also explains why we had: our own developed [tool]; Rally; Wrike; JIRA in three years ... We have the right structure now.” (CEO)
Evaluation 2: While the practitioners at Adapt are content with the problem solving, our research concern of ISD agility is not evident in their statements. We thus used the lessons from Adapt to evaluate the effect on ISD agility according to Conboy’s (2009) taxonomy (cf. Table 1). To be agile, an ISD method component must (1) contribute to one or more ways of handling change, (2) contribute to economy, quality, or simplicity without detracting from any, and (3) be continually ready for use. The results, summarized in Table 2, show that the changes contributed to agility in all three categories of the taxonomy: (1) handling change, (2) creating perceived value, and (3) continual readiness. The first and second categories require a contribution to at least one subcategory, leaving some empty fields in Table 2 with no identified contribution to agility. Our analysis also shows that the changes contributed to agility of both the projects and the company.
### Taxonomy of Agility (Conboy 2009)
<table>
<thead>
<tr>
<th>(1) Define ISD management by customer relations</th>
<th>(2) Integrate ISD management with a tool (JIRA)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Project</td>
<td>Company</td>
</tr>
<tr>
<td>Company</td>
<td>Project</td>
</tr>
</tbody>
</table>
#### 1. To be agile, an ISD method component must contribute to one or more of the following:
- **(i) creation of change**
- Shared overview of all the tasks and used resources helps act in advance of change.
- **(ii) proaction in advance of change**
- Brief method description contingent upon the overall task, which assumes and allows adjustments with the three ISD types as a shared starting point.
- Customers feeding tasks into JIRA and tracking their progress allows faster discovery and reaction to needs for change.
- Checklists and templates are easier to modify (communicating change) for future projects compared to the previous underused method.
- **(iii) reaction to change**
- Brief method description makes itself easy to change, i.e. adding a new checkpoint or a new type of customer relationship.
- Checklists and templates may support shared codifications of lessons to supplement their predominantly informal learning.
- **(iv) learning from change**
- A shared starting point in the three types helps conceptualize and discuss specific changes among the project managers and to others in the organization.
- The checklist and templates may support shared codifications of lessons to supplement their predominantly informal learning.
#### 2. To be agile, an ISD method component must contribute to one or more of the following, and must not detract from any:
- **(i) perceived economy**
- Time savings in setting up the ISD management environment and in having the developer team and the customers specify, manage, and coordinate tasks.
- Efficient communication and integration of method changes within the ISD types and improved overview of developer resources.
- **(ii) perceived quality**
- The method is tied to the external task rather than an internal focus on an agile versus traditional process. It also depends on and exploits the existing knowledge socialization.
- **(iii) perceived simplicity**
- A method scope that is lowered to their most basic practical needs specific to the different overall ISD tasks.
- The reduced method scope is easier to follow and legitimize additional questions to the experienced project managers.
- Setting up the ISD management tool requires less effort and helps the project manager remembering and tracking her own tasks.
- Setting templates and checklists, JIRA requires some effort but its maintenance is simpler.
#### 3. To be agile, an ISD method component must be continually ready i.e. minimal time and cost to prepare the component for use.
- The reduced method scope is easier to follow and legitimize additional questions to the experienced project managers.
### Table 2 Evaluation of the changes’ contribution to ISD Agility
In Table 2, **Define ISD management by customer relations**, for example, contributes to simplicity in the management of projects by providing a concise ISD management framework. The change also contributes to simplicity for the company based on the specific needs of *Adapt* and their customers, and by providing a common point of reference for the project managers.
Both changes contribute to the ability to react to change in both the projects and the company. A short and simple checklist of management tasks eases adjustments as conditions for changes to the ISD type. The short and simple descriptions are also easy to adjust to changes in *Adapt*’s environment, e.g., a
new type of customer relationship. Integrating ISD management into a tool, in this case JIRA, similarly enables customers and project managers to discover and react to changes, but it also eases the documentation – and use – of changes to checklists and templates. Both changes, furthermore, contribute to learning from change in the company. The reactions to change in the projects are shaped by JIRA, but the explicit ties to the three types of customer relations help the project managers conceptualize and discuss specific changes among each other in general.
Both changes have linkages between the project agility and the company agility in terms of coherence and concurrence. The coherence is the connection and consistency between how a change contributes to agility across project and company. For example, integrate ISD management with a tool (JIRA), contributes to perceived economy by saving time in both the projects and the company (cf. Table 2). The contributions are similar (yet not identical) and connected by being mutually enforcing and dependent on each other. We see such coherence in how the templates produced by the chief project manager reduces the project managers’ effort when setting up new ISD projects, but thereby she also eases her maintenance of the method. The concurrence is the linkages’ temporal dependency. For example, the contributions to perceived economy are emerging at a similar pace for both the projects and the organization. In this case, both the chief project manager and the project managers quickly experience time savings that can increase with the continued commitment of both parties.
5 Discussion
Our initial diagnosis of the challenges in Adapt showed that their existing ISD management approach did not sufficiently incorporate the fast-moving nature of the company. Time pressure, different and changing project types, and divergent practices inhibited the ability of the project managers to handle change in an agile manner. To improve this, we worked with them to develop a clear and simple distinction between types of ISD projects, and brief but comprehensive descriptions of how to manage each type. The descriptions were supported by a tool (in this case JIRA) in the form of checklists for the ISD management tasks. The particular way we have used the concepts, dimensions, and theory underpinning Table 2 has showed how useful the resulting framework is. The resulting framework is summarised in Figure 1.
<table>
<thead>
<tr>
<th>Agility</th>
<th>Define mgt.</th>
<th>Tool support</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Pro.</td>
<td>Comp.</td>
</tr>
<tr>
<td>1. Contribute to:</td>
<td>(i) Create change</td>
<td></td>
</tr>
<tr>
<td></td>
<td>(ii) Proactive</td>
<td></td>
</tr>
<tr>
<td></td>
<td>(iii) React to change</td>
<td></td>
</tr>
<tr>
<td></td>
<td>(iv) Learn from change</td>
<td></td>
</tr>
<tr>
<td>2. Contribute to and not detract from:</td>
<td>(i) Economy</td>
<td></td>
</tr>
<tr>
<td></td>
<td>(ii) Quality</td>
<td></td>
</tr>
<tr>
<td></td>
<td>(iii) Simplicity</td>
<td></td>
</tr>
<tr>
<td>3. Continually ready:</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
1. Map problems
2. Elicit overview
3. Plan improvement
4. Evaluate improvement
*Figure 1: The resulting framework*
The resulting framework on the left in Figure 1 stems partly from (Conboy 2009) and it is also extended with and generalised to the four columns on ‘Define ISD management by relationship with customers’ and ‘Tool support’. The four steps to the right in Figure 1 generalises how we have used the framework. The framework is fundamentally a construct for mapping the specifics of a company’s
agile practices and for utilising this mapping in observing problematic areas, eliciting an overview of the situation in the company, and for planning what will improve the situation. It is also a construct for evaluating to what degree changes have improved agility.
The main contribution of this action research can be found in the usefulness of the framework in Table 2 now generalised into Figure 1. The framework contains the theory of agility found in (Conboy 2009); but it also extends this by establishing the two other dimensions of the framework, i.e., (1) the distinction between defining ISD types based on customer relations and integrating the method with a tool; and (2) the distinction between the projects and the company. While the resulting framework reached its final format in Table 2 during the evaluation, we used all three dimensions as action researchers during all phases of the action research. The three dimensions were useful both separately, as well as when combined. They informed us as action researchers and consequently also the practitioners in Adapt about how to understand the current situation in Adapt and how to proceed with improvement from this mapping and overview. The framework also informed the evaluation of the improvement effort. The framework presented in Table 2 was useful for understanding, action planning, and evaluation of ISD management in Adapt as a fast-moving software organization. Based on this, we suggest that it may be just as useful for other fast-moving software organization wishing to improve ISD agility when we generalise it by removing what is specific to Adapt in Figure 1. In the following, we discuss three specific contributions of the action research using the framework (cf. Figure 1).
**Company environment**: The framework explicitly addresses how a fast-moving software company must relate to its environment; In our case how Adapt needs to be agile in how it relates to its different customers and how the company in differing ways must attend to customer needs. For Adapt this was achieved by defining ISD management by type of customer relation. We worked with Adapt’s project managers to develop clear and simple distinctions between ISD types and guidelines on how to manage each type. As a result, they abandoned their previous distinction between traditional vs. agile projects. The initial aim was to improve agility by making their ISD management processes more externally oriented (Cameron and Quinn 2011) while still maintaining a contingency-based approach (Conboy and Fitzgerald 2010). The external orientation should help the project managers handle the company’s constant adaptions to turbulent environments (Holmberg and Mathiassen 2001) and sharpen their aim for economy of scope rather than economy of scale (Dove 2002; Mathiassen and Pries-Heje 2006). It suggests that company agility as it is described by previous research, and more specifically how a particular company’s environment influences the company, has to be understood by ISD managers. How project managers understand the economy of scope of their company influences ISD and they cannot limit their own scope of attention to merely understanding the goals and conditions of the projects they are managing.
This also relates to the discussion of post agility for ISD and specifically on how it may be accomplished (Baskerville et al. 2011). The framework highlights some practical knowledge on how the dual goal of on the one hand agility and on the other hand alignment (of planning, people, and tasks) can be achieved within relationships in ISD. In our study, the ISD relationships are between developers, project managers, and a fast-moving organization. Specifically we demonstrate an incorporation of agility into the project management such that agile and plan-driven ceases to be distinguishable (Baskerville et al. 2011). The choice between agile and plan-driven methods (Boehm and Turner 2003) was replaced with an increased focus on the external customer relations at Adapt. This change was based on an understanding of the customers, which Adapt currently have or want to have, rather than a theoretical and paradigmatic distinction between agile and plan-driven methods; and they are thus specific to Adapt. This change of focus, we suggest, is a particular way of detailing what (Baskerville et al. 2011) calls alignment by improving the agility of both the projects and the company.
**Linkages between the agility of the projects and the company**: The linkages between the project agility and the company agility are central to explaining the contribution of our changes using the framework. There were linkages between three parts of the agility dimension in Table 2; i.e.; (1) han-
Handling change, (2) creating perceived value, and (3) continual readiness. The finding in this action research study suggests that for ISD management to be effective in a fast-moving software organization they must improve the agility of both the projects and the company.
This finding relates to the taxonomy of ISD agility in (Conboy 2009). The focus in (Conboy 2009) is on the effect of ISD method components or improvements on the agility of individual projects. However, in a fast-moving software organization like *Adapt* the agility of the company is of equal importance. While Conboy (2009) argues that the effect of an ISD method on agility is sensitive to the project context, the taxonomy does not explain the linkages between the agility of the individual project and the agility of the company. In fast-moving software organizations, the agility of the company is both an essential characteristic and a particular challenge (Holmberg and Mathiassen 2001). Thus, our action research in *Adapt* extends Conboy’s (2009) taxonomy by showing that the linkages between agility of the company and the projects are fundamental to ISD agility. Thus, with this finding we address the call for a more holistic view on agility in IS research (Salmela et al. 2015). The implication of this is that ISD managers in fast-moving software companies must *simultaneously* strive to improve agility of the projects and of the company.
**Lightness of methods and tools:** The third theme emerged from working with *Adapt* on improving ISD agility by changing their tool support to better the efficiency and efficacy. The finding is that it was useful for *Adapt* to develop brief but comprehensive descriptions of how to manage each type of ISD that were then included in *JIRA* in the form of checklists for ISD management tasks. This improvement draws on previous research showing that a risk checklist helps software practitioners identify more risks than they would identify without the aid of a checklist (Keil et al. 2008). We transferred this finding of how checklists influence practitioners’ perception and decision making to the general and essential project management tasks in *Adapt*. Furthermore, we reduced the already brief method description from 13 to 6 pages.
Our study contributes in this way to research on configuring ISD methods and tools for a dynamic context. The use of contextual factors to configure the method or process agility for ISD has received substantial research attention (Boehm and Turner 2003; Karlsson and Ågerfalk 2009; Kruchten 2013). However, little research has focused on the agility of managing the configuration activity itself. The combination of agile projects with a stable or slow-moving organization eliminates the need for management agility across both the projects and the company. In fast-moving software organizations, management agility of method and process configurations is a central challenge because their existence depends on constant adaptations to turbulent environments (Holmberg and Mathiassen 2001). Based on this action research study, we suggest that ISD management tools may play a substantial role in the frequent adjustments that are required to keep up with a dynamic environment. Our analysis also supports the principles of agile project management of minimal critical specification, autonomous teams, redundancy and feedback and learning (Dybå et al. 2014). However, we also add the importance of tool support for structured feedback and learning that is not only ‘integral to the project’s execution and the project’s interaction with the environment’ (Dybå et al. 2014 p. 293), but is integral to the fast-moving software company.
6 Conclusion
This paper reported a collaborative action research study of how ISD agility can be improved in fast-moving software organizations. We worked with the fast-moving software organization *Adapt* on two distinct changes intended to improve agility. The first was to define ISD management by customer relations. The second was to integrate ISD management with *JIRA*. The practitioners at *Adapt* assessed that these changes positively affected the challenges they were facing. Second, we used Conboy’s (2009) taxonomy to analyze whether and how the changes contributed to ISD agility. We discuss the contribution of the changes to agility in three general themes for improving ISD agility in fast-moving
software organizations: (1) the importance of understanding the company’s environment (2) the linkages between agility of the projects and the company; and (3) the lightness of methods and tools.
An important limitation of our study is the changing nature of fast-moving software organizations. The frequent moves make it very difficult to establish a current understanding of the organization and evaluate the effects of changes. Every time we met with Adapt in intervals of a few weeks they had made new changes as part of the company’s general problem solving. Thus, organizational moves quickly entangled with the problem solving of the action research project. Interventions in fast-moving software organizations cannot be discretely isolated and evaluated. Our action research ended after six months when we were able to evaluate the changes with the involved practitioners and Conboy’s (2009) taxonomy of ISD agility. While the changes may feed-forward or be adapted yet again to changing circumstances, this concern is outside the scope of our action research project.
The potential of fast-moving software organizations for economic growth, but also the persistent risk of failure from the constant adaptations, underline a need for future research. In these organizations, management of ISD agility appears to be an important element of success. However, we still need to explore different approaches to improving agility across project and company. Specifically, we call for exploration and evaluation of the coherence and concurrence between the agility of the individual projects and the company. The action research reported in this paper shows that agility is a useful measure of success when addressing ISD management challenges in fast-moving software organizations. However, we need more and varied studies to further our understanding of ISD agility improvements.
References
Patton, M. Q. 2005. Qualitative Research, Wiley Online Library.
|
{"Source-Url": "http://vbn.aau.dk/files/235388516/Persson_et_al_2016_Improving_ISD_Agility_in_Fast_Moving_Software_Organizations.pdf", "len_cl100k_base": 10749, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 60917, "total-output-tokens": 14598, "length": "2e13", "weborganizer": {"__label__adult": 0.00040030479431152344, "__label__art_design": 0.0004658699035644531, "__label__crime_law": 0.0003483295440673828, "__label__education_jobs": 0.005535125732421875, "__label__entertainment": 7.623434066772461e-05, "__label__fashion_beauty": 0.0001959800720214844, "__label__finance_business": 0.0023288726806640625, "__label__food_dining": 0.00036215782165527344, "__label__games": 0.00069427490234375, "__label__hardware": 0.00047206878662109375, "__label__health": 0.00045228004455566406, "__label__history": 0.00030231475830078125, "__label__home_hobbies": 0.00010710954666137697, "__label__industrial": 0.0003669261932373047, "__label__literature": 0.00038552284240722656, "__label__politics": 0.00031065940856933594, "__label__religion": 0.0003437995910644531, "__label__science_tech": 0.00667572021484375, "__label__social_life": 0.00012922286987304688, "__label__software": 0.007137298583984375, "__label__software_dev": 0.9716796875, "__label__sports_fitness": 0.0003056526184082031, "__label__transportation": 0.0005183219909667969, "__label__travel": 0.0002378225326538086}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62942, 0.03049]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62942, 0.18535]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62942, 0.9343]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 1765, false], [1765, 5852, null], [5852, 10361, null], [10361, 13965, null], [13965, 17747, null], [17747, 22160, null], [22160, 26690, null], [26690, 31322, null], [31322, 35663, null], [35663, 39517, null], [39517, 42962, null], [42962, 47728, null], [47728, 52153, null], [52153, 56186, null], [56186, 59878, null], [59878, 62942, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 1765, true], [1765, 5852, null], [5852, 10361, null], [10361, 13965, null], [13965, 17747, null], [17747, 22160, null], [22160, 26690, null], [26690, 31322, null], [31322, 35663, null], [35663, 39517, null], [39517, 42962, null], [42962, 47728, null], [47728, 52153, null], [52153, 56186, null], [56186, 59878, null], [59878, 62942, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62942, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62942, null]], "pdf_page_numbers": [[0, 0, 1], [0, 1765, 2], [1765, 5852, 3], [5852, 10361, 4], [10361, 13965, 5], [13965, 17747, 6], [17747, 22160, 7], [22160, 26690, 8], [26690, 31322, 9], [31322, 35663, 10], [35663, 39517, 11], [39517, 42962, 12], [42962, 47728, 13], [47728, 52153, 14], [52153, 56186, 15], [56186, 59878, 16], [59878, 62942, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62942, 0.1269]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
56749ef41e548eb6003bbfee1e291183e8429c3d
|
Chapter from the book *Embedded Systems - Theory and Design Methodology*
Downloaded from: http://www.intechopen.com/books/embedded-systems-theory-and-design-methodology
Interested in publishing with InTechOpen?
Contact us at book.department@intechopen.com
Ways for Implementing Highly-Predictable Embedded Systems Using Time-Triggered Co-Operative (TTC) Architectures
Mouaaz Nahas and Ahmed M. Nahhas
Department of Electrical Engineering, College of Engineering and Islamic Architecture,
Umm Al-Qura University, Makkah,
Saudi Arabia
1. Introduction
Embedded system is a special-purpose computer system which is designed to perform a small number of dedicated functions for a specific application (Sachitanand, 2002; Kamal, 2003). Examples of applications using embedded systems are: microwave ovens, TVs, VCRs, DVDs, mobile phones, MP3 players, washing machines, air conditions, handheld calculators, printers, digital watches, digital cameras, automatic teller machines (ATMs) and medical equipments (Barr, 1999; Bolton, 2000; Fisher et al., 2004; Pop et al., 2004). Besides these applications, which can be viewed as “noncritical” systems, embedded technology has also been used to develop “safety-critical” systems where failures can have very serious impacts on human safety. Examples include aerospace, automotive, railway, military and medical applications (Redmill, 1992; Profeta et al., 1996; Storey, 1996; Konrad et al., 2004).
The utilization of embedded systems in safety-critical applications requires that the system should have real-time operations to achieve correct functionality and/or avoid any possibility for detrimental consequences. Real-time behavior can only be achieved if the system is able to perform predictable and deterministic processing (Stankovic, 1988; Pont, 2001; Buttazzo, 2005; Phatrapornnant, 2007). As a result, the correct behavior of a real-time system depends on the time at which these results are produced as well as the logical correctness of the output results (Avrunin et al., 1998; Kopetz, 1997). In real-time embedded applications, it is important to predict the timing behavior of the system to guarantee that the system will behave correctly and consequently the life of the people using the system will be saved. Hence, predictability is the key characteristic in real-time embedded systems.
Embedded systems engineers are concerned with all aspects of the system development including hardware and software engineering. Therefore, activities such as specification, design, implementation, validation, deployment and maintenance will all be involved in the development of an embedded application (Fig. 1). A design of any system usually starts with ideas in people’s mind. These ideas need to be captured in requirements specification documents that specify the basic functions and the desirable features of the system. The system design process then determines how these functions can be provided by the system components.
For successful design, the system requirements have to be expressed and documented in a very clear way. Inevitably, there can be numerous ways in which the requirements for a simple system can be described.
Once the system requirements have been clearly defined and well documented, the first step in the design process is to design the overall system architecture. Architecture of a system basically represents an overview of the system components (i.e. sub-systems) and the interrelationships between these different components. Once the software architecture is identified, the process of implementing that architecture should take place. This can be achieved using a lower-level system representation such as an operating system or a scheduler. Scheduler is a very simple operating system for an embedded application (Pont, 2001). Building the scheduler would require a scheduling algorithm which simply provides the set of rules that determine the order in which the tasks will be executed by the scheduler during the system operating time. It is therefore the most important factor which influences predictability in the system, as it is responsible for satisfying timing and resource requirements (Buttazzo, 2005). However, the actual implementation of the scheduling algorithm on the embedded microcontroller has an important role in determining the functional and temporal behavior of the embedded system.
This chapter is mainly concerned with so-called “Time-Triggered Co-operative” (TTC) schedulers and how such algorithms can be implemented in highly-predictable, resource-constrained embedded applications.
The layout of the chapter is as follows. Section 2 provides a detailed comparison between the two key software architectures used in the design of real-time embedded systems, namely "time-triggered" and "event-triggered". Section 3 introduces and compares the two most known scheduling policies, "co-operative" and "pre-emptive", and highlights the advantages of co-operative over pre-emptive scheduling. Section 4 discusses the relationship between scheduling algorithms and scheduler implementations in practical embedded systems. In Section 5, Time-Triggered Co-operative (TTC) scheduling algorithm is introduced in detail with a particular focus on its strengths and drawbacks and how such drawbacks can be addressed to maintain its reliability and predictability attributes. Section 6 discusses the sources and impact of timing jitter in TTC scheduling algorithm. Section 7 describes various possible ways in which the TTC scheduling algorithm can be implemented on resource-constrained embedded systems that require highly-predictable system behavior. In Section 8, the various scheduler implementations are compared and contrasted in terms of jitter characteristics, error handling capabilities and resource requirements. The overall chapter conclusions are presented in Section 9.
2. Software architectures of embedded systems
Embedded systems are composed of hardware and software components. The success of an embedded design, thus, depends on the right selection of the hardware platform(s) as well
as the software environment used in conjunction with the hardware. The selection of hardware and software architectures of an application must take place at early stages in the development process (typically at the design phase). Hardware architecture relates mainly to the type of the processor (or microcontroller) platform(s) used and the structure of the various hardware components that are comprised in the system; see Mwelwa (2006) for further discussion about hardware architectures for embedded systems.
Provided that the hardware architecture is decided, an embedded application requires an appropriate form of software architecture to be implemented. To determine the most appropriate choice for software architecture in a particular system, this condition must be fulfilled (Locke, 1992): “The [software] architecture must be capable of providing a provable prediction of the ability of the application design to meet all of its time constraints.”
Since embedded systems are usually implemented as collections of real-time tasks, the various possible system architectures may then be determined by the characteristics of these tasks. In general, there are two main software architectures which are typically used in the design of embedded systems:
**Event-triggered (ET):** tasks are invoked as a response to aperiodic events. In this case, the system takes no account of time: instead, the system is controlled purely by the response to external events, typically represented by interrupts which can arrive at anytime (Bannatyne, 1998; Kopetz, 1991b). Generally, ET solution is recommended for applications in which sporadic data messages (with unknown request times) are exchanged in the system (Hsieh and Hsu, 2005).
**Time-triggered (TT):** tasks are invoked periodically at specific time intervals which are known in advance. The system is usually driven by a global clock which is linked to a hardware timer that overflows at specific time instants to generate periodic interrupts (Bennett, 1994). In distributed systems, where multi-processor hardware architecture is used, the global clock is distributed across the network (via the communication medium) to synchronise the local time base of all processors. In such architectures, time-triggering mechanism is based on time-division multiple access (TDMA) in which each processor-node is allocated a periodic time slot to broadcast its periodic messages (Kopetz, 1991b). TT solution can suit many control applications where the data messages exchanged in the system are periodic (Kopetz, 1997).
Many researchers argue that ET architectures are highly flexible and can provide high resource efficiency (Obermaisser, 2004; Locke, 1992). However, ET architectures allow several interrupts to arrive at the same time, where these interrupts might indicate (for example) that two different faults have been detected at the same time. Inevitably, dealing with an occurrence of several events at the same time will increase the system complexity and reduce the ability to predict the behavior of the ET system (Scheler and Schröder-Preikschat, 2006). In more severe circumstances, the system may fail completely if it is heavily loaded with events that occur at once (Marti, 2002). In contrast, using TT architectures helps to ensure that only a single event is handled at a time and therefore the behavior of the system can be highly-predictable.
Since highly-predictable system behavior is an important design requirement for many embedded systems, TT software architectures have become the subject of considerable attention (e.g. see Kopetz, 1997). In particular, it has been widely accepted that TT
architectures are a good match for many safety-critical applications, since they can help to improve the overall safety and reliability (Allworth, 1981; Storey, 1996; Nissanke, 1997; Bates; 2000; Obermaisser, 2004). Liu (2000) highlights that TT systems are easy to validate, test, and certify because the times related to the tasks are deterministic. Detailed comparisons between the TT and ET concepts were performed by Kopetz (1991a and 1991b).
3. Schedulers and scheduling algorithms
Most embedded systems involve several tasks that share the system resources and communicate with one another and/or the environment in which they operate. For many projects, a key challenge is to work out how to schedule tasks so that they can meet their timing constraints. This process requires an appropriate form of scheduler\(^1\). A scheduler can be viewed as a very simple operating system which calls tasks periodically (or aperiodically) during the system operating time. Moreover, as with desktop operating systems, a scheduler has the responsibility to manage the computational and data resources in order to meet all temporal and functional requirements of the system (Mwelwa, 2006).
According to the nature of the operating tasks, any real-time scheduler must fall under one of the following types of scheduling policies:
**Pre-emptive scheduling:** where a multi-tasking process is allowed. In more details, a task with higher priority is allowed to pre-empt (i.e. interrupt) any lower priority task that is currently running. The lower priority task will resume once the higher priority task finishes executing. For example, suppose that – over a particular period of time – a system needs to execute four tasks (Task A, Task B, Task C, Task D) as illustrated in Fig. 2.

Fig. 2. A schematic representation of four tasks which need to be scheduled for execution on a single-processor embedded system (Nahas, 2008).
Assuming a single-processor system is used, Task C and Task D can run as required where Task B is due to execute before Task A is complete. Since no more than one task can run at the same time on a single-processor, Task A or Task B has to relinquish control of the CPU.
\(^1\) Note that schedulers represent the core components of “Real-Time Operating System” (RTOS) kernels. Examples of commercial RTOSs which are used nowadays are: VxWorks (from Wind River), Lynx (from LynxWorks), RTLinux (from FSMLabs), eCos (from Red Hat), and QNX (from QNX Software Systems). Most of these operating systems require large amount of computational and memory resources which are not readily available in low-cost microcontrollers like the ones targeted in this work.
In pre-emptive scheduling, a higher priority might be assigned to Task B with the consequence that – when Task B is due to run – Task A will be interrupted, Task B will run, and Task A will then resume and complete (Fig. 3).
Co-operative (or “non-pre-emptive”) scheduling: where only a single-tasking process is allowed. In more details, if a higher priority task is ready to run while a lower priority task is running, the former task cannot be released until the latter one completes its execution. For example, assume the same set of tasks illustrated in Fig. 2. In the simplest solution, Task A and Task B can be scheduled co-operatively. In these circumstances, the task which is currently using the CPU is implicitly assigned a high priority: any other task must therefore wait until this task relinquishes control before it can execute. In this case, Task A will complete and then Task B will be executed (Fig. 4).
Hybrid scheduling: where a limited, but efficient, multi-tasking capabilities are provided (Pont, 2001). That is, only one task in the whole system is set to be pre-emptive (this task is best viewed as “highest-priority” task), while other tasks are running co-operatively (Fig. 5). In the example shown in the figure, suppose that Task B is a short task which has to execute immediately when it arrives. In this case, Task B is set to be pre-emptive so that it acquires the CPU control to execute whenever it arrives and whether (or not) other task is running.
Overall, when comparing co-operative with pre-emptive schedulers, many researchers have argued that co-operative schedulers have many desirable features, particularly for use in safety-related systems (Allworth, 1981; Ward, 1991; Nissanke, 1997; Bates, 2000; Pont, 2001). For example, Bates (2000) identified the following four advantages of co-operative scheduling over pre-emptive alternatives:
The scheduler is simpler.
The overheads are reduced.
Testing is easier.
Certification authorities tend to support this form of scheduling.
Similarly, Nissanke (1997) noted: “[Pre-emptive] schedules carry greater runtime overheads because of the need for context switching - storage and retrieval of partially computed results. [Co-operative] algorithms do not incur such overheads. Other advantages of co-operative algorithms include their better understandability, greater predictability, ease of testing and their inherent capability for guaranteeing exclusive access to any shared resource or data.”
Many researchers still, however, believe that pre-emptive approaches are more effective than co-operative alternatives (Allworth, 1981; Cooling, 1991). This can be due to different reasons. As in (Pont, 2001), one of the reasons why pre-emptive approaches are more widely discussed and considered is because of confusion over the options available. Pont gave an example that the basic cyclic scheduling, which is often discussed by many as an alternative to pre-emptive, is not a representative of the wide range of co-operative scheduling architectures that are available.
Moreover, one of the main issues that concern people about the reliability of co-operative scheduling is that long tasks can have a negative impact on the responsiveness of the system. This is clearly underlined by Allworth (1981): “[The] main drawback with this co-operative approach is that while the current process is running, the system is not responsive to changes in the environment. Therefore, system processes must be extremely brief if the real-time response of the system is not to be impaired.”
However, in many practical embedded systems, the process (task) duration is extremely short. For example, calculations of one of the very complicated algorithms, the “proportional integral differential” (PID) controller, can be carried out on the most basic (8-bit) 8051 microcontroller in around 0.4 ms: this imposes insignificant processor load in most systems – including flight control – where 10 ms sampling rate is adequate (Pont, 2001). Pont has also commented that if the system is designed to run long tasks, “this is often because the developer is unaware of some simple techniques that can be used to break down these tasks in an appropriate way and – in effect – convert long tasks called infrequently into short tasks called frequently”: some of these techniques are introduced and discussed in Pont (2001).
Moreover, if the performance of the system is seen slightly poor, it is often advised to update the microcontroller hardware rather than to use a more complex software architecture. However, if changing the task design or microcontroller hardware does not provide the level of performance which is desired for a particular application, then more than one microcontroller can be used. In such cases, long tasks can be easily moved to another processor, allowing the host processor to respond rapidly to other events as required (for further details, see Pont, 2001; Ayavoo et al., 2007).
Please note that the very wide use of pre-emptive schedulers can simply be resulted from a poor understanding and, hence, undervaluation of the co-operative schedulers. For example, a co-operative scheduler can be easily constructed using only a few hundred lines of highly portable code written in a high-level programming language (such as ‘C’), while the resulting system is highly-predictable (Pont, 2001).
It is also important to understand that sometimes pre-emptive schedulers are more widely used in RTOSs due to commercial reasons. For example, companies may have commercial benefits from using pre-emptive environments. Consequently, as the complexity of these environments increases, the code size will significantly increase making ‘in-house’ constructions of such environments too complicated. Such complexity factors lead to the sale of commercial RTOS products at high prices (Pont, 2001). Therefore, further academic research has been conducted in this area to explore alternative solutions. For example, over the last few years, the Embedded Systems Laboratory (ESL) researchers have considered various ways in which simple, highly-predictable, non-pre-emptive (co-operative) schedulers can be implemented in low-cost embedded systems.
4. Scheduling algorithm and scheduler implementation
A key component of the scheduler is the scheduling algorithm which basically determines the order in which the tasks will be executed by the scheduler (Buttazzo, 2005). More specifically, a scheduling algorithm is the set of rules that, at every instant while the system is running, determines which task must be allocated the resources to execute.
Developers of embedded systems have proposed various scheduling algorithms that can be used to handle tasks in real-time applications. The selection of appropriate scheduling algorithm for a set of tasks is based upon the capability of the algorithm to satisfy all timing constraints of the tasks: where these constraints are derived from the application requirements. Examples of common scheduling algorithms are: Cyclic Executive (Locke, 1992), Rate Monotonic (Liu & Layland, 1973), Earliest-Deadline-First (Liu & Layland, 1973; Liu, 2000), Least-Laxity-First (Mok, 1983), Deadline Monotonic (Leung, 1982) and Shared-Clock (Pont, 2001) schedulers (see Rao et al., 2008 for a simple classification of scheduling algorithms). This chapter outlines one key example of scheduling algorithms that is widely used in the design of real-time embedded systems when highly-predictable system behavior is an essential requirement: this is the Time Triggered Co-operative scheduler which is a form of cyclic executive.
Note that once the design specifications are converted into appropriate design elements, the system implementation process can take place by translating those designs into software and hardware components. People working on the development of embedded systems are often concerned with the software implementation of the system in which the system specifications are converted into an executable system (Sommerville, 2007; Koch, 1999). For example, Koch interpreted the implementation of a system as the way in which the software program is arranged to meet the system specifications.
The implementation of schedulers is a major problem which faces designers of real-time scheduling systems (for example, see Cho et al., 2005). In their useful publication, Cho and colleagues clarified that the well-known term scheduling is used to describe the process of finding the optimal schedule for a set of real-time tasks, while the term scheduler implementation refers to the process of implementing a physical (software or hardware) scheduler that enforces – at run-time – the task sequencing determined by the designed schedule (Cho et al., 2007).
Generally, it has been argued that there is a wide gap between scheduling theory and its implementation in operating system kernels running on specific hardware, and for any meaningful validation of timing properties of real-time applications, this gap must be bridged (Katcher et al., 1993). The relationship between any scheduling algorithm and the number of possible implementation options for that algorithm – in practical designs – has generally been viewed as ‘one-to-many’, even for very simple systems (Baker & Shaw, 1989; Koch; 1999; Pont, 2001; Baruah, 2006; Pont et al., 2007; Phatrapornnant, 2007). For example, Pont et al. (2007) clearly mentioned that if someone was to use a particular scheduling architecture, then there are many different implementation options which can be available. This claim was also supported by Phatrapornnant (2007) by noting that the TTC scheduler (which is a form of cyclic executive) is only an algorithm where, in practice, there can be many possible ways to implement such an algorithm.
The performance of a real-time system depends crucially on implementation details that cannot be captured at the design level, thus it is more appropriate to evaluate the real-time properties of the system after it is fully implemented (Avrunin et al., 1998).
5. Time-triggered co-operative (TTC) scheduling algorithm
A key defining characteristic of a time-triggered (TT) system is that it can be expected to have highly-predictable patterns of behavior. This means that when a computer system has a time-triggered architecture, it can be determined in advance – before the system begins executing – exactly what the system will do at every moment of time while the system is operating. Based on this definition, completely defined TT behavior is – of course – difficult to achieve in practice. Nonetheless, approximations of this model have been found to be useful in a great many practical systems. The closest approximation of a “perfect” TT architecture which is in widespread use involves a collection of periodic tasks which operate co-operatively (or “non-pre-emptively”). Such a time-triggered co-operative (TTC) architecture has sometimes been described as a cyclic executive (e.g. Baker & Shaw, 1989; Locke, 1992).
According to Baker and Shaw (1989), the cyclic executive scheduler is designed to execute tasks in a sequential order that is defined prior to system activation; the number of tasks is fixed; each task is allocated an execution slot (called a minor cycle or a frame) during which the task executes; the task – once interleaved by the scheduler – can execute until completion without interruption from other tasks; all tasks are periodic and the deadline of each task is equal to its period; the worst-case execution time of all tasks is known; there is no context switching between tasks; and tasks are scheduled in a repetitive cycle called major cycle. The major cycle can be defined as the time period during which each task in the scheduler executes – at least – once and before the whole task execution pattern is repeated. This is numerically calculated as the lowest common multiple (LCM) of the periods of the scheduled tasks (Baker & Shaw, 1989; Xu & Parnas, 1993). Koch (1999) emphasized that cyclic executive is a “proof-by-construction” scheme in which no schedulability analysis is required prior to system construction.
Fig. 6 illustrates the (time-triggered) cyclic executive model for a simple set of four periodic tasks. Note that the final task in the task-group (i.e. Task D) must complete execution before the arrival of the next timer interrupt which launches a new (major) execution cycle.
Ways for Implementing Highly-Predictable Embedded Systems Using Time-Triggered Co-Operative (TTC) Architectures
Fig. 6. A time-triggered cyclic executive model for a set of four periodic tasks (Nahas, 2011b).
In the example shown, each task is executed only once during the whole major cycle which is, in this case, made up of four minor cycles. Note that the task periods may not always be identical as in the example shown in Fig. 6. When task periods vary, the scheduler should define a sequence in which each task is repeated sufficiently to meet its frequency requirement (Locke, 1992).
Fig. 7 shows the general structure of the time-triggered co-operative (i.e. time-triggered co-operative) scheduler. In the example shown in this figure, the scheduler has a minor cycle of 10 ms, period values of 20, 10 and 40 ms for the tasks A, B and C, respectively. The LCM of these periods is 40 ms, therefore the length of the major cycle in which all tasks will be executed periodically is 40 ms. It is suggested that the minor cycle of the scheduler (which is also referred to as the tick interval: see Pont, 2001) can be set equal to or less than the greatest common divisor value of all task periods (Phatrapornnant, 2007). In the example shown in Fig. 7, this value is equal to 10 ms. In practice, the minor cycle is driven by a periodic interrupt generated by the overflow of an on-chip hardware timer or by the arrival of events in the external environment (Locke, 1992; Pont, 2001). The vertical arrows in the figure represent the points at which minor cycles (ticks) start.
Fig. 7. A general structure of the time-triggered co-operative (TTC) scheduler (Nahas, 2008).
Overall, TTC schedulers have many advantages. A key recognizable advantage is its simplicity (Baker & Shaw, 1989; Liu, 2000; Pont, 2001). Furthermore, since pre-emption is not allowed, mechanisms for context switching are, hence, not required and, as a consequence, the run-time overhead of a TTC scheduler can be kept very low (Locke, 1992; Buttazzo, 2005). Also, developing TTC schedulers needs no concern about protecting the integrity of shared data structures or shared resources because, at a time, only one task in the whole
system can exclusively use the resources and the next due task cannot begin its execution until the running task is completed (Baker & Shaw, 1989; Locke, 1992).
Since all tasks are run regularly according to their predefined order in a deterministic manner, the TTC schedulers demonstrate very low levels of task jitter (Locke, 1992; Bate, 1998; Buttazzo, 2005) and can maintain their low-jitter characteristics even when complex techniques, such as dynamic voltage scaling (DVS), are employed to reduce system power consumption (Phatrapornnant & Pont, 2006). Therefore, as would be expected (and unlike RM designs, for example), systems with TTC architectures can have highly-predictable timing behavior (Baker & Shaw, 1989; Locke, 1992). Locke (1992) underlines that with cyclic executive systems, “it is possible to predict the entire future history of the state of the machine, once the start time of the system is determined (usually at power-on). Thus, assuming this future history meets the response requirements generated by the external environment in which the system is to be used, it is clear that all response requirements will be met. Thus it fulfills the basic requirements of a hard real time system.”
Provided that an appropriate implementation is used, TTC architectures can be a good match for a wide range of low-cost embedded applications. For example, previous studies have described – in detail – how these techniques can be applied in various automotive applications (e.g. Ayavoo et al., 2006; Ayavoo, 2006), a wireless (ECG) monitoring system (Phatrapornnant & Pont, 2004; Phatrapornnant, 2007), various control applications (e.g. Edwards et al., 2004; Key et al., 2004; Short & Pont, 2008), and in data acquisition systems, washing-machine control and monitoring of liquid flow rates (Pont, 2002). Outside the ESL group, Nghiem et al. (2006) described an implementation of PID controller using TTC scheduling algorithm and illustrated how such architecture can help increase the overall system performance as compared with alternative implementation methods.
However, TTC architectures have some shortcomings. For example, many researchers argue that running tasks without pre-emption may cause other tasks to wait for some time and hence miss their deadlines. However, the availability of high-speed, COTS microcontrollers nowadays helps to reduce the effect of this problem and, as processor speeds continue to increase, non-pre-emptive scheduling approaches are expected to gain more popularity in the future (Baruah, 2006).
Another issue with TTC systems is that the task schedule is usually calculated based on estimates of Worst Case Execution Time (WCET) of the running tasks. If such estimates prove to be incorrect, this may have a serious impact on the system behavior (Buttazzo, 2005).
One recognized disadvantage of using TTC schedulers is the lack of flexibility (Locke, 1992; Bate, 1998). This is simply because TTC is usually viewed as ‘table-driven’ static scheduler (Baker & Shaw, 1989) which means that any modification or addition of a new functionality, during any stage of the system development process, may need an entirely new schedule to be designed and constructed (Locke, 1992; Koch, 1999). This reconstruction of the system adds more time overhead to the design process: however, with using tools such as those developed recently to support “automatic code generation” (Mwelwa et al., 2006; Mwelwa, 2006; Kurian & Pont, 2007), the work involved in developing and maintaining such systems can be substantially reduced.
Another drawback of TTC systems, as noted by Koch (1999), is that constructing the cyclic executive model for a large set of tasks with periods that are prime to each other can be unaffordable. However, in practice, there is some flexibility in the choice of task periods (Xu & Parnas, 1993; Pont, 2001). For example, Gerber et al. (1995) demonstrated how a feasible solution for task periods can be obtained by considering the period harmonicity relationship of each task with all its successors. Kim et al. (1999) went further to improve and automate this period calibration method. Please also note that using a table to store the task schedule is only one way of implementing TTC algorithm where, in practice, there can be other implementation methods (Baker & Shaw, 1989; Pont, 2001). For example, Pont (2001) described an alternative to table-driven schedule implementation for the TTC algorithm which has the potential to solve the co-prime periods problem and also simplify the process of modifying the whole task schedule later in the development life cycle or during the system run-time.
Furthermore, it has also been reported that a long task whose execution time exceeds the period of the highest rate (shortest period) task cannot be scheduled on the basic TTC scheduler (Locke, 1992). One solution to this problem is to break down the long task into multiple short tasks that can fit in the minor cycle. Also, possible alternative solution to this problem is to use a Time-Triggered Hybrid (TTH) scheduler (Pont, 2001) in which a limited degree of pre-emption is supported. One acknowledged advantage of using TTH scheduler is that it enables the designer to build a static, fixed-priority schedule made up of a collection of co-operative tasks and a single (short) pre-emptive task (Phatrapornnant, 2007). Note that TTH architectures are not covered in the context of this chapter. For more details about these scheduling approaches, see (Pont, 2001; Maaita & Pont, 2005; Hughes & Pont, 2008; Phatrapornnant, 2007).
Please note that later in this chapter, it will be demonstrated how, with extra care at the implementation stage, one can easily deal with many of the TTC scheduler limitations indicated above.
6. Jitter in TTC scheduling algorithm
Jitter is a term which describes variations in the timing of activities (Wavecrest, 2001). The work presented in this chapter is concerned with implementing highly-predictable embedded systems. Predictability is one of the most important objectives of real-time embedded systems which can simply be defined as the ability to determine, in advance, exactly what the system will do at every moment of time in which it is running. One way in which predictable behavior manifests itself is in low levels of task jitter.
Jitter is a key timing parameter that can have detrimental impacts on the performance of many applications, particularly those involving period sampling and/or data generation (e.g. data acquisition, data playback and control systems: see Torngren, 1998). For example, Cottet & David (1999) show that – during data acquisition tasks – jitter rates of 10% or more can introduce errors which are so significant that any subsequent interpretation of the sampled signal may be rendered meaningless. Similarly, Jerri (1977) discusses the serious impact of jitter on applications such as spectrum analysis and filtering. Also, in control systems, jitter can greatly degrade the performance by varying the sampling period (Torngren, 1998; Marti et al., 2001).
When TTC architectures (which represent the main focus of this chapter) are employed, possible sources of task jitter can be divided into three main categories: scheduling overhead variation, task placement and clock drift.
The overhead of a conventional (non-co-operative) scheduler arises mainly from context switching. However, in some TTC systems the scheduling overhead is comparatively large and may have a highly variable duration due to code branching or computations that have non-fixed lengths. As an example, Fig. 8 illustrates how a TTC system can suffer release jitter as a result of variations in the scheduler overhead (this relates to DVS system).

Even if the scheduler overhead variations can be avoided, TTC designs can still suffer from jitter as a result of the task placement. To illustrate this, consider Fig. 9. In this schedule example, Task C runs sometimes after A, sometimes after A and B, and sometimes alone. Therefore, the period between every two successive runs of Task C is highly variable. Moreover, if Task A and B have variable execution durations (as in Fig. 8), then the jitter levels of Task C will even be larger.

For completeness of this discussion, it is also important to consider clock drift as a source of task jitter. In the TTC designs, a clock “tick” is generated by a hardware timer that is used to trigger the execution of the cyclic tasks (Pont, 2001). This mechanism relies on the presence of a timer that runs at a fixed frequency. In such circumstances, any jitter will arise from variations at the hardware level (e.g. through the use of a low-cost frequency source, such as a ceramic resonator, to drive the on-chip oscillator: see Pont, 2001). In the TTC scheduler implementations considered in this study, the software developer has no control over the clock source. However, in some circumstances, those implementing a scheduler must take such factors into account. For example, in situations where DVS is employed (to reduce CPU power consumption), it may take a variable amount of time for the processor’s phase-locked loop (PLL) to stabilize after the clock frequency is changed (see Fig. 10).

As discussed elsewhere, it is possible to compensate for such changes in software and thereby reduce jitter (see Phatrapornnant & Pont, 2006; Phatrapornnant, 2007).
7. Various TTC scheduler implementations for highly-predictable embedded systems
In this section, a set of “representative” examples of the various classes of TTC scheduler implementations are reviewed. In total, the section reviews six TTC implementations.
7.1 Super loop (SL) scheduler
The simplest practical implementation of a TTC scheduler can be created using a “Super Loop” (SL) (sometimes called an “endless loop: Kalinsky, 2001). The super loop can be used as the basis for implementing a simple TTC scheduler (e.g. Pont, 2001; Kurian & Pont, 2007). A possible implementation of TTC scheduler using super loop is illustrated in Listing 1.
```c
int main(void)
{
...
while(1)
{
TaskA();
Delay_6ms();
TaskB();
Delay_6ms();
TaskC();
Delay_6ms();
}
// Should never reach here
return 1
}
```
Listing 1. A very simple TTC scheduler which executes three periodic tasks, in sequence.
By assuming that each task in Listing 1 has a fixed duration of 4 ms, a TTC system with a 10 ms “tick interval” has been created using a combination of super loop and delay functions (Fig. 11).
```
4 ms | 4 ms | 4 ms |
Task A | Task B | Task C |
```
Fig. 11. The task executions resulting from the code in Listing 1 (Nahas, 2011b).
In the case where the scheduled tasks have variable durations, creating a fixed tick interval is not straightforward. One way of doing that is to use a “Sandwich Delay” (Pont et al., 2006) placed around the tasks. Briefly, a Sandwich Delay (SD) is a mechanism – based on a
hardware timer – which can be used to ensure that a particular code section always takes approximately the same period of time to execute. The SD operates as follows: [1] A timer is set to run; [2] An activity is performed; [3] The system waits until the timer reaches a predetermined count value.
In these circumstances – as long as the timer count is set to a duration that exceeds the WCET of the sandwiched activity – SD mechanism has the potential to fix the execution period. Listing 2 shows how the tasks in Listing 1 can be scheduled – again using a 10 ms tick interval – if their execution durations are not fixed.
```c
int main(void)
{
...
while(1)
{
// Set up a Timer for sandwich delay
SANDWICH_DELAY_Start();
// Add Tasks in the first tick interval
Task_A();
// Wait for 10 millisecond sandwich delay
// Add Tasks in the second tick interval
SANDWICH_DELAY_Wait(10);
Task_B();
// Wait for 20 millisecond sandwich delay
// Add Tasks in the second tick interval
SANDWICH_DELAY_Wait(20);
Task_C();
// Wait for 30 millisecond sandwich delay
SANDWICH_DELAY_Wait(30);
// Should never reach here
return 1
}
}
```
Listing 2. A TTC scheduler which executes three periodic tasks with variable durations, in sequence.
Using the code listing shown, the successive function calls will take place at fixed intervals, even if these functions have large variations in their durations (Fig. 12). For further information, see (Nahas, 2011b).

### 7.2 A TTC-ISR scheduler
In general, software architectures based on super loop can be seen simple, highly efficient and portable (Pont, 2001; Kurian & Pont, 2007). However, these approaches lack the
provision of accurate timing and the efficiency in using the power resources, as the system always operates at full-power which is not necessary in many applications.
An alternative (and more efficient) solution to this problem is to make use of the hardware resources to control the timing and power behavior of the system. For example, a TTC scheduler implementation can be created using “Interrupt Service Routine” (ISR) linked to the overflow of a hardware timer. In such approaches, the timer is set to overflow at regular “tick intervals” to generate periodic “ticks” that will drive the scheduler. The rate of the tick interval can be set equal to (or higher than) the rate of the task which runs at the highest frequency (Phatrapornnant, 2007).
In the TTC-ISR scheduler, when the timer overflows and a tick interrupt occurs, the ISR will be called, and awaiting tasks will then be activated from the ISR directly. Fig. 13 shows how such a scheduler can be implemented in software. In this example, it is assumed that one of the microcontroller’s timers has been set to generate an interrupt once every 10 ms, and thereby call the function Update(). This Update() function represents the scheduler ISR. At the first tick, the scheduler will run Task A then go back to the while loop in which the system is placed in the idle mode waiting for the next interrupt. When the second interrupt takes place, the scheduler will enter the ISR and run Task B, then the cycle continues. The overall result is a system which has a 10 ms “tick interval” and three tasks executed in sequence (see Fig. 14).
```c
while(1) {
Go_To_Sleep();
}
```
```c
void Update(void) {
Tick_G++;
switch(Tick_G) {
case 1:
Task_A();
break;
case 2:
Task_B();
break;
case 3:
Task_C();
Tick_G = 0;
}
}
```
Fig. 13. A schematic representation of a simple TTC-ISR scheduler (Nahas, 2008).
Whether or not the idle mode is used in TTC-ISR scheduler, the timing observed is largely independent of the software used but instead depends on the underlying timer hardware (which will usually mean the accuracy of the crystal oscillator driving the microcontroller). One consequence of this is that, for the system shown in Fig. 13 (for example), the successive function calls will take place at precisely-defined intervals, even if there are large variations.
in the duration of tasks which are run from the \texttt{Update()} function (Fig. 14). This is very useful behavior which is not easily obtained with implementations based on super loop.

The function call tree for the TTC-ISR scheduler is shown in Fig. 15. For further information, see (Nahas, 2008).

### 7.3 TTC-dispatch scheduler
Implementation of a TTC-ISR scheduler requires a significant amount of hand coding (to control the task timing), and there is no division between the “scheduler” code and the “application” code (i.e. tasks). The TTC-Dispatch scheduler provides a more flexible alternative. It is characterized by distinct and well-defined scheduler functions.
Like TTC-ISR, the TTC-Dispatch scheduler is driven by periodic interrupts generated from an on-chip timer. When an interrupt occurs, the processor executes an \texttt{Update()} function. In the scheduler implementation discussed here, the \texttt{Update()} function simply keeps track of the number of ticks. A \texttt{Dispatch()} function will then be called, and the due tasks (if any) will be executed one-by-one. Note that the \texttt{Dispatch()} function is called from an “endless” loop placed in the function \texttt{Main()}: see Fig. 16. When not executing the \texttt{Update()} or \texttt{Dispatch()} functions, the system will usually enter the low-power idle mode.
In this TTC implementation, the software employs a \texttt{SCH\_Add\_Task()} and a \texttt{SCH\_Delete\_Task()} functions to help the scheduler add and/or remove tasks during the system run-time. Such scheduler architecture provides support for “one shot” tasks and dynamic scheduling where tasks can be scheduled online if necessary (Pont, 2001). To add a task to the scheduler, two main parameters have to be defined by the user in addition to the task’s name: task’s \texttt{offset}, and task’s \texttt{period}. The \texttt{offset} specifies the time (in ticks) before the task is first executed. The period specifies the interval (also in ticks) between repeated executions of the task. In the \texttt{Dispatch()} function, the scheduler checks these parameters for each task before running it. Please note that information about tasks is stored in a user-defined scheduler data structure. Both the \texttt{sTask} data type and the \texttt{SCH\_MAX\_TASKS} constant are used to create the “Task Array” which is referred to throughout the scheduler.
as “sTask SCH_tasks_G[SCH_MAX_TASKS]”. See (Pont, 2001) for further details. The function call tree for the TTC-Dispatch scheduler is shown in Fig. 16.

Fig. 16. Function call tree for the TTC-Dispatch scheduler (Nahas, 2011a).
Fig. 16 illustrates the whole scheduling process in the TTC-Dispatch scheduler. For example, it shows that the first function to run (after the startup code) is the `Main()` function. The `Main()` calls `Dispatch()` which in turn launches any tasks which are currently scheduled to execute. Once these tasks are complete, the control will return back to `Main()` which calls `Sleep()` to place the processor in the idle mode. The timer interrupt then occurs which will wake the processor up from the idle state and invoke the ISR `Update()`. The function call then returns all the way back to `Main()`, where `Dispatch()` is called again and the whole cycle thereby continues. For further information, see (Nahas, 2008).
### 7.4 Task Guardians (TG) scheduler
Despite many attractive characteristics, TTC designs can be seriously compromised by tasks that fail to complete within their allotted periods. The TTC-TG scheduler implementation described in this section employs a Task Guardian (TG) mechanism to deal with the impact of such task overruns. When dealing with task overruns, the TG mechanism is required to shutdown any task which is found to be overrunning. The proposed solution also provides the option of replacing the overrunning task with a backup task (if required).
The implementation is again based on TTC-Dispatch (Section 7.3). In the event of a task overrun with ordinary Dispatch scheduler, the timer ISR will interrupt the overrunning task (rather than the `Sleep()` function). If the overrunning task keeps executing then it will be periodically interrupted by `Update()` while all other tasks will be blocked until the task finishes (if ever): this is shown in Fig. 17. Note that (a) illustrates the required task schedule, and (b) illustrates the scheduler operation when Task A overrun by 5 tick interval.

Fig. 17. The impact of task overrun on a TTC scheduler (Nahas, 2008).
In order for the TG mechanism to work, various functions in the TTC-Dispatch scheduler are modified as follows:
- **Dispatch()** indicates that a task is being executed.
- **Update()** checks to see if an overrun has occurred. If it has, control is passed back to **Dispatch()**, shutting down the overrunning task.
- If a backup task exists it will be executed by **Dispatch()**.
- Normal operation then continues.
In a little more detail, detecting overrun in this implementation uses a simple, efficient method employed in the **Dispatch()** function. It simply adds a “Task_Overrun” variable which is set equal to the task index before the task is executed. When the task completes, this variable will be assigned the value of (for example) 255 to indicate a successful completion. If a task overruns, the **Update()** function in the next tick should detect this since it checks the Task_overrun variable and the last task index value. The **Update()** then changes the return address to an **End_Task()** function instead of the overrunning task. The **End_Task()** function should return control to **Dispatch**. Note that moving control from **Update()** to **End_Task()** is a nontrivial process and can be done by different ways (Hughes & Pont, 2004).
The **End_Task()** has the responsibility to shutdown the overrunning task. Also, it determines the type of function that has overrun and begins to restore register values accordingly. This process is complicated which aims to return the scheduler back to its normal operation making sure the overrun has been resolved completely. Once the overrun is dealt with, the scheduler replaces the overrunning task with a backup task which is set to run immediately before running other tasks. If there is no backup task defined by the user, then the TTC-TG scheduler implements a mechanism which turns the priority of the task that overrun to the lowest so as to reduce the impact of any future overrunning by this task. The function call tree for the TTC-TTG scheduler can be shown in Fig. 18.

Fig. 18. Function call tree for the TTC-TG scheduler (Nahas, 2008).
Note that the scheduler structure used in TTC-TG scheduler is same as that employed in the TTC-Dispatch scheduler which is simply based on ISR Update linked to a timer interrupt and a Dispatch function called periodically from the Main code (Section 7.3). For further details, see (Hughes & Pont, 2008).
### 7.5 Sandwich Delay (SD) scheduler
In Section 6, the impact of task placement on “low-priority” tasks running in TTC schedulers was considered. The TTC schedulers described in Sections 7.1 - 7.4 lack the ability to deal with jitter in the starting time of such tasks. One way to address this issue is to place “Sandwich Delay” (Pont et al., 2006) around tasks which execute prior to other tasks in the same tick interval.
In the TTC-SD scheduler described in this section, sandwich delays are used to provide execution “slots” of fixed sizes in situations where there is more than one task in a tick interval. To clarify this, consider the set of tasks shown in Fig. 19. In the figure, the required SD prior to Task C – for low jitter behavior – is equal to the WCET of Task A plus the WCET of Task B. This implies that in the second tick (for example), the scheduler runs Task A and then waits for the period equals to the WCET of Task B before running Task C. The figure shows that when SDs are placed around the tasks prior to Task C, the periods between successive runs of Task C become equal and hence jitter in the release time of this task is significantly reduced.

Note that – with this implementation – the WCET for each task is input to the scheduler through a `SCH_Task_WCET()` function placed in the Main code. After entering task parameters, the scheduler employs `Calc_Sch_Major_Cycle()` and `Calculate_Task_RT()` functions to calculate the scheduler major cycle and the required release time for the tasks, respectively. The release time values are stored in the “Task Array” using the variable `SCH_tasks_G[Index].Rls_time`. Note that the required release time of a task is the time between the start of the tick interval and the start time of the task “slot” plus a little safety margin. For further information, see (Nahas, 2011a).
### 7.6 Multiple Timer Interrupts (MTI) scheduler
An alternative to the SD technique which requires a large computational time, a “gap insertion” mechanism that uses “Multiple Timer Interrupts” (MTIs) can be employed.
In the TTC-MTI scheduler described in this section, multiple timer interrupts are used to generate the predefined execution “slots” for tasks. This allows more precise control of timing in situations where more than one task executes in a given tick interval. The use of interrupts also allows the processor to enter an idle mode after completion of each task, resulting in power saving. In order to implement this technique, two interrupts are required:
- Tick interrupt: used to generate the scheduler periodic tick.
- Task interrupt: used – within tick intervals – to trigger the execution of tasks.
The process is illustrated in Fig. 20. In this figure, to achieve zero jitter, the required release time prior to Task C (for example) is equal to the WCET of Task A plus the WCET of Task B plus scheduler overhead (i.e. ISR `Update()` function). This implies that in the second tick (for example), after running the ISR, the scheduler waits – in idle mode – for a period of time equals to the WCETs of Task A and Task B before running Task C. Fig. 20 shows that when an MTI method is used, the periods between the successive runs of Task C (the lowest priority task in the system) are always equal. This means that the task jitter in such
implementation is independent on the task placement or the duration(s) of the preceding task(s).
Fig. 20. Using MTIs to reduce release jitter in TTC schedulers (Nahas, 2011a).
In the implementation considered in this section, the WCET for each task is input to the scheduler through \texttt{SCH\_Task\_WCET()} function placed in the \texttt{Main()} code. The scheduler then employs \texttt{Calc\_Sch\_Major\_Cycle()} and \texttt{Calculate\_Task\_RT()} functions to calculate the scheduler major cycle and the required release time for the tasks, respectively. Moreover, there is no \texttt{Dispatch()} called in the \texttt{Main()} code: instead, “interrupt request wrappers” – which contain Assembly code – are used to manage the sequence of operation in the whole scheduler. The function call tree for the TTC-MTI scheduler is shown in Fig. 21 (compare with Fig. 16).
Fig. 21. Function call tree for the TTC-MTI scheduler (in normal conditions) (Nahas, 2011a).
Unlike the normal Dispatch schedulers, this implementation relies on two interrupt update\texttt{()} functions: \texttt{Tick\_Update()} and \texttt{Task\_Update()}\texttt{}. The \texttt{Tick\_Update()}\texttt{ – which is called every tick interval (as normal) – identifies which tasks are ready to execute within the current tick interval. Before placing the processor in the idle mode, the \texttt{Tick\_Update()} function sets the match register of the task timer according to the release time of the first due task running in the current interval. Calculating the release time of the first task in the system takes into account the WCET of the \texttt{Tick\_Update()}\texttt{ code.}
When the task interrupt occurs, the \texttt{Task\_Update()}\texttt{ sets the return address to the task that will be executed straight after this update function, and sets the match register of the task timer for the next task (if any). The scheduled task then executes as normal. Once the task completes execution, the processor goes back to \texttt{Sleep()} and waits for the next task interrupt (if there are following tasks to execute) or the next tick interrupt which launches a new tick interval. Note that the \texttt{Task\_Update()} code is written in such a way that it always has a fixed execution duration for avoiding jitter at the starting time of tasks.
It is worth highlighting that the TTC-MTI scheduler described here employs a form of “task guardians” which help the system avoid any overruns in the operating tasks. More specifically, the described MTI technique helps the TTC scheduler to shutdown any overrunning task by the time the following interrupt takes place. For example, if the overrunning task is followed by another task in the same tick, then the task interrupt –
which triggers the execution of the latter task – will immediately terminate the overrun. Otherwise, the task can overrun until the next tick interrupt takes place which will terminate the overrun immediately. The function call tree for the TTC-MTI scheduler – when a task overrun occurs – is shown in Fig. 22. The only difference between this process and the one shown in Fig. 21 is that an ISR will interrupt the overrunning task (rather than the `Sleep()` function). Again, if the overrunning task is the last task to execute in a given tick, then it will be interrupted and terminated by the `Tick Update()` at the next tick interval: otherwise, it will be terminated by the following `Task Update()`. For further information, see (Nahas, 2011a).

Fig. 22. Function call tree for the TTC-MTI scheduler (with task overrun) (Nahas, 2008).
### 8. Evaluation of TTC scheduler implementations
This section provides the results of the various TTC implementations considered in the previous section. The results include jitter levels, error handling capabilities and resource (i.e. CPU and memory) requirements. The section begins by briefing the experimental methodology used in this study.
#### 8.1 Experimental methodology
The empirical studies were conducted using Ashling LPC2000 evaluation board supporting Philips LPC2106 processor (Ashling Microsystems, 2007). The LPC2106 is a modern 32-bit microcontroller with an ARM7 core which can run – under control of an on-chip PLL – at frequencies from 12 MHz to 60 MHz.
The compiler used was the GCC ARM 4.1.1 operating in Windows by means of Cygwin (a Linux emulator for windows). The IDE and simulator used was the Keil ARM development kit (v3.12).
For meaningful comparison of jitter results, the task-set shown in Fig. 23 was used to allow exploring the impact of schedule-induced jitter by scheduling Task A to run every two ticks. Moreover, all tasks were set to have variable execution durations to allow exploring the impact of task-induced jitter.
For jitter measurements, two measures were recorded: Tick Jitter: represented by the variations in the interval between the release times of the periodic tick, and Task Jitter: represented by the variations in the interval between the release times of periodic tasks. Jitter was measured using a National Instruments data acquisition card ‘NI PCI-6035E’ (National Instruments, 2006), used in conjunction with appropriate software LabVIEW 7.1 (LabVIEW, 2007). The “difference jitter” was reported which is obtained by subtracting the minimum period (between each successive ticks or tasks) from the maximum period obtained from the measurements in the sample set. This jitter is sometimes referred to as “absolute jitter” (Buttazzo, 2005).
The CPU overhead was measured using the performance analyzer supported by the Keil simulator which calculates the time required by the scheduler as compared to the total runtime of the program. The percentage of the measured CPU time was then reported to indicate the scheduler overhead in each TTC implementation.
For ROM and RAM memory overheads, the CODE and DATA memory values required to implement each scheduler were recorded, respectively. Memory values were obtained using the “.map” file which is created when the source code is compiled. The STACK usage was also measured (as DATA memory overhead) by initially filling the data memory with ‘DEAD CODE’ and then reporting the number of memory bytes that had been overwritten after running the scheduler for sufficient period.
### 8.2 Results
This section summarizes the results obtained in this study. Table 1 presents the jitter levels, CPU requirements, memory requirements and ability to deal with task overrun for all schedulers. The jitter results include the tick and tasks jitter. The ability to deal with task overrun is divided into six different cases as shown in Table 2. In the table, it is assumed that Task A is the overrunning task.
<table>
<thead>
<tr>
<th>Scheduler</th>
<th>Tick Jitter (µs)</th>
<th>Task A Jitter (µs)</th>
<th>Task B Jitter (µs)</th>
<th>Task C Jitter (µs)</th>
<th>CPU %</th>
<th>ROM (Bytes)</th>
<th>RAM (Bytes)</th>
<th>Ability to deal with task overrun</th>
</tr>
</thead>
<tbody>
<tr>
<td>TTC-SL</td>
<td>1.2</td>
<td>1.5</td>
<td>4016.2</td>
<td>5772.2</td>
<td>100</td>
<td>2264</td>
<td>124</td>
<td>1b</td>
</tr>
<tr>
<td>TTC-ISR</td>
<td>0.0</td>
<td>0.1</td>
<td>4016.7</td>
<td>5615.8</td>
<td>39.5</td>
<td>2256</td>
<td>127</td>
<td>1a</td>
</tr>
<tr>
<td>TTC Dispatch</td>
<td>0.0</td>
<td>0.1</td>
<td>4022.7</td>
<td>5699.8</td>
<td>39.7</td>
<td>4012</td>
<td>325</td>
<td>1b</td>
</tr>
<tr>
<td>TTC-TG</td>
<td>0.0</td>
<td>0.1</td>
<td>4026.2</td>
<td>5751.9</td>
<td>39.8</td>
<td>4296</td>
<td>446</td>
<td>2b</td>
</tr>
<tr>
<td>TTC-SD</td>
<td>0.0</td>
<td>0.1</td>
<td>1.5</td>
<td>1.5</td>
<td>74.0</td>
<td>5344</td>
<td>310</td>
<td>1b</td>
</tr>
<tr>
<td>TTC-MTI</td>
<td>0.0</td>
<td>0.1</td>
<td>0.0</td>
<td>0.0</td>
<td>39.6</td>
<td>3620</td>
<td>514</td>
<td>3a</td>
</tr>
</tbody>
</table>
Table 1. Results obtained in the study detailed in this chapter.
From the table, it is difficult to obtain zero jitter in the release time of the tick in the TTC-SL scheduler, although the tick jitter can still be low. Also, the TTC-SL scheduler always requires a full CPU load (~ 100%). This is since the scheduler does not use the low-power “idle” mode when not executing tasks: instead, the scheduler waits in a “while” loop. In the TTC-ISR scheduler, the tick interrupts occur at precisely-defined intervals with no measurable delays or jitter and the release jitter in Task A is equal to zero. Inevitably, the
memory values in the TTC-Dispatch scheduler are somewhat larger than those required to implement the TTC-SL and TTC-ISR schedulers. The results from the TTC-TG scheduler are very similar to those obtained from the TTC-Dispatch scheduler except that it requires slightly more data memory. When the TTC-SD scheduler is used, the low-priority tasks are executed at fixed intervals. However, there is still a little jitter in the release times of Tasks B and Task C. This jitter is caused by variation in time taken to leave the software loop – which is used in the SD mechanism to check if the required release time for the concerned task is matched – and begin to execute the task. With the TTC-MTI scheduler, the jitter in the release time of all tasks running in the system is totally removed, causing a significant increase in the overall system predictability.
Regarding the ability to deal with task overrun, the TTC-TG scheduler detects and hence terminates the overrunning task at the beginning of the tick following the one in which the task overruns. Moreover, the scheduler allows running a backup task in the same tick in which the overrun is detected and hence continues to run the following tasks. This means that one tick shift is added to the schedule. Also, the TTC-MTI scheduler employs a simple TG mechanism and – once an interrupt occurs – the running task (if any) will be terminated. Note that the implementation employed here did not support backup tasks.
<table>
<thead>
<tr>
<th>Schedule</th>
<th>Shut down (after Ticks)</th>
<th>Backup task</th>
<th>Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>1a</td>
<td>---</td>
<td>Not applicable</td>
<td>Overrunning task is not shut down. The number of elapsed ticks during overrun is not counted and therefore tasks due to run in these ticks are ignored.</td>
</tr>
<tr>
<td>1b</td>
<td>---</td>
<td>Not applicable</td>
<td>Overrunning task is not shut down. The number of elapsed ticks during overrun is counted and therefore tasks due to run in these ticks are executed immediately after overrunning task ends.</td>
</tr>
<tr>
<td>2a</td>
<td>1 Tick</td>
<td>Not available</td>
<td>Overrunning task is detected at the time of the next tick and shut down.</td>
</tr>
<tr>
<td>2b</td>
<td>1 Tick</td>
<td>Available BK(A)</td>
<td>Overrunning task is detected at the time of the next tick and shut down; a replacement (backup) task is added to the schedule.</td>
</tr>
<tr>
<td>3a</td>
<td>WCET(Ax)</td>
<td>Not available</td>
<td>Overrunning task is shut down immediately after it exceeds its estimated WCET.</td>
</tr>
<tr>
<td>3b</td>
<td>WCET(Ax)</td>
<td>Available BK(A)</td>
<td>Overrunning task is shut down immediately after it exceeds its estimated WCET. A backup task is added to the schedule.</td>
</tr>
</tbody>
</table>
Table 2. Examples of possible schedules obtained with task overrun (Nahas, 2008).
9. Conclusions
The particular focus in this chapter was on building embedded systems which have severe resource constraints and require high levels of timing predictability. The chapter provided necessary definitions to help understand the scheduling theory and various techniques used to build a scheduler for the type of systems concerned with in this study. The discussions indicated that for such systems, the “time-triggered co-operative” (TTC) schedulers are a good match. This was mainly due to their simplicity, low resource requirements and high predictability they can offer. The chapter, however, discussed major problems that can affect
the performance of TTC schedulers and reviewed some suggested solutions to overcome such problems.
Then, the discussions focused on the relationship between scheduling algorithm and scheduler implementations and highlighted the challenges faced when implementing software for a particular scheduler. It was clearly noted that such challenges were mainly caused by the broad range of possible implementation options a scheduler can have in practice, and the impact of such implementations on the overall system behavior.
The chapter then reviewed six various TTC scheduler implementations that can be used for resource-constrained embedded systems with highly-predictable system behavior. Useful results from the described schedulers were then provided which included jitter levels, memory requirements and error handling capabilities. The results suggested that a “one size fits all” TTC implementation does not exist in practice, since each implementation has advantages and disadvantages. The selection of a particular implementation will, hence, be decided based on the requirements of the application in which the TTC scheduler is employed, e.g. timing and resource requirements.
10. Acknowledgement
The research presented in this chapter was mainly conducted in the Embedded Systems Laboratory (ESL) at University of Leicester, UK, under the supervision of Professor Michael Pont, to whom the authors are thankful.
11. References
Pop et al., 2002
Nowadays, embedded systems - the computer systems that are embedded in various kinds of devices and play an important role of specific control functions, have permitted various aspects of industry. Therefore, we can hardly discuss our life and society from now onwards without referring to embedded systems. For wide-ranging embedded systems to continue their growth, a number of high-quality fundamental and applied researches are indispensable. This book contains 19 excellent chapters and addresses a wide spectrum of research topics on embedded systems, including basic researches, theoretical studies, and practical work. Embedded systems can be made only after fusing miscellaneous technologies together. Various technologies condensed in this book will be helpful to researchers and engineers around the world.
How to reference
In order to correctly reference this scholarly work, feel free to copy and paste the following:
|
{"Source-Url": "https://cdn.intechopen.com/pdfs-wm/29201.pdf", "len_cl100k_base": 14947, "olmocr-version": "0.1.53", "pdf-total-pages": 30, "total-fallback-pages": 0, "total-input-tokens": 72520, "total-output-tokens": 20329, "length": "2e13", "weborganizer": {"__label__adult": 0.0006494522094726562, "__label__art_design": 0.0011644363403320312, "__label__crime_law": 0.0005602836608886719, "__label__education_jobs": 0.0015401840209960938, "__label__entertainment": 0.00017058849334716797, "__label__fashion_beauty": 0.00035572052001953125, "__label__finance_business": 0.0005741119384765625, "__label__food_dining": 0.0005478858947753906, "__label__games": 0.001506805419921875, "__label__hardware": 0.033416748046875, "__label__health": 0.0007529258728027344, "__label__history": 0.000682830810546875, "__label__home_hobbies": 0.0003135204315185547, "__label__industrial": 0.0020294189453125, "__label__literature": 0.0003650188446044922, "__label__politics": 0.0005216598510742188, "__label__religion": 0.0009546279907226562, "__label__science_tech": 0.375732421875, "__label__social_life": 8.696317672729492e-05, "__label__software": 0.00843048095703125, "__label__software_dev": 0.56640625, "__label__sports_fitness": 0.00047397613525390625, "__label__transportation": 0.0024509429931640625, "__label__travel": 0.0003185272216796875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 80500, 0.03167]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 80500, 0.71398]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 80500, 0.89437]], "google_gemma-3-12b-it_contains_pii": [[0, 258, false], [258, 2984, null], [2984, 6119, null], [6119, 9792, null], [9792, 12505, null], [12505, 14389, null], [14389, 17898, null], [17898, 21299, null], [21299, 24976, null], [24976, 27187, null], [27187, 30764, null], [30764, 34301, null], [34301, 36709, null], [36709, 38455, null], [38455, 40373, null], [40373, 42814, null], [42814, 45417, null], [45417, 47657, null], [47657, 50587, null], [50587, 53602, null], [53602, 56354, null], [56354, 59197, null], [59197, 62351, null], [62351, 65776, null], [65776, 68676, null], [68676, 71826, null], [71826, 74798, null], [74798, 77903, null], [77903, 79108, null], [79108, 80500, null]], "google_gemma-3-12b-it_is_public_document": [[0, 258, true], [258, 2984, null], [2984, 6119, null], [6119, 9792, null], [9792, 12505, null], [12505, 14389, null], [14389, 17898, null], [17898, 21299, null], [21299, 24976, null], [24976, 27187, null], [27187, 30764, null], [30764, 34301, null], [34301, 36709, null], [36709, 38455, null], [38455, 40373, null], [40373, 42814, null], [42814, 45417, null], [45417, 47657, null], [47657, 50587, null], [50587, 53602, null], [53602, 56354, null], [56354, 59197, null], [59197, 62351, null], [62351, 65776, null], [65776, 68676, null], [68676, 71826, null], [71826, 74798, null], [74798, 77903, null], [77903, 79108, null], [79108, 80500, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 80500, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 80500, null]], "pdf_page_numbers": [[0, 258, 1], [258, 2984, 2], [2984, 6119, 3], [6119, 9792, 4], [9792, 12505, 5], [12505, 14389, 6], [14389, 17898, 7], [17898, 21299, 8], [21299, 24976, 9], [24976, 27187, 10], [27187, 30764, 11], [30764, 34301, 12], [34301, 36709, 13], [36709, 38455, 14], [38455, 40373, 15], [40373, 42814, 16], [42814, 45417, 17], [45417, 47657, 18], [47657, 50587, 19], [50587, 53602, 20], [53602, 56354, 21], [56354, 59197, 22], [59197, 62351, 23], [62351, 65776, 24], [65776, 68676, 25], [68676, 71826, 26], [71826, 74798, 27], [74798, 77903, 28], [77903, 79108, 29], [79108, 80500, 30]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 80500, 0.04734]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
959c8d89555aa0c91bb4ba1f8c51070fa492c7ff
|
Cost Optimization Pillar
AWS Well-Architected Framework
April 2020
Notices
Customers are responsible for making their own independent assessment of the information in this document. This document: (a) is for informational purposes only, (b) represents current AWS product offerings and practices, which are subject to change without notice, and (c) does not create any commitments or assurances from AWS and its affiliates, suppliers or licensors. AWS products or services are provided “as is” without warranties, representations, or conditions of any kind, whether express or implied. The responsibilities and liabilities of AWS to its customers are controlled by AWS agreements, and this document is not part of, nor does it modify, any agreement between AWS and its customers.
© 2020 Amazon Web Services, Inc. or its affiliates. All rights reserved.
Abstract
This whitepaper focuses on the cost optimization pillar of the Amazon Web Services (AWS) Well-Architected Framework. It provides guidance to help customers apply best practices in the design, delivery, and maintenance of AWS environments.
A cost-optimized workload fully utilizes all resources, achieves an outcome at the lowest possible price point, and meets your functional requirements. This whitepaper provides in-depth guidance for building capability within your organization, designing your workload, selecting your services, configuring and operating the services, and applying cost optimization techniques.
Introduction
The **AWS Well-Architected Framework** helps you understand the decisions you make while building workloads on AWS. The Framework provides architectural best practices for designing and operating reliable, secure, efficient, and cost-effective workloads in the cloud. It demonstrates a way to consistently measure your architectures against best practices and identify areas for improvement. We believe that having well-architected workloads greatly increases the likelihood of business success.
The framework is based on five pillars:
- Operational Excellence
- Security
- Reliability
- Performance Efficiency
- Cost Optimization
This paper focuses on the cost optimization pillar, and how to architect workloads with the most effective use of services and resources, to achieve business outcomes at the lowest price point.
You'll learn how to apply the best practices of the cost optimization pillar within your organization. Cost optimization can be challenging in traditional on-premises solutions because you must predict future capacity and business needs while navigating complex procurement processes. Adopting the practices in this paper will help your organization achieve the following goals:
- Practice Cloud Financial Management
- Expenditure and usage awareness
- Cost effective resources
- Manage demand and supply resources
- Optimize over time
This paper is intended for those in technology and finance roles, such as chief technology officers (CTOs), chief financial officers (CFOs), architects, developers, financial controllers, financial planners, business analysts, and operations team
members. This paper does not provide implementation details or architectural patterns, however, it does include references to appropriate resources.
Cost Optimization
Cost optimization is a continual process of refinement and improvement over the span of a workload’s lifecycle. The practices in this paper help you build and operate cost-aware workloads that achieve business outcomes while minimizing costs and allowing your organization to maximize its return on investment.
Design Principles
Consider the following design principles for cost optimization:
**Implement cloud financial management:** To achieve financial success and accelerate business value realization in the cloud, you must invest in Cloud Financial Management. Your organization must dedicate the necessary time and resources for building capability in this new domain of technology and usage management. Similar to your Security or Operations capability, you need to build capability through knowledge building, programs, resources, and processes to help you become a cost efficient organization.
**Adopt a consumption model:** Pay only for the computing resources you consume, and increase or decrease usage depending on business requirements. For example, development and test environments are typically only used for eight hours a day during the work week. You can stop these resources when they’re not in use for a potential cost savings of 75% (40 hours versus 168 hours).
**Measure overall efficiency:** Measure the business output of the workload and the costs associated with delivery. Use this data to understand the gains you make from increasing output, increasing functionality, and reducing cost.
**Stop spending money on undifferentiated heavy lifting:** AWS does the heavy lifting of data center operations like racking, stacking, and powering servers. It also removes the operational burden of managing operating systems and applications with managed services. This allows you to focus on your customers and business projects rather than on IT infrastructure.
**Analyze and attribute expenditure:** The cloud makes it easier to accurately identify the cost and usage of workloads, which then allows transparent attribution of IT costs to revenue streams and individual workload owners. This helps measure return on
investment (ROI) and gives workload owners an opportunity to optimize their resources and reduce costs.
**Definition**
There are five focus areas for cost optimization in the cloud:
- Practice Cloud Financial Management
- Expenditure and usage awareness
- Cost-effective resources
- Manage demand and supplying resources
- Optimize over time
Similar to the other pillars within the Well-Architected Framework, there are trade-offs to consider for cost optimization. For example, whether to optimize for speed-to-market, or for cost. In some cases, it’s best to optimize for speed—going to market quickly, shipping new features, or meeting a deadline—rather than investing in upfront cost optimization.
Design decisions are sometimes directed by haste rather than data, and the temptation always exists to overcompensate, rather than spend time benchmarking for the most cost-optimal deployment. Overcompensation can lead to over-provisioned and under-optimized deployments. However, it may be a reasonable choice if you must “lift and shift” resources from your on-premises environment to the cloud and then optimize afterwards.
Investing the right amount of effort in a cost optimization strategy up front allows you to realize the economic benefits of the cloud more readily by ensuring a consistent adherence to best practices and avoiding unnecessary over provisioning. The following sections provide techniques and best practices for the initial and ongoing implementation of Cloud Financial Management and cost optimization for your workloads.
**Practice Cloud Financial Management**
Cloud Financial Management (CFM) enables organizations to realize business value and financial success as they optimize their cost and usage and scale on AWS.
The following are Cloud Financial Management best practices:
- Functional ownership
- Finance and technology partnership
- Cloud budgets and forecasts
- Cost-aware processes
- Cost-aware culture
- Quantify business value delivered through cost optimization
**Functional Ownership**
**Establish a cost optimization function:** This function is responsible for establishing and maintaining a culture of cost awareness. It can be an existing individual, a team within your organization, or a new team of key finance, technology and organization stakeholders from across the organization.
The function (individual or team) prioritizes and spends the required percentage of their time on cost management and cost optimization activities. For a small organization, the function might spend a smaller percentage of time compared to a full-time function for a larger enterprise.
The function require a multi-disciplined approach, with capabilities in project management, data science, financial analysis, and software/infrastructure development. The function is can improve efficiencies of workloads by executing cost optimizations (centralized approach), influencing technology teams to execute optimizations (decentralized), or a combination of both (hybrid). The function may be measured against their ability to execute and deliver against cost optimization goals (for example, workload efficiency metrics).
You must secure executive sponsorship for this function. The sponsor is regarded as champion for cost efficient cloud consumption, and provides escalation support for the function to ensure that cost optimization activities are treated with the level of priority defined by the organization. Together, the sponsor and function ensure that your organization consumes the cloud efficiently and continue to deliver business value.
Finance and Technology Partnership
Establish a partnership between finance and technology: Technology teams innovate faster in the cloud due to shortened approval, procurement, and infrastructure deployment cycles. This can be an adjustment for finance organizations previously used to executing time-consuming and resource-intensive processes for procuring and deploying capital in data center and on-premises environments, and cost allocation only at project approval.
Establish a partnership between key finance and technology stakeholders to create a shared understanding of organizational goals and develop mechanisms to succeed financially in the variable spend model of cloud computing. Relevant teams within your organization must be involved in cost and usage discussions at all stages of your cloud journey, including:
- **Financial leads**: CFOs, financial controllers, financial planners, business analysts, procurement, sourcing, and accounts payable must understand the cloud model of consumption, purchasing options, and the monthly invoicing process. Due to the fundamental differences between the cloud (such as the rate of change in usage, pay as you go pricing, tiered pricing, pricing models, and detailed billing and usage information) compared to on-premises operation, it is essential that the finance organization understands how cloud usage can impact business aspects including procurement processes, incentive tracking, cost allocation and financial statements.
- **Technology leads**: Technology leads (including product and application owners) must be aware of the financial requirements (for example, budget constraints) as well as business requirements (for example, service level agreements). This allows the workload to be implemented to achieve the desired goals of the organization.
The partnership of finance and technology provides the following benefits:
- Finance and technology teams have near real-time visibility into cost and usage.
- Finance and technology teams establish a standard operating procedure to handle cloud spend variance.
- Finance stakeholders act as strategic advisors with respect to how capital is used to purchase commitment discounts (for example, Reserved Instances or AWS Savings Plans), and how the cloud is used to grow the organization.
• Existing accounts payable and procurement processes are used with the cloud.
• Finance and technology teams collaborate on forecasting future AWS cost and usage to align/build organizational budgets.
• Better cross-organizational communication through a shared language, and common understanding of financial concepts.
Additional stakeholders within your organization that should be involved in cost and usage discussions include:
• **Business unit owners**: Business unit owners must understand the cloud business model so that they can provide direction to both the business units and the entire company. This cloud knowledge is critical when there is a need to forecast growth and workload usage, and when assessing longer-term purchasing options, such as Reserved Instances or Savings Plans.
• **Third parties**: If your organization uses third parties (for example, consultants or tools), ensure that they are aligned to your financial goals and can demonstrate both alignment through their engagement models and a return on investment (ROI). Typically, third parties will contribute to reporting and analysis of any workloads that they manage, and they will provide cost analysis of any workloads that they design.
### Cloud Budgets and Forecasts
**Establish cloud budgets and forecasts**: Customers use the cloud for efficiency, speed and agility, which creates a highly variable amount of cost and usage. Costs can decrease with increases in workload efficiency, or as new workloads and features are deployed. Or, workloads will scale to serve more of your customers, which increases cloud usage and costs. Existing organizational budgeting processes must be modified to incorporate this variability.
Adjust existing budgeting and forecasting processes to become more dynamic using either a trend based algorithm (using historical costs as inputs), or using business driver based algorithms (for example, new product launches or regional expansion), or a combination of both trend and business drivers.
You can use [AWS Cost Explorer](https://aws.amazon.com/costexplorer) to forecast daily (up to 3 months) or monthly (up to 12 months) cloud costs based on machine learning algorithms applied to your historical costs (trend based).
Cost-Aware Processes
Implement cost awareness in your organizational processes: Cost awareness must be implemented in new and existing organizational processes. It is recommended to re-use and modify existing processes where possible—this minimizes the impact to agility and velocity. The following recommendations will help implement cost awareness in your workload:
- Ensure that change management includes a cost measurement to quantify the financial impact of your changes. This helps pro-actively address cost-related concerns and highlight cost savings.
- Ensure that cost optimization is a core component of your operating capabilities. For example, you can leverage existing incident management processes to investigate and identify root cause for cost and usage anomalies (cost overages).
- Accelerate cost savings and business value realization through automation or tooling. When thinking about the cost of implementing, frame the conversation to include an ROI component to justify the investment of time or money.
- Extend existing training and development programs to include cost aware training throughout your organization. It is recommended that this includes continuous training and certification. This will build an organization that is capable of self-managing cost and usage.
Report and notify on cost and usage optimization: You must regularly report on cost and usage optimization within your organization. You can implement dedicated sessions to cost optimization, or include cost optimization in your regular operational reporting cycles for your workloads. AWS Cost Explorer provides dashboards and reports. You can track your progress of cost and usage against configured budgets with AWS Budgets Reports.
You can also use Amazon QuickSight with Cost and Usage Report (CUR) data, to provide highly customized reporting with more granular data.
Implement notifications on cost and usage to ensure that changes in cost and usage can be acted upon quickly. AWS Budgets allows you to provide notifications against targets. We recommend configuring notifications on both increases and decreases, and in both cost and usage for workloads.
Monitor cost and usage proactively: It is recommended to monitor cost and usage proactively within your organization, not just when there are exceptions or anomalies.
Highly visible dashboards throughout your office or work environment ensure that key people have access to the information they need, and indicate the organization’s focus on cost optimization. Visible dashboards enable you to actively promote successful outcomes and implement them throughout your organization.
Cost-Aware Culture
Create a cost aware culture: Implement changes or programs across your organization to create a cost aware culture. It is recommended to start small, then as your capabilities increase and your organization’s use of the cloud increases, implement large and wide ranging programs.
A cost aware culture allows you to scale cost optimization and cloud financial management through best practices that are performed in an organic and decentralized manner across your organization. This creates high levels of capability across your organization with minimal effort, compared to a strict top-down, centralized approach.
Small changes in culture can have large impacts on the efficiency of your current and future workloads. Examples of this include:
- Gamifying cost and usage across your organization. This can be done through a publicly visible dashboard, or a report that compares normalized costs and usage across teams (for example, cost per workload, cost per transaction).
- Recognizing cost efficiency. Reward voluntary or unsolicited cost optimization accomplishments publicly or privately, and learn from mistakes to avoid repeating them in the future.
- Create top-down organizational requirements for workloads to run at pre-defined budgets.
Keep up to date with new service releases: You may be able to implement new AWS services and features to increase cost efficiency in your workload. Regularly review the AWS News Blog, the AWS Cost Management blog, and What’s New with AWS for information on new service and feature releases.
Quantify Business Value Delivered Through Cost Optimization
Quantify business value from cost optimization: In addition to reporting savings from cost optimization, it is recommended that you quantify the additional value
Cost optimization benefits are typically quantified in terms of lower costs per business outcome. For example, you can quantify On-Demand Amazon Elastic Compute Cloud (Amazon EC2) cost savings when you purchase Savings Plans, which reduce cost and maintain workload output levels. You can quantify cost reductions in AWS spending when idle Amazon EC2 instances are terminated, or unattached Amazon Elastic Block Store (Amazon EBS) volumes are deleted.
Quantifying business value from cost optimization allows you to understand the entire set of benefits to your organization. Because cost optimization is a necessary investment, quantifying business value allows you to explain the return on investment to stakeholders. Quantifying business value can help you gain more buy-in from stakeholders on future cost optimization investments, and provides a framework to measure the outcomes for your organization’s cost optimization activities.
The benefits from cost optimization, however, go above and beyond cost reduction or avoidance. Consider capturing additional data to measure efficiency improvements and business value. Examples of improvement include:
- **Executing cost optimization best practices**: For example, resource lifecycle management reduces infrastructure and operational costs and creates time and unexpected budget for experimentation. This increases organization agility and uncovers new opportunities for revenue generation.
- **Implementing automation**: For example, Auto Scaling, which ensures elasticity at minimal effort, and increases staff productivity by eliminating manual capacity planning work. For more details on operational resiliency, refer to the Well-Architected Reliability Pillar whitepaper.
- **Forecasting future AWS costs**: Forecasting enables finance stakeholders to set expectations with other internal and external organization stakeholders, and helps improve your organization’s financial predictability. AWS Cost Explorer can be used to perform forecasting for your cost and usage.
**Resources**
Refer to the following resources to learn more about AWS best practices for budgeting and forecasting cloud spend.
- Reporting your budget metrics with budget reports
- Forecasting with AWS Cost Explorer
- AWS Training
Expenditure and Usage Awareness
Understanding your organization’s costs and drivers is critical for managing your cost and usage effectively, and identifying cost-reduction opportunities. Organizations typically operate multiple workloads run by multiple teams. These teams can be in different organization units, each with its own revenue stream. The capability to attribute resource costs to the workloads, individual organization, or product owners drives efficient usage behavior and helps reduce waste. Accurate cost and usage monitoring allows you to understand how profitable organization units and products are, and allows you to make more informed decisions about where to allocate resources within your organization. Awareness of usage at all levels in the organization is key to driving change, as change in usage drives changes in cost.
Consider taking a multi-faceted approach to becoming aware of your usage and expenditures. Your team must gather data, analyze, and then report. Key factors to consider include:
- Governance
- Monitoring cost and usage
- Decommissioning
Governance
In order to manage your costs in the cloud, you must manage your usage through the governance areas below:
**Develop Organizational Policies:** The first step in performing governance is to use your organization’s requirements to develop policies for your cloud usage. These policies define how your organization uses the cloud and how resources are managed. Policies should cover all aspects of resources and workloads that relate to cost or usage, including creation, modification, and decommission over the resource’s lifetime.
Policies should be simple so that they are easily understood and can be implemented effectively throughout the organization. Start with broad, high-level policies, such as which geographic Region usage is allowed in, or times of the day that resources should be running. Gradually refine the policies for the various organizational units and
workloads. Common policies include which services and features can be used (for example, lower performance storage in test/development environments), and which types of resources can be used by different groups (for example, the largest size of resource in a development account is medium).
**Develop goals and targets:** Develop cost and usage goals and targets for your organization. Goals provide guidance and direction to your organization on expected outcomes. Targets provide specific measurable outcomes to be achieved. An example of a goal is: platform usage should increase significantly, with only a minor (non-linear) increase in cost. An example target is: a 20% increase in platform usage, with less than a 5% increase in costs. Another common goal is that workloads need to be more efficient every 6 months. The accompanying target would be that the cost per output of the workload needs to decrease by 5% every 6 months.
A common goal for cloud workloads is to increase workload efficiency, which is to decrease the cost per business outcome of the workload over time. It is recommended to implement this goal for all workloads, and also set a target such as a 5% increase in efficiency every 6-12 months. This can be achieved in the cloud through building capability in cost optimization, and through the release of new services and service features.
**Account structure:** AWS has a one-parent-to-many-children account structure that is commonly known as a master (the parent, formerly payer) account-member (the child, formerly linked) account. A best practice is to always have at least one master with one member account, regardless of your organization size or usage. All workload resources should reside only within member accounts.
There is no one-size-fits-all answer for how many AWS accounts you should have. Assess your current and future operational and cost models to ensure that the structure of your AWS accounts reflects your organization’s goals. Some companies create multiple AWS accounts for business reasons, for example:
- Administrative and/or fiscal and billing isolation is required between organization units, cost centers, or specific workloads.
- AWS service limits are set to be specific to particular workloads.
- There is a requirement for isolation and separation between workloads and resources.
Within AWS Organizations, consolidated billing creates the construct between one or more member accounts and the master account. Member accounts allow you to isolate
and distinguish your cost and usage by groups. A common practice is to have separate member accounts for each organization unit (such as finance, marketing, and sales), or for each environment lifecycle (such as development, testing and production), or for each workload (workload a, b, and c), and then aggregate these linked accounts using consolidated billing.
Consolidated billing allows you to consolidate payment for multiple member AWS accounts under a single master account, while still providing visibility for each linked account’s activity. As costs and usage are aggregated in the master account, this allows you to maximize your service volume discounts, and maximize the use of your commitment discounts (Savings Plans and Reserved Instances) to achieve the highest discounts.
**AWS Control Tower** can quickly set up and configure multiple AWS accounts, ensuring that governance is aligned with your organization’s requirements.
**Organizational Groups and Roles:** After you develop policies, you can create logical groups and roles of users within your organization. This allows you to assign permissions and control usage. Begin with high-level groupings of people, typically this aligns with organizational units and job roles (for example, systems administrator in the IT Department, or Financial controller). The groups join people that do similar tasks and need similar access. Roles define what a group must do. For example, a systems administrator in IT requires access to create all resources, but an analytics team member only needs to create analytics resources.
**Controls — Notifications:** A common first step in implementing cost controls is to setup notifications when cost or usage events occur outside of the policies. This enables you to act quickly and verify if corrective action is required, without restricting or negatively impacting workloads or new activity. After you know the workload and environment limits, you can enforce governance. In AWS, notifications are conducted with **AWS Budgets**, which allows you to define a monthly budget for your AWS costs, usage, and commitment discounts (Savings Plans and Reserved Instances). You can create budgets at an aggregate cost level (for example, all costs), or at a more granular level where you include only specific dimensions such as linked accounts, services, tags, or Availability Zones. You can also attach email notifications to your budgets, which will trigger when current or forecasted costs or usage exceeds a defined percentage threshold.
**Controls — Enforcement:** As a second step, you can enforce governance policies in AWS through **AWS Identity and Access Management (IAM)**, and **AWS Organizations Service Control Policies (SCP)**. IAM allows you to securely manage access to AWS
services and resources. Using IAM, you can control who can create and manage AWS resources, the type of resources that can be created, and where they can be created. This minimizes the creation of resources that are not required. Use the roles and groups created previously, and assign IAM policies to enforce the correct usage. SCP offers central control over the maximum available permissions for all accounts in your organization, ensuring that your accounts stay within your access control guidelines. SCPs are available only in an organization that has all features enabled, and you can configure the SCPs to either deny or allow actions for member accounts by default. Refer to the Well-Architected Security Pillar whitepaper for more details on implementing access management.
**Controls — Service Quotas:** Governance can also be implemented through management of Service Quotas. By ensuring Service Quotas are set with minimum overhead and accurately maintained, you can minimize resource creation outside of your organization’s requirements. To achieve this, you must understand how quickly your requirements can change, understand projects in progress (both creation and decommission of resources) and factor in how fast quota changes can be implemented. Service Quotas can be used to increase your quotas when required.
AWS Cost Management services are integrated with the AWS Identity and Access Management (IAM) service. You use the IAM service in conjunction with Cost Management services to control access to your financial data and to the AWS tools in the billing console.
**Track workload lifecycle:** Ensure that you track the entire lifecycle of the workload. This ensures that when workloads or workload components are no longer required, they can be decommissioned or modified. This is especially useful when you release new services or features. The existing workloads and components may appear to be in use, but should be decommissioned to redirect customers to the new service. Notice previous stages of workloads — after a workload is in production, previous environments can be decommissioned or greatly reduced in capacity until they are required again.
AWS provides a number of management and governance services you can use for entity lifecycle tracking. You can use AWS Config or AWS Systems Manager to provide a detailed inventory of your AWS resources and configuration. It is recommended that you integrate with your existing project or asset management systems to keep track of active projects and products within your organization. Combining your current system with the rich set of events and metrics provided by AWS allows you to build a view of
significant lifecycle events and proactively manage resources to reduce unnecessary costs.
Refer to the Well-Architected Operational Excellence Pillar whitepaper for more details on implementing entity lifecycle tracking.
Monitor Cost and Usage
Enable teams to take action on their cost and usage through detailed visibility into the workload. Cost optimization begins with a granular understanding of the breakdown in cost and usage, the ability to model and forecast future spend, usage, and features, and the implementation of sufficient mechanisms to align cost and usage to your organization’s objectives. The following are required areas for monitoring your cost and usage:
Configure detailed data sources: Enable hourly granularity in Cost Explorer and create a Cost and Usage Report (CUR). These data sources provide the most accurate view of cost and usage across your entire organization. The CUR provides daily or hourly usage granularity, rates, costs, and usage attributes for all chargeable AWS services. All possible dimensions are in the CUR including: tagging, location, resource attributes, and account IDs.
Configure your CUR with the following customizations:
- Include resource IDs
- Automatically refresh the CUR
- Hourly granularity
- Versioning: Overwrite existing report
- Data integration: Athena (Parquet format and compression)
Use AWS Glue to prepare the data for analysis, and use Amazon Athena to perform data analysis, using SQL to query the data. You can also use Amazon QuickSight to build custom and complex visualizations and distribute them throughout your organization.
Identify cost attribution categories: Work with your finance team and other relevant stakeholders to understand the requirements of how costs must be allocated within your organization. Workload costs must be allocated throughout the entire lifecycle, including development, testing, production, and decommissioning. Understand how the costs
incurred for learning, staff development, and idea creation are attributed in the organization. This can be helpful to correctly allocate accounts used for this purpose to training and development budgets, instead of generic IT cost budgets.
Establish workload metrics: Understand how your workload’s output is measured against business success. Each workload typically has a small set of major outputs that indicate performance. If you have a complex workload with many components, then you can prioritize the list, or define and track metrics for each component. Work with your teams to understand which metrics to use. This unit will be used to understand the efficiency of the workload, or the cost for each business output.
Assign organization meaning to cost and usage: Implement tagging in AWS to add organization information to your resources, which will then be added to your cost and usage information. A tag is a key-value pair—the key is defined and must be unique across your organization, and the value is unique to a group of resources. An example of a key-value pair is the key is Environment, with a value of Production. All resources in the production environment will have this key-value pair. Tagging allows you to categorize and track your costs with meaningful, relevant organization information. You can apply tags that represent organization categories (such as cost centers, application names, projects, or owners), and identify workloads and characteristics of workloads (such as, test or production) to attribute your costs and usage throughout your organization.
When you apply tags to your AWS resources (such as EC2 instances or Amazon S3 buckets) and activate the tags, AWS adds this information to your Cost and Usage Reports. You can run reports and perform analysis, on tagged and untagged resources to allow greater compliance with internal cost management policies, and ensure accurate attribution.
Creating and implementing an AWS tagging standard across your organization’s accounts enables you to manage and govern your AWS environments in a consistent and uniform manner. Use Tag Policies in AWS Organizations to define rules for how tags can be used on AWS resources in your accounts in AWS Organizations. Tag Policies allow you to easily adopt a standardized approach for tagging AWS resources.
AWS Tag Editor allows you to add, delete, and manage tags of multiple resources.
AWS Cost Categories allows you to assign organization meaning to your costs, without requiring tags on resources. You can map your cost and usage information to unique internal organization structures. You define category rules to map and categorize costs using billing dimensions, such as accounts and tags. This provides another level of
management capability in addition to tagging. You can also map specific accounts and tags to multiple projects.
**Configure billing and cost optimization tools:** To modify usage and adjust costs, each person in your organization must have access to their cost and usage information. It is recommended that all workloads and teams have the following tooling configured when they use the cloud:
- **Reports:** Summarize of all cost and usage information.
- **Notifications:** Provide notifications when cost or usage is outside of defined limits.
- **Current State:** Configure a dashboard showing current levels of cost and usage. The dashboard should be available in a highly visible place within the work environment (similar to an operations dashboard).
- **Trending:** Provide the capability to show the variability in cost and usage over the required period of time, with the required granularity.
- **Forecasts:** Provide the capability to show estimated future costs.
- **Tracking:** Show the current cost and usage against configured goals or targets.
- **Analysis:** Provide the capability for team members to perform custom and deep analysis down to the hourly granularity, with all possible dimensions.
You can use AWS native tooling, such as [AWS Cost Explorer](https://aws.amazon.com/cost Explorer), [AWS Budgets](https://aws.amazon.com/budgets), and [Amazon Athena](https://aws.amazon.com/athena) with QuickSight to provide this capability. You can also use third-party tooling, however, you must ensure that the costs of this tooling provide value to your organization.
**Allocate costs based on workload metrics:** Cost Optimization is delivering business outcomes at the lowest price point, which can only be achieved by allocating workload costs by workload metrics (measured by workload efficiency). Monitor the defined workload metrics through log files or other application monitoring. Combine this data with the workload costs, which can be obtained by looking at costs with a specific tag value or account ID. It is recommended to perform this analysis at the hourly level. Your efficiency will typically change if you have some static cost components (for example, a backend database running 24/7) with a varying request rate (for example, usage peaks at 9am – 5pm, with few requests at night). Understanding the relationship between the static and variable costs will help you to focus your optimization activities.
Decommission Resources
After you manage a list of projects, employees, and technology resources over time you will be able to identify which resources are no longer being used, and which projects that no longer have an owner.
**Track resources over their lifetime:** Decommission workload resources that are no longer required. A common example is resources used for testing, after testing has been completed, the resources can be removed. Tracking resources with tags (and running reports on those tags) will help you identify assets for decommission. Using tags is an effective way to track resources, by labeling the resource with its function, or a known date when it can be decommissioned. Reporting can then be run on these tags. Example values for feature tagging are “featureX testing” to identify the purpose of the resource in terms of the workload lifecycle.
**Implement a decommissioning process:** Implement a standardized process across your organization to identify and remove unused resources. The process should define the frequency searches are performed, and the processes to remove the resource to ensure that all organization requirements are met.
**Decommission resources:** The frequency and effort to search for unused resources should reflect the potential savings, so an account with a small cost should be analyzed less frequently than an account with larger costs. Searches and decommission events can be triggered by state changes in the workload, such as a product going end of life or being replaced. Searches and decommission events may also be triggered by external events, such as changes in market conditions or product termination.
**Decommission resources automatically:** Use automation to reduce or remove the associated costs of the decommissioning process. Designing your workload to perform automated decommissioning will reduce the overall workload costs during its lifetime. You can use AWS Auto Scaling to perform the decommissioning process. You can also implement custom code using the API or SDK to decommission workload resources automatically.
**Resources**
Refer to the following resources to learn more about AWS best practices for expenditure awareness.
- [AWS Tagging Strategies](#)
- [Activating User-Defined Cost Allocation Tags](#)
Cost Effective Resources
Using the appropriate services, resources, and configurations for your workloads is key to cost savings. Consider the following when creating cost-effective resources:
- Evaluate cost when selecting services
- Select the correct resource type, size, and number
- Select the best pricing model
- Plan for data transfer
You can use AWS Solutions Architects, AWS Solutions, AWS Reference Architectures, and APN Partners to help you choose an architecture based on what you have learned.
Evaluate Cost When Selecting Services
**Identify organization requirements:** When selecting services for your workload, it is key that you understand your organization priorities. Ensure that you have a balance between cost and other Well-Architected pillars, such as performance and reliability. A fully cost-optimized workload is the solution that is most aligned to your organization’s requirements, not necessarily the lowest cost. Meet with all teams within your organization to collect information, such as product, business, technical and finance.
**Analyze all workload components:** Perform a thorough analysis on all components in your workload. Ensure that balance between the cost of analysis and the potential savings in the workload over its lifecycle. You must find the current impact, and potential future impact, of the component. For example, if the cost of the proposed resource is $10/month, and under forecasted loads would not exceed $15/month,
spending a day of effort to reduce costs by 50% ($5 a month) could exceed the potential benefit over the life of the system. Using a faster and more efficient data-based estimation will create the best overall outcome for this component.
Workloads can change over time, the right set of services may not be optimal if the workload architecture or usage changes. Analysis for selection of services must incorporate current and future workload states and usage levels. Implementing a service for future workload state or usage may reduce overall costs by reducing or removing the effort required to make future changes.
AWS Cost Explorer and the CUR can analyze the cost of a Proof of Concept (PoC) or running environment. You can also use the AWS Simple Monthly Calculator or the AWS Pricing Calculator to estimate workload costs.
**Managed Services:** Managed services remove the operational and administrative burden of maintaining a service, which allows you to focus on innovation. Additionally, because managed services operate at cloud scale, they can offer a lower cost per transaction or service.
Consider the time savings that will allow your team to focus on retiring technical debt, innovation, and value-adding features. For example, you might need to “lift and shift” your on-premises environment to the cloud as rapidly as possible and optimize later. It is worth exploring the savings you could realize by using managed services that remove or reduce license costs.
Usually, managed services have attributes that you can set to ensure sufficient capacity. You must set and monitor these attributes so that your excess capacity is kept to a minimum and performance is maximized. You can modify the attributes of AWS Managed Services using the AWS Management Console or AWS APIs and SDKs to align resource needs with changing demand. For example, you can increase or decrease the number of nodes on an Amazon EMR cluster (or an Amazon Redshift cluster) to scale out or in.
You can also pack multiple instances on an AWS resource to enable higher density usage. For example, you can provision multiple small databases on a single Amazon Relational Database Service (Amazon RDS) DB instance. As usage grows, you can migrate one of the databases to a dedicated RDS DB instance using a snapshot and restore process.
When provisioning workloads on managed services, you must understand the requirements of adjusting the service capacity. These requirements are typically time,
effort, and any impact to normal workload operation. The provisioned resource must allow time for any changes to occur, provision the required overhead to allow this. The ongoing effort required to modify services can be reduced to virtually zero by using APIs and SDKs that are integrated with system and monitoring tools, such as Amazon CloudWatch.
**Amazon Relational Database Service (RDS), Amazon Redshift, and Amazon ElastiCache** provide a managed database service. **Amazon Athena, Amazon Elastic Map Reduce (EMR), and Amazon Elasticsearch** provide a managed analytics service.
**AWS Managed Services (AMS)** is a service that operates AWS infrastructure on behalf of enterprise customers and partners. It provides a secure and compliant environment that you can deploy your workloads onto. AMS uses enterprise cloud operating models with automation to allow you to meet your organization requirements, move into the cloud faster, and reduce your on-going management costs.
**Serverless or Application-level Services:** You can use serverless or application-level services such as **AWS Lambda, Amazon Simple Queue Service (Amazon SQS), Amazon Simple Notification Service (Amazon SNS), and Amazon Simple Email Service (Amazon SES)**. These services remove the need for you to manage a resource, and provide the function of code execution, queuing services, and message delivery. The other benefit is that they scale in performance and cost in line with usage, allowing efficient cost allocation and attribution.
For more information on Serverless, refer to the **Well-Architected Serverless Application lens whitepaper**.
**Analyze the workload for different usage over time:** As AWS releases new services and features, the optimal services for your workload may change. Effort required should reflect potential benefits. Workload review frequency depends on your organization requirements. If it is a workload of significant cost, implementing new services sooner will maximize cost savings, so more frequent review can be advantageous. Another trigger for review is change in usage patterns. Significant changes in usage can indicate that alternate services would be more optimal. For example, for higher data transfer rates a direct connect service may be cheaper than a VPN, and provide the required connectivity. Predict the potential impact of service changes, so you can monitor for these usage level triggers and implement the most cost effective services sooner.
**Licensing costs:** The cost of software licenses can be eliminated through the use of open source software. This can have significant impact on workload costs as the size of the workload scales. Measure the benefits of licensed software against the total cost to
ensure that you have the most optimized workload. Model any changes in licensing and how they would impact your workload costs. If a vendor changes the cost of your database license, investigate how that impacts the overall efficiency of your workload. Consider historical pricing announcements from your vendors for trends of licensing changes across their products. Licensing costs may also scale independently of throughput or usage, such as licenses that scale by hardware (CPU bound licenses). These licenses should be avoided because costs can rapidly increase without corresponding outcomes.
You can use AWS License Manager to manage the software licenses in your workload. You can configure licensing rules and enforce the required conditions to help prevent licensing violations, and also reduce costs due to license overages.
**Select the Correct Resource Type, Size, and Number**
By selecting the best resource type, size, and number of resources, you meet the technical requirements with the lowest cost resource. Right-sizing activities takes into account all of the resources of a workload, all of the attributes of each individual resource, and the effort involved in the right-sizing operation. Right-sizing can be an iterative process, triggered by changes in usage patterns and external factors, such as AWS price drops or new AWS resource types. Right-sizing can also be one-off if the cost of the effort to right-size, out weights the potential savings over the life of the workload.
In AWS, there are a number of different approaches:
- Perform cost modeling
- Select size based on metrics or data
- Select size automatically (based on metrics)
**Cost Modeling:** Perform cost modeling for your workload and each of its components to understand the balance between resources, and find the correct size for each resource in the workload, given a specific level of performance. Perform benchmark activities for the workload under different predicted loads and compare the costs. The modeling effort should reflect potential benefit; for example, time spent is proportional to component cost or predicted saving. For best practices, refer to the Review section of the Performance Efficiency Pillar of the AWS Well-Architected Framework whitepaper.
AWS Compute Optimizer can assist with cost modeling for running workloads. It provides right-sizing recommendations for compute resources based on historical
usage. This is the ideal data source for compute resources because it is a free service, and it utilizes machine learning to make multiple recommendations depending on levels of risk. You can also use Amazon CloudWatch and CloudWatch Logs with custom logs as data sources for right sizing operations for other services and workload components.
The following are recommendations for cost modeling data and metrics:
- The monitoring must accurately reflect the end-user experience. Select the correct granularity for the time period and thoughtfully choose the maximum or 99th percentile instead of the average.
- Select the correct granularity for the time period of analysis that is required to cover any workload cycles. For example, if a two-week analysis is performed, you might be overlooking a monthly cycle of high utilization, which could lead to under-provisioning.
**Metrics or data-based selection:** Select resource size or type based on workload and resource characteristics; for example, compute, memory, throughput, or write intensive. This selection is typically made using cost modeling, a previous version of the workload (such as an on-premises version), using documentation, or using other sources of information about the workload (whitepapers, published solutions).
**Automatic selection based on metrics:** Create a feedback loop within the workload that uses active metrics from the running workload to make changes to that workload. You can use a managed service, such as AWS Auto Scaling, which you configure to perform the right sizing operations for you. AWS also provides APIs, SDKs, and features that allow resources to be modified with minimal effort. You can program a workload to stop-and-start an EC2 instance to allow a change of instance size or instance type. This provides the benefits of right-sizing while removing almost all the operational cost required to make the change.
Some AWS services have built in automatic type or size selection, such as S3 Intelligent-Tiering. S3 Intelligent-Tiering automatically moves your data between two access tiers: frequent access and infrequent access, based on your usage patterns.
**Select the Best Pricing Model**
**Perform workload cost modeling:** Consider the requirements of the workload components and understand the potential pricing models. Define the availability requirement of the component. Determine if there are multiple independent resources that perform the function in the workload, and what the workload requirements are over time. Compare the cost of the resources using the default On-Demand pricing model.
and other applicable models. Factor in any potential changes in resources or workload components.
**Perform regular account level analysis:** Performing regular cost modeling ensures that opportunities to optimize across multiple workloads can be implemented. For example, if multiple workloads use On-Demand, at an aggregate level, the risk of change is lower, and implementing a commitment-based discount will achieve a lower overall cost. It is recommended to perform analysis in regular cycles of two weeks to 1 month. This allows you to make small adjustment purchases, so the coverage of your pricing models continues to evolve with your changing workloads and their components.
Use the [AWS Cost Explorer](https://aws.amazon.com/cost Explorer) recommendations tool to find opportunities for commitment discounts.
To find opportunities for Spot workloads, use an hourly view of your overall usage, and look for regular periods of changing usage or elasticity.
**Pricing Models:** AWS has multiple pricing models that allow you to pay for your resources in the most cost-effective way that suits your organization’s needs. The following section describes each purchasing model:
- On-Demand
- Spot
- Commitment discounts - Savings Plans
- Commitment discounts - Reserved Instances/Capacity
- Geographic selection
- Third-party agreements and pricing
**On-Demand:** This is the default, pay as you go pricing model. When you use resources (for example, EC2 instances or services such as DynamoDB on demand) you pay a flat rate, and you have no long-term commitments. You can increase or decrease the capacity of your resources or services based on the demands of your application. On-Demand has an hourly rate, but depending on the service, can be billed in increments of 1 second (for example Amazon RDS, or Linux EC2 instances). On demand is recommended for applications with short-term workloads (for example, a four-month project), that spike periodically, or unpredictable workloads that can’t be interrupted. On demand is also suitable for workloads, such as pre-production environments, which require uninterrupted runtimes, but do not run long enough for a commitment discount (Savings Plans or Reserved Instances).
Spot: A **Spot Instance** is spare EC2 compute capacity available at discounts of up to 90% off On-Demand prices with no long-term commitment required. With Spot Instances, you can significantly reduce the cost of running your applications or scale your application’s compute capacity for the same budget. Unlike On-Demand, Spot Instances can be interrupted with a 2-minute warning if EC2 needs the capacity back, or the Spot Instance price exceeds your configured price. On average, Spot Instances are interrupted less than 5% of the time.
Spot is ideal when there is a queue or buffer in place, or where there are multiple resources working independently to process the requests (for example, Hadoop data processing). Typically these workloads are fault-tolerant, stateless, and flexible, such as batch processing, big data and analytics, containerized environments, and high performance computing (HPC). Non-critical workloads such as test and development environments are also candidates for Spot.
Spot is also integrated into multiple AWS services, such as EC2 Auto Scaling groups (ASGs), Elastic MapReduce (EMR), Elastic Container Service (ECS), and AWS Batch.
When a Spot Instance needs to be reclaimed, EC2 sends a two-minute warning via a Spot Instance interruption notice delivered through CloudWatch Events, as well as in the instance metadata. During that two-minute period, your application can use the time to save its state, drain running containers, upload final log files, or remove itself from a load balancer. At the end of the two minutes, you have the option to hibernate, stop, or terminate the Spot Instance.
Consider the following best practices when adopting Spot Instances in your workloads:
- **Set your maximum price as the On-Demand rate**: This ensures that you will pay the current spot rate (the cheapest available price) and will never pay more than the On-Demand rate. Current and historical rates are available via the console and API.
- **Be flexible across as many instance types as possible**: Be flexible in both the family and size of the instance type, to improve the likelihood of fulfilling your target capacity requirements, obtain the lowest possible cost, and minimize the impact of interruptions.
- **Be flexible about where your workload will run**: Available capacity can vary by Availability Zone. This improves the likelihood of fulfilling your target capacity by tapping into multiple spare capacity pools, and provides the lowest possible cost.
• **Design for continuity**: Design your workloads for statelessness and fault-tolerance, so that if some of your EC2 capacity gets interrupted, it will not have impact on the availability or performance of the workload.
• We recommend using Spot Instances in combination with On-Demand and Savings Plans/Reserved Instances to maximize workload cost optimization with performance.
**Commitment Discounts – Savings Plans**: AWS provides a number of ways for you to reduce your costs by reserving or committing to use a certain amount of resources, and receiving a discounted rate for your resources. A [Savings Plan](https://aws.amazon.com/savingsplans/) allows you to make an hourly spend commitment for one or three years, and receive discounted pricing across your resources. Savings Plans provide discounts for AWS Compute services such as EC2, Fargate, and Lambda. When you make the commitment, you pay that commitment amount every hour, and it is subtracted from your On-Demand usage at the discount rate. For example, you commit to $50 an hour, and have $150 an hour of On-Demand usage. Considering the Savings Plans pricing, your specific usage has a discount rate of 50%. So, your $50 commitment covers $100 of On-Demand usage. You will pay $50 (commitment) and $50 of remaining On-Demand usage.
**Compute Savings Plans** are the most flexible and provide a discount of up to 66%. They automatically apply across Availability Zones, instance size, instance family, operating system, tenancy, Region, and compute service.
**Instance Savings Plans** have less flexibility but provide a higher discount rate (up to 72%). They automatically apply across Availability Zones, instance size, instance family, operating system, and tenancy.
There are three payment options:
• **No upfront payment**: There is no upfront payment; you then pay a reduced hourly rate each month for the total hours in the month.
• **Partial upfront payment**: Provides a higher discount rate than No upfront. Part of the usage is paid up front; you then pay a smaller reduced hourly rate each month for the total hours in the month.
• **All upfront payment**: Usage for the entire period is paid up front, and no other costs are incurred for the remainder of the term for usage that is covered by the commitment.
You can apply any combination of these three purchasing options across your workloads.
Savings plans apply first to the usage in the account they are purchased in, from the highest discount percentage to the lowest, then they apply to the consolidated usage across all other accounts, from the highest discount percentage to the lowest.
It is recommended to purchase all Savings Plans in an account with no usage or resources, such as the master account. This ensures that the Savings Plan applies to the highest discount rates across all of your usage, maximizing the discount amount.
Workloads and usage typically change over time. It is recommended to continually purchase small amounts of Savings Plans commitment over time. This ensures that you maintain high levels of coverage to maximize your discounts, and your plans closely match your workload and organization requirements at all times.
Do not set a target coverage in your accounts, due to the variability of discount that is possible. Low coverage does not necessarily indicate high potential savings. You may have a low coverage in your account, but if your usage is made up of small instances, with a licensed operating system, the potential saving could be as low as a few percent. Instead, track and monitor the potential savings available in the Savings Plan recommendation tool. Frequently review the Savings Plans recommendations in Cost Explorer (perform regular analysis) and continue to purchase commitments until the estimated savings are below the required discount for the organization. For example, track and monitor that your potential discounts remained below 20%, if it goes above that a purchase must be made.
Monitor the utilization and coverage, but only to detect changes. Do not aim for a specific utilization percent, or coverage percent, as this does not necessarily scale with savings. Ensure that a purchase of Savings Plans results in an increase in coverage, and if there are decreases in coverage or utilization ensure they are quantified and known. For example, you migrate a workload resource to a newer instance type, which reduces utilization of an existing plan, but the performance benefit outweighs the saving reduction.
**Commitment Discounts – Reserved Instances/Commitment:** Similar to Savings Plans, [Reserved Instances](https://aws.amazon.com/Reserved Instances) (RI) offer discounts up to 72% for a commitment to running a minimum amount of resources. Reserved Instances are available for RDS, Elasticsearch, ElastiCache, Amazon Redshift, and DynamoDB. Amazon CloudFront and AWS Elemental MediaConvert also provide discounts when you make minimum usage commitments. Reserved Instances are currently available for EC2, however Savings Plans offer the same discount levels with increased flexibility and no management overhead.
Reserved Instances offer the same pricing options of no upfront, partial upfront, and all upfront, and the same terms of one or three years.
Reserved Instances can be purchased in a Region or a specific Availability Zone. They provide a capacity reservation when purchased in an Availability Zone.
EC2 features convertible RI’s, however, Savings Plans should be used for all EC2 instances due to increased flexibility and reduced operational costs.
The same process and metrics should be used to track and make purchases of Reserved Instances. It is recommended to not track coverage of RI’s across your accounts. It is also recommended that utilization % is not monitored or tracked, instead view the utilization report in Cost Explorer, and use net savings column in the table. If the net savings is a significantly large negative amount, you must take action to remediate the unused RI.
**EC2 Fleet:** EC2 Fleet is a feature that allows you to define a target compute capacity, and then specify the instance types and the balance of On-Demand and Spot for the fleet. EC2 Fleet will automatically launch the lowest price combination of resources to meet the defined capacity.
**Geographic Selection:** When you architect your solutions, a best practice is to seek to place computing resources closer to users to provide lower latency and strong data sovereignty. For global audiences, you should use multiple locations to meet these needs. You should select the geographic location that minimizes your costs.
The AWS Cloud infrastructure is built around Regions and Availability Zones. A Region is a physical location in the world where we have multiple Availability Zones. Availability Zones consist of one or more discrete data centers, each with redundant power, networking, and connectivity, housed in separate facilities.
Each AWS Region operates within local market conditions, and resource pricing is different in each Region. Choose a specific Region to operate a component of or your entire solution so that you can run at the lowest possible price globally. You can use the AWS Simple Monthly Calculator to estimate the costs of your workload in various Regions.
**Third-party agreements and pricing:** When you utilize third-party solutions or services in the cloud, it is important that the pricing structures are aligned to Cost Optimization outcomes. Pricing should scale with the outcomes and value it provides. An example of this is software that takes a percentage of savings it provides, the more you save (outcome) the more it charges. Agreements that scale with your bill are typically not
aligned to Cost Optimization, unless they provide outcomes for every part of your specific bill. For example, a solution that provides recommendations for EC2 and charges a percentage of your entire bill will increase if you use other services for which it provides no benefit. Another example is a managed service that is charged at a percentage of the cost of resources that are managed. A larger instance size may not necessarily require more management effort, but will be charged more. Ensure that these service pricing arrangements include a cost optimization program or features in their service to drive efficiency.
### Plan for Data Transfer
An advantage of the cloud is that it is a managed network service. There is no longer the need to manage and operate a fleet of switches, routers, and other associated network equipment. Networking resources in the cloud are consumed and paid for in the same way you pay for CPU and storage—you only pay for what you use. Efficient use of networking resources is required for cost optimization in the cloud.
**Perform data transfer modeling:** Understand where the data transfer occurs in your workload, the cost of the transfer, and its associated benefit. This allows you to make an informed decision to modify or accept the architectural decision. For example, you may have a Multi-Availability Zone configuration where you replicate data between the Availability Zones. You model the cost of structure and decide that this is an acceptable cost (similar to paying for compute and storage in both Availability Zone) to achieve the required reliability and resilience.
Model the costs over different usage levels. Workload usage can change over time, and different services may be more cost effective at different levels.
Use [AWS Cost Explorer](https://console.aws.amazon.com/sts/hasilOption) or the [Cost and Usage Report (CUR)](https://console.aws.amazon.com/sts/hasilOption) to understand and model your data transfer costs. Configure a proof of concept (PoC) or test your workload, and run a test with a realistic simulated load. You can model your costs at different workload demands.
**Optimize Data Transfer:** Architecting for data transfer ensures that you minimize data transfer costs. This may involve using content delivery networks to locate data closer to users, or using dedicated network links from your premises to AWS. You can also use WAN optimization and application optimization to reduce the amount of data that is transferred between components.
**Select services to reduce data transfer costs:** [Amazon CloudFront](https://console.aws.amazon.com/sts/hasilOption) is a global content delivery network that delivers data with low latency and high transfer speeds. It
caches data at edge locations across the world, which reduces the load on your resources. By using CloudFront, you can reduce the administrative effort in delivering content to large numbers of users globally, with minimum latency.
**AWS Direct Connect** allows you to establish a dedicated network connection to AWS. This can reduce network costs, increase bandwidth, and provide a more consistent network experience than internet-based connections.
**AWS VPN** allows you to establish a secure and private connection between your private network and the AWS global network. It is ideal for small offices or business partners because it provides quick and easy connectivity, and it is a fully managed and elastic service.
**VPC Endpoints** allow connectivity between AWS services over private networking and can be used to reduce public data transfer and **NAT gateways** costs. **Gateway VPC endpoints** have no hourly charges, and support Amazon S3 and Amazon DynamoDB. **Interface VPC endpoints** are provided by AWS PrivateLink and have an hourly fee and per GB usage cost.
**Resources**
Refer to the following resources to learn more about AWS best practices for cost effective resources.
- [AWS Managed Services: Enterprise Transformation Journey Video](#)
- [Analyzing Your Costs with Cost Explorer](#)
- [Accessing Reserved Instance Recommendations](#)
- [Getting Started with Rightsizing Recommendations](#)
- [Spot Instances Best Practices](#)
- [Spot Fleets](#)
- [How Reserved Instances Work](#)
- [AWS Global Infrastructure](#)
- [Spot Instance Advisor](#)
- [Well-Architected Labs - Cost Effective Resources](#)
Manage Demand and Supply Resources
When you move to the cloud, you pay only for what you need. You can supply resources to match the workload demand at the time they’re needed — eliminating the need for costly and wasteful overprovisioning. You can also modify the demand using a throttle, buffer, or queue to smooth the demand and serve it with less resources.
The economic benefits of just-in-time supply should be balanced against the need to provision to account for resource failures, high availability, and provision time. Depending on whether your demand is fixed or variable, plan to create metrics and automation that will ensure that management of your environment is minimal – even as you scale. When modifying the demand, you must know the acceptable and maximum delay that the workload can allow.
In AWS, you can use a number of different approaches for managing demand and supplying resources. The following sections describe how to use these approaches:
- Analyze the workload
- Manage demand
- Demand-based supply
- Time-based supply
**Analyze the workload:** Know the requirements of the workload. The organization requirements should indicate the workload response times for requests. The response time can be used to determine if the demand is managed, or if the supply of resources will change to meet the demand.
The analysis should include the predictability and repeatability of the demand, the rate of change in demand, and the amount of change in demand. Ensure that the analysis is performed over a long enough period to incorporate any seasonal variance, such as end-of-month processing or holiday peaks.
Ensure that the analysis effort reflects the potential benefits of implementing scaling. Look at the expected total cost of the component, and any increases or decreases in usage and cost over the workload lifetime.
You can use [AWS Cost Explorer](https://aws.amazon.com/cost explorer) or [Amazon QuickSight](https://aws.amazon.com/quick sight) with the CUR or your application logs to perform a visual analysis of workload demand.
Manage Demand
Manage Demand – Throttling: If the source of the demand has retry capability, then you can implement throttling. Throttling tells the source that if it cannot service the request at the current time it should try again later. The source will wait for a period of time and then re-try the request. Implementing throttling has the advantage of limiting the maximum amount of resources and costs of the workload. In AWS, you can use Amazon API Gateway to implement throttling. Refer to the Well-Architected Reliability pillar whitepaper for more details on implementing throttling.
Manage Demand – Buffer based: Similar to throttling, a buffer defers request processing, allowing applications that run at different rates to communicate effectively. A buffer-based approach uses a queue to accept messages (units of work) from producers. Messages are read by consumers and processed, allowing the messages to run at the rate that meets the consumers’ business requirements. You don’t have to worry about producers having to deal with throttling issues, such as data durability and backpressure (where producers slow down because their consumer is running slowly).
In AWS, you can choose from multiple services to implement a buffering approach. Amazon SQS is a managed service that provides queues that allow a single consumer to read individual messages. Amazon Kinesis provides a stream that allows many consumers to read the same messages.
When architecting with a buffer-based approach, ensure that you architect your workload to service the request in the required time, and that you are able to handle duplicate requests for work.
Dynamic Supply
Demand-based supply: Leverage the elasticity of the cloud to supply resources to meet changing demand. Take advantage of APIs or service features to programmatically vary the amount of cloud resources in your architecture dynamically. This allows you to scale components in your architecture, and automatically increase the number of resources during demand spikes to maintain performance, and decrease capacity when demand subsides to reduce costs.
Auto Scaling helps you adjust your capacity to maintain steady, predictable performance at the lowest possible cost. It is a fully managed and free service that integrates with Amazon EC2 instances and Spot Fleets, Amazon ECS, Amazon DynamoDB, and Amazon Aurora.
Auto Scaling provides automatic resource discovery to help find resources in your workload that can be configured, it has built-in scaling strategies to optimize performance, costs or a balance between the two, and provides predictive scaling to assist with regularly occurring spikes.
Auto Scaling can implement manual, scheduled or demand based scaling, you can also use metrics and alarms from Amazon CloudWatch to trigger scaling events for your workload. Typical metrics can be standard Amazon EC2 metrics, such as CPU utilization, network throughput, and ELB observed request/response latency. When possible, you should use a metric that is indicative of customer experience, typically this a custom metric that might originate from application code within your workload.
When architecting with a demand-based approach keep in mind two key considerations. First, understand how quickly you must provision new resources. Second, understand that the size of margin between supply and demand will shift. You must be ready to cope with the rate of change in demand and also be ready for resource failures.
**Elastic Load Balancing** (ELB) helps you to scale by distributing demand across multiple resources. As you implement more resources, you add them to the load balancer to take on the demand. AWS ELB has support for EC2 Instances, containers, IP addresses ,and Lambda functions.
**Time-based supply:** A time-based approach aligns resource capacity to demand that is predictable or well-defined by time. This approach is typically not dependent upon utilization levels of the resources. A time-based approach ensures that resources are available at the specific time they are required, and can be provided without any delays due to start-up procedures and system or consistency checks. Using a time-based approach, you can provide additional resources or increase capacity during busy periods.
You can use scheduled Auto Scaling to implement a time-based approach. Workloads can be scheduled to scale out or in at defined times (for example, the start of business hours) thus ensuring that resources are available when users or demand arrives.
You can also leverage the [AWS APIs and SDKs](https://aws.amazon.com/api/) and [AWS CloudFormation](https://aws.amazon.com/cloudformation/) to automatically provision and decommission entire environments as you need them. This approach is well suited for development or test environments that run only in defined business hours or periods of time.
You can use APIs to scale the size of resources within an environment (vertical scaling). For example, you could scale up a production workload by changing the instance size...
or class. This can be achieved by stopping and starting the instance and selecting the different instance size or class. This technique can also be applied to other resources, such as EBS Elastic Volumes, which can be modified to increase size, adjust performance (IOPS) or change the volume type while in use.
When architecting with a time-based approach keep in mind two key considerations. First, how consistent is the usage pattern? Second, what is the impact if the pattern changes? You can increase the accuracy of predictions by monitoring your workloads and by using business intelligence. If you see significant changes in the usage pattern, you can adjust the times to ensure that coverage is provided.
**Dynamic Supply:** You can use AWS Auto Scaling, or incorporate scaling in your code with the AWS API or SDKs. This reduces your overall workload costs by removing the operational cost from manually making changes to your environment, and can be performed much faster. This will ensure that the workload resourcing best matches the demand at any time.
**Resources**
Refer to the following resources to learn more about AWS best practices for managing demand and supplying resources.
- [API Gateway Throttling](#)
- [Getting Started with Amazon SQS](#)
- [Getting Started with Amazon EC2 Auto Scaling](#)
**Optimize Over Time**
In AWS, you optimize over time by reviewing new services and implementing them in your workload.
**Review and Implement New Services**
As AWS releases new services and features, it is a best practice to review your existing architectural decisions to ensure that they remain cost effective. As your requirements change, be aggressive in decommissioning resources, components, and workloads that you no longer require. Consider the following to help you optimize over time:
- Develop a workload review process
• Review and implement services
**Develop a workload review process:** To ensure that you always have the most cost efficient workload, you must regularly review the workload to know if there are opportunities to implement new services, features, and components. To ensure that you achieve overall lower costs the process must be proportional to the potential amount of savings. For example, workloads that are 50% of your overall spend should be reviewed more regularly, and more thoroughly, than workloads that are 5% of your overall spend. Factor in any external factors or volatility. If the workload services a specific geography or market segment, and change in that area is predicted, more frequent reviews could lead to cost savings. Another factor in review is the effort to implement changes. If there are significant costs in testing and validating changes, reviews should be less frequent.
Factor in the long-term cost of maintaining outdated and legacy, components and resources, and the inability to implement new features into them. The current cost of testing and validation may exceed the proposed benefit. However, over time, the cost of making the change may significantly increase as the gap between the workload and the current technologies increases, resulting in even larger costs. For example, the cost of moving to a new programming language may not currently be cost effective. However, in five years time, the cost of people skilled in that language may increase, and due to workload growth, you would be moving an even larger system to the new language, requiring even more effort than previously.
Break down your workload into components, assign the cost of the component (an estimate is sufficient), and then list the factors (for example, effort and external markets) next to each component. Use these indicators to determine a review frequency for each workload. For example, you may have webservers as a high cost, low change effort, and high external factors, resulting in high frequency of review. A central database may be medium cost, high change effort, and low external factors, resulting in a medium frequency of review.
**Review the workload and implement services:** To realize the benefits of new AWS services and features, you must execute the review process on your workloads and implement new services and features as required. For example, you might review your workloads and replace the messaging component with Amazon Simple Email Service (SES). This removes the cost of operating and maintaining a fleet of instances, while providing all the functionality at a reduced cost.
Conclusion
Cost optimization and Cloud Financial Management is an ongoing effort. You should regularly work with your finance and technology teams, review your architectural approach, and update your component selection.
AWS strives to help you minimize cost while you build highly resilient, responsive, and adaptive deployments. To truly optimize the cost of your deployment, take advantage of the tools, techniques, and best practices discussed in this paper.
Contributors
Contributors to this document include:
- Philip Fitzsimons, Sr Manager Well-Architected, Amazon Web Services
- Nathan Besh, Cost Lead Well-Architected, Amazon Web Services
- Levon Stepanian, BDM, Cloud Financial Management, Amazon Web Services
- Keith Jarrett, Business Development Lead – Cost Optimization
- PT Ng, Commercial Architect, Amazon Web Services
- Arthur Basbaum, Business Developer Manager, Amazon Web Service
- Jarman Hauser, Commercial Architect, Amazon Web Services
Further Reading
For additional information, see:
- AWS Well-Architected Framework
Document Revisions
<table>
<thead>
<tr>
<th>Date</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>April 2020</td>
<td>Updated to incorporate CFM, new services, and integration with the Well-Architected tool.</td>
</tr>
<tr>
<td>July 2018</td>
<td>Updated to reflect changes to AWS and incorporate learnings from reviews with customers.</td>
</tr>
<tr>
<td>November 2017</td>
<td>Updated to reflect changes to AWS and incorporate learnings from reviews with customers.</td>
</tr>
<tr>
<td>November 2016</td>
<td>First publication</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://d1.awsstatic.com/whitepapers/architecture/AWS-Cost-Optimization-Pillar.pdf", "len_cl100k_base": 15227, "olmocr-version": "0.1.53", "pdf-total-pages": 41, "total-fallback-pages": 0, "total-input-tokens": 87697, "total-output-tokens": 16835, "length": "2e13", "weborganizer": {"__label__adult": 0.0006346702575683594, "__label__art_design": 0.0019741058349609375, "__label__crime_law": 0.0008797645568847656, "__label__education_jobs": 0.00818634033203125, "__label__entertainment": 0.000705718994140625, "__label__fashion_beauty": 0.00039076805114746094, "__label__finance_business": 0.2301025390625, "__label__food_dining": 0.0005965232849121094, "__label__games": 0.0018062591552734375, "__label__hardware": 0.00417327880859375, "__label__health": 0.0013914108276367188, "__label__history": 0.00086212158203125, "__label__home_hobbies": 0.0006346702575683594, "__label__industrial": 0.00225067138671875, "__label__literature": 0.0010023117065429688, "__label__politics": 0.0007805824279785156, "__label__religion": 0.0007233619689941406, "__label__science_tech": 0.271240234375, "__label__social_life": 0.0003733634948730469, "__label__software": 0.1827392578125, "__label__software_dev": 0.286376953125, "__label__sports_fitness": 0.0003821849822998047, "__label__transportation": 0.0012454986572265625, "__label__travel": 0.0006222724914550781}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 81683, 0.00235]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 81683, 0.16878]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 81683, 0.92061]], "google_gemma-3-12b-it_contains_pii": [[0, 69, false], [69, 857, null], [857, 857, null], [857, 857, null], [857, 1485, null], [1485, 3113, null], [3113, 5427, null], [5427, 7184, null], [7184, 9022, null], [9022, 11334, null], [11334, 13584, null], [13584, 15917, null], [15917, 18019, null], [18019, 20291, null], [20291, 22268, null], [22268, 24785, null], [24785, 27583, null], [27583, 30271, null], [30271, 32229, null], [32229, 34993, null], [34993, 37438, null], [37438, 39735, null], [39735, 41218, null], [41218, 43709, null], [43709, 46462, null], [46462, 48893, null], [48893, 51507, null], [51507, 53740, null], [53740, 56245, null], [56245, 58634, null], [58634, 61385, null], [61385, 64005, null], [64005, 66756, null], [66756, 68389, null], [68389, 70461, null], [70461, 72843, null], [72843, 75527, null], [75527, 77384, null], [77384, 80013, null], [80013, 80976, null], [80976, 81683, null]], "google_gemma-3-12b-it_is_public_document": [[0, 69, true], [69, 857, null], [857, 857, null], [857, 857, null], [857, 1485, null], [1485, 3113, null], [3113, 5427, null], [5427, 7184, null], [7184, 9022, null], [9022, 11334, null], [11334, 13584, null], [13584, 15917, null], [15917, 18019, null], [18019, 20291, null], [20291, 22268, null], [22268, 24785, null], [24785, 27583, null], [27583, 30271, null], [30271, 32229, null], [32229, 34993, null], [34993, 37438, null], [37438, 39735, null], [39735, 41218, null], [41218, 43709, null], [43709, 46462, null], [46462, 48893, null], [48893, 51507, null], [51507, 53740, null], [53740, 56245, null], [56245, 58634, null], [58634, 61385, null], [61385, 64005, null], [64005, 66756, null], [66756, 68389, null], [68389, 70461, null], [70461, 72843, null], [72843, 75527, null], [75527, 77384, null], [77384, 80013, null], [80013, 80976, null], [80976, 81683, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 81683, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 81683, null]], "pdf_page_numbers": [[0, 69, 1], [69, 857, 2], [857, 857, 3], [857, 857, 4], [857, 1485, 5], [1485, 3113, 6], [3113, 5427, 7], [5427, 7184, 8], [7184, 9022, 9], [9022, 11334, 10], [11334, 13584, 11], [13584, 15917, 12], [15917, 18019, 13], [18019, 20291, 14], [20291, 22268, 15], [22268, 24785, 16], [24785, 27583, 17], [27583, 30271, 18], [30271, 32229, 19], [32229, 34993, 20], [34993, 37438, 21], [37438, 39735, 22], [39735, 41218, 23], [41218, 43709, 24], [43709, 46462, 25], [46462, 48893, 26], [48893, 51507, 27], [51507, 53740, 28], [53740, 56245, 29], [56245, 58634, 30], [58634, 61385, 31], [61385, 64005, 32], [64005, 66756, 33], [66756, 68389, 34], [68389, 70461, 35], [70461, 72843, 36], [72843, 75527, 37], [75527, 77384, 38], [77384, 80013, 39], [80013, 80976, 40], [80976, 81683, 41]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 81683, 0.01653]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
b9835e51bbd1eee8cd3edb45412826d1300d55b0
|
Mathematical Programming Modulo Strings
Ankit Kumar and Panagiotis Manolios
Northeastern University
Email: {ankitk, pete}@ccs.neu.edu
I. INTRODUCTION
The problem of solving string equations has interested mathematicians and computer scientists for decades. Security, software engineering and verification applications, in particular, have generated a renewed interest in string solvers. Security applications include finding cross-site scripting vulnerabilities in Web applications, SQL injection attacks and fuzzing [1], [2], [3], [4], [5]. Software engineering applications include testcase generation, symbolic evaluation and flow analysis [6], [7], [8]. Programming language applications include type inference for array processing languages [9], [10].
The basic problem is easy to define. Let $\Gamma$ be a non-empty set of constants. The elements of $\Gamma^*$ form a free monoid, i.e., a structure with a single associative operation, corresponding to concatenation, and an identity element $e$. Elements of $\Gamma^*$ are called strings or words. Let $\mathcal{X}$ be a set of variables over $\Gamma^*$ and let $\mathcal{Y}$ be a set of variables over such that $\Gamma$, $\mathcal{X}$ and $\mathcal{Y}$ are disjoint. Elements in $\mathcal{Y}$ are also called unit variables. Let $\mathcal{Z} = \mathcal{X} \cup \mathcal{Y}$. Elements of the free monoid $(\Gamma \cup \mathcal{Z})^*$ are called sequences, again with $e$ as the identity. A normal substitution is a partial function $\rho : \mathcal{Z} \rightarrow (\Gamma \cup \mathcal{Z})^*$. Every substitution can be extended to the domain $(\Gamma \cup \mathcal{Z})$, by defining $\rho(a) = a$ for all $a$ not in the domain of $\rho$. We can also extend the domain to $(\Gamma \cup \mathcal{Z})^*$ in the standard way. $w\rho$ stands for the application of substitution $\rho$ to the sequence $w$ and it extends naturally to sequence equations. A solution of a set of equations $\{u_1 = v_1, u_2 = v_2, \ldots, u_n = v_n\}$ is a substitution $\rho$ that when applied to each equation yields identical sequences, i.e., $\{u_1\rho = v_1\rho, u_2\rho = v_2\rho, \ldots, u_n\rho = v_n\rho\}$ is a set of syntactic equivalences over $(\Gamma \cup \mathcal{Z})^*$. The problem statement is: given a set of sequence equations $\{u_1 = v_1, u_2 = v_2, \ldots, u_n = v_n\}$ find a solution if there exists one, otherwise return unsat.
Related Work. Makanin, in 1977, proved that the satisfiability of string equations is decidable [11]. A series of results on complexity followed, after which Plandowski showed that the problem is in polynomial space [12]. String solvers supporting a variety of theories are available, e.g., Z3Str3 [13], CVC4 [14], [15], S3P [16], Norn [17], TRAU [18], SeqSolve [19], Sloth [2], Kepler22 [20] and HAMPI [1]. Z3Str3 and CVC4 are multi-theory SMT solvers which consider unbounded string equations with concatenation, substring, replace and length functionality. Together with S3P and Norn, these tools handle a variety of string constraints including string equations, length constraints and regular language membership. However, these tools are incomplete. HAMPI works only for problems with one string variable of fixed size. Kepler22 is a decision procedure for the straight line and quadratic fragments of string equations. Norn and TRAU can decide only the acyclic fragment whereas Sloth decides straight line and acyclic fragments. To the best of our knowledge, there is no solver that for decidable fragments is both theoretically and practically complete, e.g., none of the above solvers are able to solve the string equation $y_x y_x y_c y_z y_c y_a y = y a c w a z y b y x$. Therefore it is important to explore new techniques for solving string equations. One of the most promising existing techniques uses context-dependent techniques to improve the reasoning of string constraints in the context of DPLL(T)-based SMT solvers [15]. Similarly, our work introduces new techniques for reasoning in the context of BC(T)-based (Branch and Cut Modulo T) MPMT solvers [21], [22].
Contributions. Our contributions include (1) TranSeq, a new non-deterministic, branching transition system that can be used as part of the MPMT framework for combining decision procedures, (2) the SeqSolve solver, an implementation of TranSeq which resolves non-deterministic choices in a way designed to infer as much as possible with as few computational resources as possible, (3) proof sketches of soundness, completeness and termination for TranSeq and (4) an evaluation of SeqSolve using a set of benchmarks from related work, as well as Remora examples [9], [10]. We use publicly available benchmarks, being careful to evaluate only the string solving capabilities of our tool, not irrelevant aspects of the underlying SMT/MPMT tools. The integration of our solver into SMT/MPMT tools is briefly discussed. There are over 1,100 problems in our benchmark and no existing string solver can solve all of them. Experimental results show that SeqSolve is more efficient and complete than existing solvers.
Consider the string equation \( b = a \). The constant \( b \) differs from the constant \( a \) so this equation is unsatisfiable. Our algorithm determines by performing partial evaluation that includes evaluating constant prefixes and suffixes of equations.
**Example 2 [Trim]** Consider \( xab = xbb \). Our algorithm trims common prefixes and suffixes from both sides of the input equation to get \( a = b \) which is unsatisfiable by ConstUnsat.
**Example 3 [Decompose]** Consider \( xyazy = yxubyz \). Prefixes \( xy \) and \( yx \) have provably equal lengths. So do the suffixes \( yz \) and \( yz \). Therefore our algorithm decomposes the input equation into three equations: \( xy = yz, a = ub \) and \( zy = yz \). Equation \( a = ub \) can be further decomposed into \( a = b \) and \( u = \epsilon \), which is unsatisfiable by ConstUnsat.
**Example 4 [EqLength]** Consider \( wxyyvu = vyxyw \). Decomposition generates the two distinct equations \( wv = vu \) and \( xy = yz \). Notice that if an equation is satisfiable, then both sides have to have the same length and our algorithm generates the constraint \( l_x + 1 + l_y = l_y + l_x \) where \( l_x \) and \( l_y \) denote the lengths of \( x \) and \( y \), respectively, which is unsatisfiable.
**Example 5 [EqConsts]** Consider \( ax = xb \). If the equation is satisfiable, then both sides of the equation must have the same number of occurrences of each constant. To enforce this, our algorithm generates the constraint \( 1 + c_a^x = c_b^x \), where \( c_a^x \) is the number of \( a \)'s in \( x \), which is unsatisfiable.
**Example 6 [VarElim]** Consider the set of (implicitly conjoined) string equations \( \{uv = vu, xa = ax, cy = x\} \). The last equation has the form of a definition and this allows our algorithm to eliminate \( x \) by applying the appropriate substitution to the set of equations, giving us \( \{uv = vu, cy = acy\} \). Since \( cya = acy \) is unsatisfiable, so is the set.
**Example 7 [VarSplit]** Consider \( xxa = cyx \). One side starts with the constant \( c \) so the other side must also start with \( c \), which means \( x \) cannot be empty and must start with a \( c \). Our algorithm detects this and adds the equation \( x = cx \), where \( \hat{x} \) is a new string variable. After eliminating \( x \) and trimming, we wind up with the equation \( \hat{x}c\hat{x}a = y\hat{x}x \), which decomposes into \( \hat{x}c = y \) and \( \hat{x}a = cx \). The Eq_consts analysis (Example 5) infers that the second equation is unsatisfiable. Our algorithm also does this for suffixes.
**Example 8 [VarSubst]** Consider \( wuazwua = cywuz \). The equation is equi-satisfiable with \( xxa = cyx \): we substitute a new string variable, \( x \), for the sequence of string variables, \( wuaz \), thereby eliminating all occurrences of \( w, u \) and \( z \) from all string equations. The resulting equation is unsatisfiable by VarSplit (see Example 7).
**Example 9 [Rewrite]** Consider the set of (implicitly conjoined) string equations \( \{zv = ba, xxazv = cyxba\} \). The first equality can be used to rewrite the second equality to \( xxazv = cyxazv \) which can be trimmed to \( xx = cyx \), which is unsatisfiable, as per Example 7.
**Example 10 [LenSplit]** Consider \( xbyu = caxz \). The length of the prefix \( xb \) is strictly less than the length of the prefix \( cax \), which allows us to infer that \( yu = yz \) for some new string variable \( y \neq \epsilon \). We can rewrite \( yu \) to \( yz \) (see Example 9) and after trimming, we wind up with the equation \( xby = cax \), which is unsatisfiable (see Example 5).
**Example 11 [EqWords]** Consider \( xbcay = ycbax \). Let \( W_{ca}^x \) and \( W_{ca}^y \) be the number of occurrences of a word \( ca \) in \( x \) and \( y \) respectively. If the equation is satisfiable, then both sides must have the same number of \( ca \) occurrences. To enforce this, our algorithm generates the constraint \( W_{ca}^x + 1 + W_{ca}^y = W_{ca}^y + W_{ca}^x \), which is unsatisfiable. Consider \( bxbacw = cbaczw \), which shows that counting words requires more care than what the above example suggests, e.g., to count the occurrences of \( bc \), we have to take into account whether \( c \) is a prefix of \( w \), whether \( b \) is a suffix of \( x \), whether \( x \) is empty, and so on. We use 0-1 indicator variables \( P_w \) and \( P_y \) denoting the above conditions, respectively. Now, with just the \( ab \) occurrence analysis, we can use variable splitting on \( w \) (\( w \) ends in an \( a \)) and then on \( v \) (\( v \) ends in an \( a \)) to derive a contradiction.
**Example 12 [SAT]** None of the string solvers we tried are able to solve the string equation \( xcyzyxyc = yacwazvbuax \). This equation is outside the scope of Kepler22, StrSolve, Hampi and Sloth, Sloth, TRAU and S3P return \( unsat \), which is wrong. Nom, Z3Str3 and CVC4 timed out after 1,000 seconds, which shows that existing tools are incomplete, in a practical sense. Our solver finds the assignment \( x = aba, y = ab, u = cbac \) and \( v, w, z = \epsilon \) in a fraction of a second.
### III. BLOCKS, SUBSTITUTIONS AND THEORIES
Suppose that a sequence \( u \) has an \( l \) length subsequence of consecutive occurrences of the constant \( a \). This subsequence can be compactly represented by the pair \( (a, l) \), which we refer to as a block. A block in \( \Gamma \times P_{Exp} \) where
\[
P_{Exp} = \{ x \mid P_{Exp} + P_{Exp} \not= P_{Exp} \}
\]
and \( x \) is a variable over positive natural numbers, \( P \). We require that a \( P_{Exp} \) is positive. A sequence that allows blocks
is called an extended sequence (es); an extended sequence equation (ese) is similarly defined. The set of extended sequences es is \((\Gamma \cup (\Gamma \times PExp) \cup Z)^*\). We define a function compress : es \(\rightarrow (\Gamma, PExp) \cup Z^*\) which given an (extended) sequence, replaces contiguous occurrences of each constant by its block such that no two blocks of the same constant are adjacent to each other, thus returning a unique maximally compressed sequence. We define the following useful functions, which given an extended sequence \(U\): (1) Elem : es \(\rightarrow 2^{\Gamma \cup Z \cup (\Gamma \times PExp)}\) returns the set of elements of \(U\); (2) Atoms : es \(\rightarrow 2^{\Gamma \cup Z}\) returns the set of variables and constants occurring in \(U\); (3)_consts : es \(\rightarrow 2^Z\) returns the set of constants in \(U\). (4) Vars : es \(\rightarrow 2^Z\) returns the set of variables in \(U\). These functions extend naturally to eses and to sets of es and eses. An extended sequence \(U\) represents a sequence \(u\) if \(u\) is obtained from \(U\) by replacing every block \((\alpha, n)\) by \(\alpha\) repeated \(n\) times. Note that \(n\) needs to be a positive integer. Extended sequences \(U\) and \(V\) are syntactically equivalent if they represent the same sequence. We use \(\equiv\) to denote syntactic equivalence. For example, \((\alpha, 2)\alpha X \equiv \alpha(\alpha, 2)X\), as both of them represent the sequence \(\alpha\alpha\alpha X\). Notice that syntactic equivalence is an equivalence relation.
We define a substitution \(\sigma\) to be a partial function of the form \(\sigma : es \rightarrow es\); Given substitution \(\sigma\), let \(\sigma_x\) be \(\sigma\) restricted to \(Z\) and let \(\sigma_x\) be \(\sigma_x\sigma_v\). Let \(\text{dom}(f)\) and \(\text{cod}(f)\) be the domain and codomain of function \(f\), respectively. Note that \(\text{dom}(\sigma) \subseteq Z\), so \(\sigma\) is a normal substitution. Substitutions \(\sigma_x\) and \(\sigma_v\) partition \(\sigma\) and have disjoint domains. We say that \(\sigma_x\) is an extended substitution, as its domain may contain sequences. We require substitutions to be well-typed, i.e., \(\sigma_v\) must map unit variables to sequences of unit length. \(U\sigma\) stands for the application of substitution \(\sigma\) to \(U\) \(\in es\). This notation extends naturally to equations and sets of equations. In order for application to be well-defined, we require that \(\sigma\) is consistent, as defined below. We say that \(\sigma\) is uniquely defined if for all \(x, y \in \text{dom}(\sigma)\), if \(x \neq y\) then \(\text{Atoms}(x) \cap \text{Atoms}(y) = \emptyset\). To see why we require this, consider the case where \(\sigma_v = \{x:a\}\); \(\sigma_v = \{y:a\}\); note that \((y\sigma)x\) is ambiguous.
Given two uniquely defined substitutions, \(\sigma\) and \(\tau\), we say that they are equivalent, written \(\sigma \equiv \tau\), if for all \(U \in es\), we have \(U\sigma \equiv U\tau\). We say that \(\sigma\) is consistent if it is uniquely defined and \(\forall \tau : \text{dom}(\tau) \subseteq Z \land \sigma \equiv \tau\), i.e., \(\sigma\) is equivalent to a normal substitution. Consider \(\sigma = \{x:\text{abc}, y:\text{a}\}\). Even though \(\sigma\) is uniquely defined, it cannot be expressed as a normal substitution. From now on, unless we say otherwise, all substitutions are implicitly assumed to be consistent. A substitution \(\sigma\) is said to solve an es \(U = V\) if \(U\sigma \equiv V\sigma\); \(\sigma\) solves \(Q\), a set of eses, if \(\sigma\) solves every es in \(Q\). A word \(ab\) is an es in which no prefix is a suffix.
**Theorem 1.** If \(\sigma\) is a consistent substitution and \(x_1, \ldots, x_n \in Z\) are distinct variables such that \(n \geq 0\) and \(\{x_1, \ldots, x_n\} \cap \text{Vars}(\text{dom}(\sigma)) = \emptyset\), then \(\sigma \cup \{x_1:V_1, \ldots, x_n:V_n\}\) (where \(V_1, \ldots, V_n\) are extended sequences of the right type) is a consistent substitution.
A theory is a pair \(T = (\Sigma, I)\), where \(\Sigma\) is a signature and \(I\) is a class of \(\Sigma\)-interpretations, the models of \(T\). A set of formulas, \(\Psi\), entails in \(T\) a \(\Sigma\)-formula \(\phi\), written \(\Psi \models_T \phi\), if every interpretation in \(I\) that satisfies all formulas in \(\Psi\) satisfies \(\phi\) as well. The set \(\Psi\) is unsatisfiable in \(T\) if \(\Psi \not\models_T \bot\).
Let \(LIA\) be a theory with signature \((0, 1, +, -, \leq)\) interpreted over the standard model of integers \(\mathbb{Z}\). A linear constraint is a formula of the form \(\sum_{i \in [1..n]} a_i x_i \leq b\), where \(x_i\) are variables and \(a_i\) and \(b\) are integer constants. For a collection of linear constraints \(C, C \models_{\text{lia}} \bot\) means that \(C\) is unsatisfiable in \(LIA\), whereas \(C \not\models_{\text{lia}} \bot\) means that a model exists for \(C\). Our algorithm accepts and generates linear constraints on the conjunction of input string equations. It assumes a sound, complete and terminating backend ILP solver for such constraints. Let \(ES\) be a theory of (extended) sequences over a signature \(\Sigma_{ES}\) with two sorts: extended sequences \(es\) and integers \((\mathbb{Z})\) along with an infinite set of variables over each sort. \(\Sigma_{ES}\) also includes constants in \(\Gamma\), \(PExp\) expressions, blocks, (extended) sequences and functions \(\text{len}\) interpreted as the string length function, \(\text{countConst}\) interpreted as a function counting the number of specified constant in a sequence and \(\text{countWords}\) interpreted as a function counting the number of specified words in a sequence.
**IV. MPMT-BASED STRING SOLVER**
Our algorithm, SeqSolve, accepts a conjunction of string equations \(Q\) as well as initial constraints \(\text{C}_{\text{init}}\) and returns either unsat, unknown or sat along with a solution. \(\text{C}_{\text{init}}\) is a set of initexp’s defined as
\[LExp := Z \mid x \mid \text{len}(u) \mid LExp + LExp \mid LExp - LExp\]
\[\text{initexp} := LExp \mid \text{abs} < \mid \text{abs} \leq \mid \text{abs} > \mid \text{abs} \geq \mid \text{abs} \neq \mid \text{abs} < \mid \text{abs} \geq \mid \text{abs} \leq \mid \text{abs} \neq \mid \text{abs} > \mid \text{abs} \neq \]
where \(x\) is an integer variable \((\mathbb{Z})\), \(u\) is an (extended) sequence and \(\text{len} : es \rightarrow \mathbb{N}\) is a function that returns length of \(u\). We refer to variables occurring in \(PExp\) and \(LExp\) expressions as numeric variables. Central to the algorithm is a nondeterministic transition system TranSeq with rules that operate on configurations consisting of (extended) sequence equations and sets of LIA constraints.
Our decision procedure can be integrated into MPMT solvers in a fine-grained way since MPMT is based on branching, using the branch-and-cut framework. However, in order to make the paper more self contained, we present TranSeq and SeqSolve with as few dependencies on the MPMT framework as possible.
Our decision procedure can be integrated into SMT solvers using the idea of recursive solvers: these are solvers whose decision procedures may depend on the solvers themselves. For example, we can integrate our decision procedure into Z3, even though our decision procedure uses Z3 as a backend solver, by using a separate Z3 process to handle the LIA constraints and one can use this integration as a backend solver.
for yet another decision procedure, and so on. As far as we know, we are the first to propose the idea of recursive solvers. For SMT solvers like Z3 that provide contexts and a stack with a push-pop interface to manage constraints, integration can be achieved using these features by creating a new context or stack frame, thereby allowing decision procedures to query the SMT solver without polluting its state.
A. Configurations
The algorithm works on configurations that include tuples of the form \( \langle \text{unsat} \rangle, \langle \text{unknown} \rangle, \langle \text{sat}, \sigma, C \rangle \) and \( \langle Q, \sigma, \text{vars}, C \rangle \) where (1) \( Q \) is a set of eses, (2) \( \sigma : \text{es} \rightarrow \text{es} \) is a (consistent) substitution, (3) \( \text{vars} \) is a superset of the variables in \( \mathcal{Z} \) which occur in \( Q \), (4) \( C \) is a union of constraints \( C_{\text{len}}, C_{\text{consts}}, C_{\text{words}} \) and a set of linear constraints corresponding to \( C_{\text{init}} \), where (i) \( C_{\text{len}} \) is a set of linear constraints regarding the lengths of variables in \( \text{vars} \). For \( x \in \text{vars} \), \( l_x \) is an integer variable denoting the length of \( x \) and \( e_x \) is a 0-1 indicator variable indicating whether \( x \) is empty. Linear constraints in \( C_{\text{len}} \) and \( C_{\text{init}} \) are over these integer variables and over \( P_{\text{Exp}} \) variables; (ii) \( C_{\text{consts}} \) is a set of linear constraints regarding the number of occurrences of constants in \( \text{vars} \). For \( x \in \text{vars} \), \( n_x^\sigma \) is an integer variable denoting the number of occurrences of the constant \( a \) in \( x \). Linear constraints in \( C_{\text{consts}} \) are over these variables as well as over variables of \( C_{\text{len}} \); (iii) \( C_{\text{words}} \) is a set of linear constraints regarding the number of words occurring in variables from \( \text{vars} \). Let \( x \in \text{vars} \) and \( s \in \text{consts}^* \). Then \( W_x^s \) denotes the number of \( s \) occurrences in \( x \); \( P_x^s \) and \( S_x^s \) are 0-1 indicator variables indicating whether \( x \) begins with \( s \) and ends with \( s \), respectively. Linear constraints in \( C_{\text{words}} \) are over these variables as well as over variables of \( C_{\text{len}} \).
The reason why we distinguish between \( C_{\text{len}}, C_{\text{consts}} \) and \( C_{\text{words}} \) is that it makes it easier to consider simplified transition systems that include only a subset of these kinds of constraints. We define sets \( \text{consts} \) and \( C_{\text{fuel}} \) where (1) \( \text{consts} \) is a superset of the constants from \( \Gamma \) occurring in \( Q \) and (2) \( C_{\text{fuel}} \) is a set of linear constraints over the \( l_x \) variables, used to guarantee termination. Both \( \text{consts} \) and \( C_{\text{fuel}} \) are generated once and never modified by our transition system. The rules in TranSeq depend on auxiliary functions that are used to generate LIA constraints or to simplify equations. All of these functions are described in the full version of this paper.
B. Transition System TranSeq
We describe a non-deterministic transition system TranSeq. TranSeq consists of a set of rules called derivation rules. A derivation rule applies to a configuration \( K \) if all of the rule’s premises are satisfied by \( K \). Such a rule is enabled for \( K \). A derivation tree is a tree where each node is a configuration and the children of any non-leaf node are exactly the configurations obtained by applying one of the derivation rules to the node. A configuration is terminal if no rules can be applied to it. We prove that terminal configurations are either of the form \( \langle \text{unsat} \rangle \), in which case we call them unsat terminal nodes, \( \langle \text{unknown} \rangle \), in which case we call them unknown terminal nodes, or of the form \( \langle \text{sat}, \sigma, C \rangle \), in which case we call them sat terminal nodes and \( \sigma, C \) can be used to generate a satisfying assignment to the equations appearing in the root of the tree.
A configuration \( K = \langle Q, \sigma, \text{vars}, C \rangle \) is sat (unsat) iff \( Q \cup C \cup C_{\text{fuel}} \) is sat (unsat). \( K \) is \( C \)-sat iff \( Q \cup C \) is sat. Notice that an unknown terminal node may be sat (or unsat). This discrepancy is due to the \( C_{\text{fuel}} \) constraints, which are provable upper bounds on the lengths of minimal solutions, but only if we have no length constraints in the input, so it is possible that \( K \) is \( C \)-sat, but the configuration is unsat and we generate an unknown terminal node. The derivation rules of TranSeq are given in guarded assignment form and can be categorized into three groups: (1) Terminal rules: Rules that yield terminal nodes. (2) Inference rules: Rules that generate new inferences. (3) Branching rules: Rules that generate multiple subproblems.
A derivation tree is closed if all its leaf nodes are terminal nodes. A derivation tree is unsat-closed if it is closed and all of its leaf nodes are unsat-terminal nodes. A derivation tree is unknown-closed if it is closed, has at least one unknown terminal node and has no sat-terminal nodes. We prove that if a derivation tree is unsat-closed, then the conjunction of the equations and constraints appearing in the root of the tree are unsatisfiable. A derivation tree for a set of sequence equations \( Q = \{ u_1=v_1, u_2=v_2, \ldots, u_n=v_n \} \) and some initial length constraints \( C_{\text{init}} \) (if provided) is a tree whose root, \( \text{genRoot}(Q, C_{\text{init}}) \), is defined in Algorithm 1 where \( \text{Choose}(X) \) is a function that given a non-empty set \( X \), returns an element of \( X \). \( C_{\text{len}}, C_{\text{consts}} \) and \( C_{\text{words}} \) are initialized with linear constraints by functions \( \text{initLen} \), \( \text{initConsts} \) and \( \text{initWordCount} \) respectively. These functions generate constraints which are satisfiable for any string variable. \( C_{\text{fuel}} \) comprises of constraints on the size of the minimum solution of each equation in \( Q \) which are calculated in function \( \text{initFuel} \) and are based on results from [23]. The sets \( \text{consts} \) and \( \text{vars} \) are supersets of the constants and variables occurring in \( Q \), respectively.
We define the function \( \text{toLIA} \), which given an \( \text{initexp} \) returns a linear constraint. Given \( \text{len}(x) \), where \( x \) is a sequence variable, \( \text{toLIA} \) returns \( l_x \); we extend this to \( \text{initexp} \) expressions in the obvious way and use \( \text{toLIA} \) to also generate fuel constraints. We denote the set of words we are interested in counting as \( \mathcal{W} \), which is global.
C. Rules in TranSeq
We now describe each rule in TranSeq. The conclusion of a rule describes how each component of a configuration is changed, if it does. Rules with two or more conclusions separated by ||, are branching rules, where each of the configurations are starting configurations for new branches in their derivation tree. In derivation rules, if \( Q \) is relevant, it appears on the top-left corner in the premise and as the last line of a concluding branch. \( A \) is an abbreviation for \( A \cup \{ t \} \) and \( A \sim t \) abbreviates \( A \setminus \{ t \} \). We use \( \equiv (\neq) \) for syntactic equivalence
Algorithm 1 genRoot(Q, Cinit) - Given input set of string equations Q, genRoot generates the root node of a derivation tree.
1: \(\sigma \leftarrow \{\}\)
2: vars \(\leftarrow \{x \mid x \in Z \land x \in w \land w=v \in Q\}\)
3: const \(\leftarrow \{a \mid a \in w \land a \in \Gamma \land w=v \in Q\}\)
4: if const = \(\emptyset \land \) vars \(\cap \) \(Y \neq \emptyset\) then
5: \(\) const \(\leftarrow \{\text{Choose}(\Gamma)\}\)
6: \(\) Clen \(\leftarrow \bigcup_{v \in \text{vars}, w \in \Gamma} \text{initLen}(v)\)
7: \(\) Cconst \(\leftarrow \bigcup_{v \in \text{vars}} \text{initConsts}(v, \text{const})\)
8: \(\) Cwords \(\leftarrow \bigcup_{v \in \text{vars}, w \in \Gamma} \text{initWordCount}(v, w)\)
9: \(\) C \(\leftarrow \text{toLIA}(C_{\text{init}}) \cup C_{\text{len}} \cup C_{\text{const}} \cup C_{\text{words}}\)
10: \(\) Cfuel \(\leftarrow \text{initFuel}(Q)\)
11: \(\) return \(\langle Q, \sigma, \text{vars}, C\rangle\)
(in-equivalence) and \(\neq\) for semantic equality (inequality).
**Terminal rules** When Q is empty, if C is unsatisfiable, LIAUUnsatisfies unsat otherwise Sat returns a sat configuration.
\[
\text{C} \models_{\text{LIA}} \perp_{\text{unsat}} \quad \text{LIAUUnsat}
\]
\[
\{\} \not\models_{\text{LIA}} \perp_{\text{sat}, \sigma, C} \quad \text{Sat}
\]
If the fuel constraints are needed to show unsatisfiability, then the rule FuelUnsat returns unsat if no initial linear constraints were provided, otherwise the rule Unknown returns unknown. Terminal rules are subject to fairness constraints, as described later.
\[
\begin{align*}
\text{C}_{\text{init}} &= \emptyset & \text{C} \cup \text{Cfuel} &\models_{\text{LIA}} \perp_{\text{unsat}} & \text{FuelUnsat} \\
\text{C}_{\text{init}} &\neq \emptyset & \text{C} &\not\models_{\text{LIA}} \perp_{\text{unsat}} & \text{Unknown}
\end{align*}
\]
If there exists an equation with syntactically different extended sequences on both sides, ConstUnsat infers unsat.
\[
\{U=V, \ldots\} \quad U \neq V \quad \text{Vars}(UV) = \emptyset \
\]
Note that we do not apply substitution \(\sigma\) to \(U\) and \(V\) when checking for syntactic equivalence, as shown below.
\[
\{U=V, \ldots\} \quad U\sigma \neq V\sigma \quad \text{Vars}(UV) = \emptyset \
\]
This is because, for any equation \(U=V \in Q\), we get the original rule due to \(U\sigma = U\) as a result of the invariant \(Q\sigma = Q\), which we prove later.
If one side of an equation contains a unit variable while the other side is empty, then YVarEmpty infers \(\langle \text{unsat}\rangle\).
\[
\{U=\epsilon, \ldots\} \quad e \in U \quad e \in Y \
\]
**DiffCons deduces unsat.** If both sides begin with blocks of unequal constants,
\[
\{U=\epsilon, \ldots\} \quad \alpha \in \text{Atoms}(U) \quad \alpha \in \text{consts} \\
\]
\[
\langle \text{unsat}\rangle \quad \text{ConstEmpty}
\]
\[
\{(\alpha, l)U=(\beta, m)V, \ldots\} \quad \alpha \neq \beta \\
\]
\[
\langle \text{unsat}\rangle \quad \text{DiffCons}
\]
The rules ConstEmpty and DiffCons deduce unsat based on how terms in an equation start, but there is a symmetry here that allows us to define rules that make the same deduction based on how terms end. For example, the symmetric version of DiffCons would start with \(\{U(\alpha, l) = V(\beta, m), \ldots\}\), but would otherwise be identical to DiffCons. When rules have this kind of symmetry, we denote it by underlining the name of the rule in its definition. These symmetric rules help with efficiency, but are not needed for completeness, so to simplify the rest of the presentation, we proceed as if they do not exist.
**Inference rules** Trim removes syntactically equal prefixes and suffixes from both sides of an equation; note that one of \(a, b\) can be \(\epsilon\). EqElim removes eses whose both sides are syntactically equivalent. Observe that Trim can be used to reduce an equation \(U=V\) which is syntactically equivalent on both sides, to get \(\epsilon=\epsilon\), in which case we get syntactic equivalence of both sides trivially.
\[
\{aUb=cVd, \ldots\} \quad a \equiv c \quad |ab| > 0 \quad b \equiv d \quad \{U=U, \ldots\} \
\]
\text{Trim}
\[
\{U=V, \ldots\} \quad |\text{splitEq}(U, V, C)| > 1 \
\]
\text{EqElim}
Decompose splits an ese \(U=V\) into multiple equations using length constraints. A simple example is given in Example 3.
\[
\{U=V, \ldots\} \quad \text{splitEq}(U, V, C) > 1 \
\]
\text{Decompose}
Compress converts an equation \(u=v \in Q\) into a maximally compressed sequence. Observe that the premise requires that there is at least one constant element in \(u=v\). Note that blocks such as \((a, 1)\) are not constants, as they are not elements of \(\Gamma\).
\[
\{u=v, \ldots\} \quad \text{Atoms}(uv) \cap \Gamma \neq \emptyset \quad \text{Compress}
\]
VarSubstitutes formalizes the idea from Example 8. Given \(W\), a non-empty subsequence in \(Q\) satisfying the conditions below, the rule replaces \(W\) with a new variable \(z\). We show later that for every node in a derivation tree generated by our algorithm, \(Q\sigma = Q\) holds; hence, the first condition for consistency of substitutions is satisfied. The second consistency condition is satisfied due to the premise that requires atoms of \(W\) and \(Q\{W:z\}\) to be disjoint. Hence, the substitution in the new configuration is consistent. The LIANewVar procedure generates numeric constraints for new variables. After this rule, it is called implicitly whenever a new variable is introduced.
\[
\{U=V, \ldots\} \quad (\exists S, T :: \text{SWT} = U \land |W| > 1) \
\]
\[
\text{Atoms}(W) \subseteq \text{vars} \quad z \in X \quad z \notin \text{vars} \
\]
\[
\text{Atoms}(W) \cap \text{Atoms}(U=V, \ldots) = \emptyset \quad \text{VarSubst}
\]
\[
\text{LIANewVar}(z) \
\]
\[
\sigma \leftarrow \sigma, W:z \
\]
\[
\{U=V, \ldots\} \quad \{W:z\} \
\]
Rewrite replaces a subsequence $S$ of $U$ by $T$, given that $S=T$ is an equation in $Q$. Rewrite can choose which occurrences to replace. Infinite derivation trees are ruled out with a fairness requirement that only allows us to use the Rewrite rule a finite number of times.
\[
\frac{\{U=V, S=\ldots\} \quad S \in U}{\{U:S\}=V, S=\ldots\}} \quad \text{Rewrite}
\]
EqLength, EqConsts and EqWords generate length, constant count and word count constraints implied by an equation. Function equateWordCount returns a linear constraint equating the number of occurrences of a word $w$ in $U$ and $V$.
\[
\frac{\{U=V, \ldots\} \quad \text{equateLen}(U,V) \subseteq C}{C_{\text{len}} \leftarrow C_{\text{len}} \cup \text{equateLen}(U,V)} \quad \text{EqLength}
\]
\[
\frac{\{U=V, \ldots\} \quad \text{equateCons}(U,V) \subseteq C}{C_{\text{consts}} \leftarrow C_{\text{consts}} \cup \text{equateCons}(U,V, \text{consts})} \quad \text{EqConsts}
\]
\[
\frac{\{U=V, w \in \text{consts} \} \quad \text{equateWordCount}(U,V,w) \not\subseteq C}{C_{\text{words}} \leftarrow C_{\text{words}} \cup \text{equateWordCount}(U,V,w)} \quad \text{EqWords}
\]
VarElim allows us to eliminate variables.
\[
\frac{x=\ldots}{x \notin V \quad x \in X} \quad \sigma \leftarrow \sigma, x;V \quad \{\ldots;\{x;V\} \quad \text{VarElim}
\]
Given an equation where one side starts with $c$ occurrences of variable $x$ and the other starts with $m$ occurrences of constant $\beta$, the rule VarSplit infers shape information about $x$ involving fresh variable $y$. $x$ can not be empty, and the prefix of $x^\alpha$ must be syntactically equivalent to $(\beta, m)$. Hence, VarSplit infers that $x$ is $(\beta, k)y$, where $c \geq k \geq m$. Note that $c$ is a constant, hence expressions such as $c \neq k$ do not take us out of the LIA fragment. Also note that if $k < m$, $y$ will have to start with $\beta$ as well, which we do not want. Hence we add an implication that if $k < m$ then $y$ is empty. We extend the set of equations with $x=(\beta, k)y$. Anytime we extend a set of equations with an equation of the form $x=\ldots$, we call VarElim to eliminate the variable $x$.
\[
\frac{x=(\beta, l)V=\ldots}{\sigma \neq \beta, c > 0} \quad x, y \in X \quad y \notin \vars
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, k > 0, (c-1)*k < m \leq c*k, \quad k < m \Rightarrow \epsilon_y = 1
\]
\[
C_{\text{words}} \leftarrow C_{\text{words}}, k < m \Rightarrow S_\beta^x = 1
\]
\[
\{x=(\beta, k)y, x^\alpha(\alpha,l)V=(\beta, m)V, \ldots\}
\]
Length constraints alone may not always be enough to split an equation. LenSplit introduces a new variable on one side of an equation such that the resulting equation is clearly split into smaller and possibly more tractable equations. Example 10 illustrates a simple example.
\[
\frac{U=W=szV, \ldots}{\text{C} \models_{\text{w}} \text{len}(U) < \text{len}(Sz)} \quad y, z \in X \quad y \notin \vars
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, \epsilon_{y} = 0 \quad \{U=ySz, W=yV, \ldots\}
\]
Inferences made by the backend LIA solver can be used to infer sequence variables. LIAEmpty concludes that a variable $x$ is empty if $\epsilon_x = 1$ is derived by the solver. Similarly, $x$ starts (ends) (with $\alpha$ iff the solver derives $P_\alpha^x = 1$) ($S_\alpha^x = 1$).
\[
\begin{align*}
C &\models_{\text{w}} \epsilon_x = 1 & x \in \vars \quad \{x=e\,\epsilon, \ldots\} \quad \text{LIAEmpty} \\
C &\models_{\text{w}} P_\alpha^x = 1 & y \in X \quad \{y=\alpha y, \ldots\} \quad \text{LIAEmpty} \\
C &\models_{\text{w}} S_\alpha^x = 1 & y \in X \quad \{y=\alpha y, \ldots\} \quad \text{LIAEnd}
\end{align*}
\]
Given an equation where one side is empty, XVarEmpty infers that a variable $x \in X$ in the other side must also be empty. If the two sides of an "$e\,\epsilon$" start with unit variables $x$ and $y$, then DiffYYVars infers that both the variables must be equal.
\[
\begin{align*}
\{x=e\,\epsilon, \ldots\} \quad \{xU=yV, \ldots\} \\
x \in U \quad x \in X \quad x \neq y \\
x, y \in \vars \quad \{x = y, U = V, \ldots\} \quad \text{DiffYYVars}
\end{align*}
\]
**Branching rules** Given an equation where one side starts with a block of $\alpha$, while the other side starts with a unit variable $e$, UnitConst infers that either the length of the $\alpha$ block is greater than one, or equal to one. Observe that some constraints in this rule are emphasized with a wavy underline. If such constraints are implied by $C$, we can directly jump to their corresponding branch. Practically, it helps to not branch, if one of the underlined constraints can be derived in the premise.
\[
\begin{align*}
\{eU=(\alpha,l)V, \ldots\} &\quad e \in \vars \quad \text{UnitConst} \\
C_{\text{len}} &\leftarrow C_{\text{len}}, l \leq 1 \quad \| \quad C_{\text{len}} &\leftarrow C_{\text{len}}, l \geq 1 \\
C_{\text{len}} &\leftarrow C_{\text{len}}, \epsilon_y = 1 \quad \| \quad C_{\text{len}} &\leftarrow C_{\text{len}}, \epsilon_y = 0 \\
y = e, eU = V, \ldots &\quad y = ez, U = zV, \ldots \\
\end{align*}
\]
Given an equation where one side starts with a unit variable $e$ while the other side starts with sequence variable $y$. UnitVar infers that either $y$ is empty, or $e$ is a prefix of $y$.
\[
\begin{align*}
\{eU=yV, \ldots\} &\quad e \in \vars \quad y, z \in X \quad z \notin \vars \\
C_{\text{len}} &\leftarrow C_{\text{len}}, \epsilon_y = 1 \quad \| \quad C_{\text{len}} &\leftarrow C_{\text{len}}, \epsilon_y = 0 \\
y = e, eU = V, \ldots &\quad y = ez, U = zV, \ldots \\
\end{align*}
\]
If both sides of an equation start with blocks of the same constant $\alpha$, SimConsts infers that either both blocks have the same length or one of them has length more than the other. So this rule should have three branches, one equating $l$ and $m$, while the other two deducing a strict inequality between them. However, there are two branches, one equating $l$ and $m$, while the other deducing $m \neq l$. This is because, for the sake of conciseness we introduce "hatted" variables $\hat{U}, \hat{V}, \hat{l}, \hat{m}$ and $\hat{\beta}$. A branch with hatted variables signifies the presence of another branch where the hatted variables are replaced by their substitutions defined as:
\[
\{x; y, \hat{y}; x, \hat{X}; Y, \hat{Y}; X, \hat{U}; V, \hat{V}; U, \hat{l}, \hat{m}; l, \hat{\alpha}; \hat{\beta}; \hat{\alpha}\}
\]
Notice that we also have underlined constraints in the conclusion. So, the rule SimConsts represents six rules, three after expanding hatted variables where none of the underlines constraints is implied by \( C \), and the rest considering presence of each of the underlined constraints in the premise of its corresponding rule.
\[
\{(x, l)U = (x, m)V, \ldots \} \quad \text{SimConsts}
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, m \geq l \quad \| \quad C_{\text{len}} \leftarrow C_{\text{len}}, m > l \quad \{U = V, \ldots \} \quad \{U = (x, m - l)V, \ldots \}
\]
Similar to SimConsts, DiffXVars also uses both hatted variables and underlined constraints which gives rise to a total of ten rules. If both sides of an equation start with syntactically different variables \( x, y \in \mathcal{X} \), and none of the underlined constraints is implied by \( C \), then DiffXVars infers that either one of them is empty or they are semantically equal or one of them is a prefix of the other.
\[
\{xU = yV, \ldots \} \quad x \neq y
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, l_x > l_y \quad \| \quad C_{\text{len}} \leftarrow C_{\text{len}}, l_x = l_y, \quad \{U = V, \ldots \} \quad \{U = (x, l_y)V, \ldots \}
\]
Finally, VarConst fires when one side of an equation starts with a constant block \((\alpha, l)\) while the other side starts with a variable \( x \). Again, VarConst represents eight rules due to the presence of underlined constraints in its branching conclusions. Assuming none of these constraints is implied by \( C \), the first branch sets \( x \) empty; second branch sets length of \( x \) less than \( l \); third branch equated \( x \) to \((\alpha, l)\), while the last branch sets \( x \) as a block of \( \alpha \) whose length is greater than \( l \), possibly followed by another variable \( y \) that does not start with \( \alpha \).
\[
\{xU = (\alpha, l)V, \ldots \} \quad x, y \in \mathcal{X} \quad y \notin \text{vars}
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, \epsilon_x = 1 \quad \| \quad C_{\text{len}} \leftarrow C_{\text{len}}, 0 < l_x < l \quad \{x = (\alpha, l), U = (\alpha, l - l_x)V, \ldots \}
\]
\[
\{x = \epsilon, U = (\alpha, l)V, \ldots \} \quad \{x = (\alpha, l), U = (\alpha, l - l_x)V, \ldots \}
\]
\[
C_{\text{len}} \leftarrow C_{\text{len}}, 0 < l_x = l \quad \| \quad C_{\text{len}} \leftarrow C_{\text{len}}, 0 < l < l_x \quad \{x = (\alpha, l), U = V, \ldots \} \quad \{x = (\alpha, l), xU = (\alpha, l)V, \ldots \}
\]
\[
D. \text{SeqSolve definition}
\]
We define SeqSolve in Algorithm 2. It takes a set of sequence equations \( W \) and an optional set of length constraints \( C_{\text{init}} \) as input and either returns a sat with a solution, unknown or unsat.
\[
\text{Algorithm SeqSolve takes a set of (extended) sequence equations } W \text{ and optionally a set of linear constraints } C_{\text{init}} \text{ as input and either returns a sat with a solution, unknown or unsat.}
\]
\[
1: T \leftarrow \text{genRoot}(W, C_{\text{init}})
2: \text{while } \exists \text{ a non-terminal leaf node } n \in T \text{ do}
3: \quad \text{apply an enabled TranSeq rule to } n
4: \quad \text{if sat terminal node } \langle \sigma, C \rangle \text{ generated then}
5: \quad \quad \text{generate a satisfying assignment } \psi \text{ from } \sigma, C
6: \quad \quad \text{return sat, } \psi
7: \quad \text{if } \exists \text{ leaf node } \langle \text{unknown} \rangle \in T \text{ then}
8: \quad \quad \text{return unknown}
9: \quad \text{else}
10: \quad \quad \text{return unsat}
\]
**Definition 1.** A string equation solver is an algorithm that takes as input a set of string equations and a set of linear constraints. Its output is either “Unsat,” “Unknown,” or “Sat” and an assignment.
**Definition 2.** A string equation solver is sound if it never lies, by which we mean: (1) when it returns “Sat,” the conjunction of the string equations and the linear constraints is satisfiable and the assignment returned is a satisfying assignment and (2) when it returns “Unsat,” the conjunction of the string equations and the linear constraints is unsatisfiable.
**Definition 3.** A string equation solver is partially correct if it is sound and terminating.
**Definition 4.** A string equation solver is fully correct if it is sound, terminating and never returns “Unknown.”
Note that a sound solver can be turned into a partially correct solver by adding a timeout, which results in the solver returning “Unknown.” We prove that our solver is fully correct for the theory of string equations by showing that when the input consists of only a conjunction of string equations \( Q \), our transition system generates a derivation tree that is unsatisfiable if the input is unsatisfiable; otherwise it generates a derivation tree containing a sat terminal node, from which we can extract a satisfying assignment for the input. When the input also includes linear constraints, our solver is partially correct as it may also generate an unknown-closed derivation tree. We show that SeqSolve is sound using the following theorems.
**Theorem 5.** Given inputs \( Q, C_{\text{init}} \) such that SeqSolve generates a tree \( T \) with a sat terminal node \langle \sigma, C \rangle, then \( \sigma, C \) can be used to generate a solution for \( Q, C_{\text{init}} \).
A configuration is var-compliant iff it is of the form \( \langle Q, \sigma, \text{vars}, \ldots \rangle \) where \( \text{Vars}(\sigma) \subseteq \text{vars} \) (by \( \text{Vars}(\sigma) \) we mean \( \text{Vars(dom}(\sigma)) \cup \text{Vars(cod}(\sigma)) \)). A configuration is numvar-compliant iff (1) it is of the form \( \langle Q, \sigma, \text{vars}, C \rangle \) and all numeric variables appearing in it are also in \( C \) and (2) for a variable \( x \in \text{vars} \), initLen(\( x \)) \( \cup \) initConsts(\( x, \text{consts} \)) \( \cup \) initWordCount(\( x, \text{consts} \)) \( \subseteq C \). A configuration is good if it is either terminal or it is disjoint, var-compliant and numvar-compliant. A derivation tree is good if all of its nodes are
Theorem 9. SeqSolve as described in [23] and on fair derivation trees. SeqSolve is subject to the following fairness conditions: (1) LIAUnsat, FuelUnsat and Unknown are weakly-fair rules. First note that once any of these rules is enabled, it stays enabled. We require that no branch of a derivation tree contains a suffix in which a weakly-fair rule is infinitely enabled, yet never applied. (2) Rewrite can only be applied a finite number of times along any branch.
A fair derivation tree is one which respects the above fairness conditions. SeqSolve generates fair and good derivation trees. We use good derivation trees to show that TranSeq is sound.
Theorem 6. Every TranSeq rule is sound when applied to a good configuration.
The termination of SeqSolve (and TranSeq) depends on a bound on the minimum lengths of solutions of string equations as described in [23] and on fair derivation trees.
Theorem 7. SeqSolve is terminating.
Theorem 8. SeqSolve is a partially correct string equation solver.
Theorem 10. SeqSolve is a fully correct string equation solver when the input does not include any linear constraints.
VI. IMPLEMENTATION OF SEQSOLVE
Our implementation of SeqSolve along with all the benchmarks used is publicly available [24]. SeqSolve is implemented in ACL2s [25] which allows us to (1) define datatypes like blocks, sequences and valid Z3 expressions (used to query Z3) (2) define TranSeq rules, which requires proving termination and input/output contracts (input/output types) (3) prove basic theorems relating datatypes (subtypes,etc) and properties needed for above proofs and (4) make essential use of the Z3 interface ACL2s provides to solve ILP constraints. SeqSolve provides various settings that can be used to control how aggressively it generates linear constraints; however, all of the results reported in this paper are with the default settings. We implemented SeqSolve as a standalone decision procedure as opposed to making it a part of an MPMT solver. This makes it easier to compare our tool with other string solvers in an apples-to-apples way, avoiding the complications that would arise from the use of different underlying solvers and frameworks.
We apply a few TranSeq rules until we reach a fixpoint before generating the derivation tree in order to simplify the input problem. These preprocessing steps include Decompose, VarElim, VarSubst and Compress. After reaching a fixpoint, we use LIAUnsat to check if the set of initial constraints and the linear constraints we generated above are unsat.
In our implementation of the rule EqWords, we only use words with the property that no non-empty prefix of w is a suffix of w. Since our solver makes many low-level calls to Z3, it does this in an incremental way. In addition, care is taken to avoid unnecessary calls to Z3, e.g., LIAUnsat is not checked after running Trim, EqElim, Decompose, Compress, VarSubst, Rewrite and VarElim, because in all of these rules, we do not update C. We do not apply any branching rules, unless we have no other options. Our implementation supports string operations like charAt, contains, indexOf, substr, prefixOf and suffixOf. Each of these operations can be converted to a problem in the theory of extended sequences e.g., given charAt constraint \( e = (\text{str.at } s n) \), we convert it into the conjunction of the string equation \( s = xey \) and \( \text{len}(x) = n \), where \( e \in \mathcal{Y} \) and \( x, y \in \mathcal{X} \). Given the constraint \( \text{str.contains } s t \), we convert it into the string equation \( s = xty \) where \( x, y \in \mathcal{X} \).
VII. EVALUATION
We compared our solver against Z3Str2 and Z3Str3 (Z3 version 4.8.8), Norn 1.0, Z3-Trau, Sloth 1.0 and CVC4 1.7. These are the only string solvers we know of that solve string equations with length constraints and ran without crashing. In [26], the tools CVC4, Z3Str2 and S3 are evaluated in which S3 is found to be 5 times slower than Z3Str2 and crashed on about 4.5% of problems in the Kaluza [27] benchmarks. We ran all of the selected tools on Kaluza and Stringfuzz-generated [28] benchmarks, as well as on benchmarks consisting of problem instances pertinent to type inference in Remora [9], [10], a dependently typed array processing language. The type of an array term in Remora encodes the shape of the array as a list of dimensions (natural numbers). Our work was motivated by the problem of inferencing these shapes which reduces to solving string equations. For example, suppose that \( X \) has dimensions \([a \ 3]\) and \( Y \) has dimensions \( b[3]\), where \( a \) is a single dimension, while \( b \) and \( z \) are lists of dimensions, and juxtaposition indicates concatenation. If \( X \) and \( Y \) are used in a context where they must have the same dimensions, then for the program to be well-typed, we require that the string equation \( a3b = b3z \) is satisfiable. One solution is \( b = [\ ] \), \( z = [3] \) and \( a = 3 \), in which case \( X \) and \( Y \) are 2-dimensional matrices with shape \([3 \ 3]\).
We used all of the problems in the above mentioned benchmarks that were in the extended sequence theory, thus, excluding problems in Kaluza that used other constructs. This allows us to evaluate only our contribution, the string solver, not the underlying solvers. In total, we have 1,178 problems, of which 903 are sat problems and 275 are unsat problems. We cross-verified the tools and for all benchmark problems, all tools that gave definitive answers agreed on the classification of the problem. All experiments were performed on the same machine, which was running macOS Catalina 10.14.6 with a 2.7GHz Intel Core i5 CPU and 8 GB of memory. The timeout
for each problem was set to 60 seconds. Figure 1 shows the results of the performance evaluation, using what we call a ray plot. Ray plots are designed to visually depict the results of the evaluation in as simple a way as possible. On the x-axis we have the expected number of problems solved and on the y-axis we have the expected time in seconds. Suppose you want to determine how long it will take to solve n benchmark problems, say 800; just look at the line \( x = 800 \) and you will see that SeqSolve will take about 100 seconds, CVC4 will take over 2,000 seconds, Z3Str3 will take just under 12,000 seconds, Norn will take about 5,500 seconds and Z3Str2 can only solve about 500 problems, so it will never solve 800 problems. Symmetrically, if you want to determine how many problems you can expect to solve in \( t \) seconds, just look at the line \( y = t \). This is a simpler plot than a cactus plot, which shows similar information, but with problems ordered, on a per-tool basis, from easiest to hardest. These orderings can vary significantly from tool to tool and there is no way for a user of the tool to determine how easy or difficult a problem will be, so it is not clear what benefit there is to this extra complexity. It is easy to generate ray plots; just run all the benchmark problems and draw a ray from the origin to the \((p,t)\) coordinate, where \( p \) is the number of problems solved and \( t \) is the time taken. This is equivalent to shuffling the problems many times and taking the average of the running times for the shufflings.
In Table I we show a table version of the experimental evaluation. Tuples under “Solved” give the number of problems solved for the Stringfuzz-generated, Kaluza and handcrafted benchmarks, respectively. In addition to the time in seconds, we also show the number of problems for which solvers returned unknown, timed out or returned incorrect result (X). We ran the tools without giving them a timeout and our scripts killed jobs that were taking too long, but some tools returned unknown before timeouts occurred. Notice that SeqSolve beats all the other string solvers in terms of the standard ordering, which is based on first the number incorrect results, then on the number of problems solved and finally on the time taken.
Acknowledgements: We thank Andrew Walter for integrating Z3 with ACL2s, which was indispensable.
VIII. CONCLUSION AND FUTURE WORK
We introduced a new non-deterministic, branching transition system, TranSeq, for deciding the satisfiability of conjunctions of string equations and length constraints. TranSeq extends the MPMT framework for combining decision procedures and we prove that it is both sound and complete. We implemented a prototype, SeqSolve, which is based on TranSeq and resolves non-deterministic choices in a way designed to infer as much as possible with as few computational resources as possible. We evaluated SeqSolve by comparing it with existing tools on a suite of benchmark problems and found that SeqSolve solved more problems and was faster than existing solvers. In our ongoing work, we plan to extend the scope of TranSeq so that it supports richer classes of constraints. We also plan to reason about the implementation, as it is mostly written in ACL2s, which is built on top of the ACL2 theorem prover.
REFERENCES
|
{"Source-Url": "https://www.ccs.neu.edu/home/pete/pub/fmcad-2021.pdf", "len_cl100k_base": 15004, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 43253, "total-output-tokens": 18774, "length": "2e13", "weborganizer": {"__label__adult": 0.0003840923309326172, "__label__art_design": 0.0007700920104980469, "__label__crime_law": 0.0004875659942626953, "__label__education_jobs": 0.0029430389404296875, "__label__entertainment": 0.00016641616821289062, "__label__fashion_beauty": 0.0002269744873046875, "__label__finance_business": 0.0006008148193359375, "__label__food_dining": 0.0004520416259765625, "__label__games": 0.00101470947265625, "__label__hardware": 0.0010280609130859375, "__label__health": 0.0007185935974121094, "__label__history": 0.0005846023559570312, "__label__home_hobbies": 0.0002005100250244141, "__label__industrial": 0.0007786750793457031, "__label__literature": 0.0006108283996582031, "__label__politics": 0.0004875659942626953, "__label__religion": 0.0006704330444335938, "__label__science_tech": 0.25244140625, "__label__social_life": 0.00017368793487548828, "__label__software": 0.01227569580078125, "__label__software_dev": 0.7216796875, "__label__sports_fitness": 0.0003826618194580078, "__label__transportation": 0.00075531005859375, "__label__travel": 0.0002570152282714844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 60870, 0.00868]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 60870, 0.60705]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 60870, 0.82406]], "google_gemma-3-12b-it_contains_pii": [[0, 5086, false], [5086, 10774, null], [10774, 18328, null], [18328, 25942, null], [25942, 31797, null], [31797, 38169, null], [38169, 44284, null], [44284, 50026, null], [50026, 54404, null], [54404, 60870, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5086, true], [5086, 10774, null], [10774, 18328, null], [18328, 25942, null], [25942, 31797, null], [31797, 38169, null], [38169, 44284, null], [44284, 50026, null], [50026, 54404, null], [54404, 60870, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 60870, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 60870, null]], "pdf_page_numbers": [[0, 5086, 1], [5086, 10774, 2], [10774, 18328, 3], [18328, 25942, 4], [25942, 31797, 5], [31797, 38169, 6], [38169, 44284, 7], [44284, 50026, 8], [50026, 54404, 9], [54404, 60870, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 60870, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
b8b9807a5c1f3011da222d980a1265bc6381c440
|
A hierarchic architecture model for dynamic reconfiguration
Conference or Workshop Item
How to cite:
Link(s) to article on publisher’s website:
http://dx.doi.org/doi:10.1109/PDSE.1997.596843
A Hierarchic Architecture Model for Dynamic Reconfiguration
Michel Wermelinger
Departamento de Informática, Universidade Nova de Lisboa
2825 Monte da Caparica, Portugal
E-mail: mw@di.fct.unl.pt
Abstract
Dynamic reconfiguration is the ability to modify a parallel or distributed system while it is running. We adopt the framework developed by Jeff Kramer and colleagues at the system architecture level: changes must occur in a consistent state, which is brought about by “freezing” some system components. The goal is to reduce system disruption, i.e., to minimize
1. the part of the system to be “frozen” and
2. the time taken by reconfiguration operations.
Towards the first goal we take a connection based approach instead of a component based one. To reduce time, we refine the reconfiguration algorithm by executing changes in parallel as much as possible. Our model also handles hierarchic systems.
1. Introduction
Most systems must undergo several modifications during their lifetime in order to cope with new human needs, new technology or a new environment. Large distributed systems can be described as a configuration of separate, interconnected components. Modifications can therefore occur both at the component level (change implementation, add new functions, etc.) and at the architecture level (add or remove components or connections). We deal only with the latter, in particular we address the following questions:
1. What kind of modifications can be done?
2. How are they performed?
The answer to the first one is given by a configuration model that defines the system architecture and the change process. The second question is about how the changes will be executed by the underlying operating system.
For economical or safety reasons, some systems cannot be stopped or taken off-line to perform those changes. Thus changes are done while the system is running. This is called dynamic reconfiguration and applies only to distributed or parallel systems because centralized “single-thread” systems must be completely stopped to be altered. Normally changes may not be executed at once. For example, to remove a component first it must cease all interactions with its neighbour components. Thus a further question must be addressed:
3. When may the changes be performed?
The answer is: when the components to be changed are in a consistent state. The definition of “consistency” will be given by the model and it is brought about by “freezing” a part of the system which may include components or connections that will not be modified.
To handle the previous questions we adopt a framework developed by Kramer and colleagues [5, 6]. It is simple and general, both in terms of the changes it allows and in terms of the assumptions it makes on systems. Upon closer analysis of the two algorithms proposed for finding the set of system components to “freeze” [6, 2], we have found that neither is minimal regarding the disruption it causes to the system. Switching to a connection based approach we come up with a conceptually very simple yet effective minimal solution.
However, that only accounts for disruption in terms of “size”, i.e., what parts of the system are “frozen”. It does not take into account for how long they are inactive. Since we work with an abstract, implementation-independent reconfiguration model, our solution just provides an execution order for the change commands such that they are performed as much in parallel as the logical dependencies between them allow.
The third contribution of this paper is the treatment of hierarchic systems, whose components can be made of interconnected subcomponents. For practical purposes, the original work [5, 6, 2] only deals with flat systems. The hierarchic reconfiguration management method to be introduced
allows the parallel execution of change commands in different subsystems while taking into account any dependencies among them. Furthermore, the method is as modular as the system it is applied to.
The structure of the paper is as follows. The next section summarizes and analyzes the work done by Jeff Kramer and colleagues, showing its problems regarding disruption minimization and hierarchic systems. Whereas the original framework is described mainly in informal terms [5, 6], this paper will provide formal definitions: section 3 describes the refined architecture model and section 4 deals with disruption minimization. Towards that end, it presents a connection-based approach and an ordering of change commands. Finally, section 5 describes a method to construct a configuration manager for a given hierarchic system. The last section presents some concluding remarks and future work.
2. The original model
We adopt the configuration model developed in [5, 6] and summarized in Figure 1. In the following we describe the assumptions made by the model for each element appearing in the diagram.
A system can be depicted as a directed graph whose nodes are the system components and whose arcs are transactions between components. As the model is component-based, it assumes there is at most one connection between any pair of components. An arc from a node to a node states that the transaction is initiated by , although during the transaction communication flow can occur in both directions. Transactions complete in bounded time and the initiator is always informed of completion. In particular, the system does not get into any deadlock or livelock situation. These assumptions will help to prove that the consistent state can be reached in finite time and that the configuration manager will know when. A transaction is dependent on the consequent transactions (written ), if its completion depends on the completion of all the other ones. Otherwise, a transaction is called independent.
Changes to a system are specified using four commands, to be executed by the operating system, with obvious meanings: create , remove , link and unlink . Given a specification of the current system configuration and the specification of the configuration changes, the validation process checks whether the changes may be (totally or partially) applied to the system and produces the specification of the resulting system. Checks may range from simple syntactic ones (e.g., remove is incorrect if does not exist in the system) to deep semantic results (e.g., will the resulting system be deadlock-free?). In the following it is assumed that changes are valid and that the specification is declarative, i.e., the change commands are not in any particular order.
Given the valid changes, the configuration manager generates the instructions for the operating system to reconfigure the current system, such that the resulting one will conform to the specification produced by the validation process. In particular, the manager performs the following steps:
1. Compute from the change specification the nodes that must be in a consistent state for reconfiguration to take place.
2. Compute the nodes that must become “frozen” in order to achieve consistency over the set of nodes obtained in the previous step.
3. Send a “freeze” message to each node obtained in step 2 and wait for all the acknowledgments.
4. Instruct the operating system to execute changes in the following order: unlink, remove, create, link.
5. Instruct the created and the “frozen” nodes (except the removed ones) to resume processing.
There are two approaches based on this model that differ only in steps 2 and 3. The first one [6], which we will call the passive approach, “freezes” a node by preventing it from initiating any new transaction; the second one [2] completely stops the node’s execution and therefore will be called the blocking approach.
2.1. The Passive Approach
In this method [6] the “frozen” state is called passive and the “freeze” message is passivate. To facilitate exposition, let us first handle only independent transactions.
A component is passive if it is not engaged in transactions it initiated and if it will not start new ones. However, it must accept and service transactions in order to let other nodes become passive. Therefore, passiveness is reachable in finite time: a component just has to wait for the transactions it initiated to finish (this is guaranteed to happen) and then make sure it will not start new ones. The passive state is just a necessary condition for reconfiguration. In order to guarantee a consistent and stable internal state, in addition to being passive a node should not have any outstanding transaction to service. This is called *quiescence* and depends on those components that can initiate transactions with the node. Therefore, the passive set of a node $Q$. $PS(Q)$, is defined as $Q$ and all nodes with connection arcs towards $Q$. It is easy to see that $Q$ is quiescent if all nodes in $PS(Q)$ are passive.
The quiescent set $QS$ for a given change specification is the set of nodes that must be quiescent during the reconfiguration, namely those that will be removed and the initiators of transactions that will be added or removed. Newly created nodes are automatically quiescent. The set of nodes to "freeze", called change passive set, is simply $CPS = \bigcup_{i \in QS} PS(i)$.
To see why this does not work for dependent transactions, consider a system with clients $C_i$ accessing through agents $A_i$ a server $S$ managed by $M$ (Figure 2). If the server is going to be replaced, then both $S$ and $P$ will be removed. Thus the configuration manager calculates $QS = \{M, S\}$ and $CPS = \{A_1, A_2, M, S\}$. However, if a client has a new request $s_i$, then the respective agent cannot service it because according to the definition of passiveness it may not initiate $r_i$ (on which $s_i$ depends). This would lead to a partially incomplete transaction, i.e., to an inconsistent state of the whole system during reconfiguration. On the other hand, allowing $A_i$ to start transaction $r_i$ would lead to new transactions on the manager and on the server, which therefore would not be in the quiescent state.
To solve this problem, the notion of passive state must be changed. Otherwise reachability of the quiescent state in bounded time would be lost. If $A_1$ is to be replaced, then $QS = CPS = \{C_1, A_1\}$. If $A_1$ becomes passive before $C_1$, and $C_1$ just initiates a new transaction $s_1$ before getting the passivate command from the configuration manager, then the client will never become passive because $r_1$ is not initiated. In this case one could order the commands (passivate $C_1$ before passivate $A_1$), but for systems with mutual dependencies like the one in Figure 3 no such ordering is possible.
The notion of passive set must also change, since the nodes that may initiate transactions with a given node are not just its immediate neighbours. The new definitions are thus as follows.
- In the generalized passive state a node is not engaged in non-consequent transactions it initiated and it will not initiate new ones. Furthermore the node accepts and services all requests, initiating consequent transactions if necessary.
- The enlarged passive set of a node $Q$, $EPS(Q)$, includes $Q$ and all nodes that can initiate transactions which result in consequent transactions on $Q$.
Notice that both definitions reduce to the old ones in case all transactions are independent. The reconfiguration algorithm remains the same, except that $PS(i)$ is substituted by $EPS(i)$ in the calculation of $CPS$.
The server replacement in Figure 2 is now correctly handled. Since $EPS(S) = \{C_1, A_1, C_2, A_2, M, S\}$, all nodes have to be passivated. Even if all components but $C_1$ are already passive, any pending $s_1$ transaction will be serviced (through $A_1$ and $M$) by the server and therefore the client can become passive and reconfiguration may start.
In general, systems are not flat as assumed until now but hierarchic, i.e., some nodes (called composite) are made of connected subnodes. A composite node is connected to other nodes through some of its subcomponents. The transaction dependency of a composite component must be derived from its subcomponents. The following substitution rule is given in [6]:
"when composing 2 nodes, substitute the consequents for each occurrence of the dependent transaction which is hidden by the composition."
The rule can be iterated on components and connections (Figure 4). To simplify reconfiguration management, [6] suggests that a composite node is considered to be passive if all its subnodes are, and that all transactions between composite nodes are independent.
**Figure 2.** A client-server system with dependent transactions
**Figure 3.** Mutual dependencies
2.2. The Blocking Approach
An alternative method is presented in [2]. It assumes that a node is consistent and self-contained except during transactions, as those are the only interactions with the outside environment. Thus, to make a node quiescent it is enough to block it while it is idle (not engaged in any transaction). A component is also assumed not to interleave transactions: while handling a request a node may not service any new one, even if it comes from a different connection, and it may initiate only consequent transactions. This is used to prove that the blocked state is reachable in finite time.
The basic algorithm is thus to send a block message to the nodes in the quiescent set (called BSet, short for blocking set, in [2]). As soon as such a node is idle, it blocks and sends an acknowledgment to the configuration manager. Since some of the nodes that depend on a node may also have to block, the node must temporarily unblock to service some requests. However, it must be guaranteed that at some point no more such requests will arrive and the node will remain blocked. The basic question is therefore: what transactions should a blocked node service?
It is obvious that it cannot process just any incoming transaction, since it might come from a node that is not affected in any way by the reconfiguration and as such might initiate a new transaction at any time. Thus the blocked node would have to unblock unpredictably and the safe state needed for reconfiguration to begin would never be reached. It is also evident that at least the transactions initiated by other BSet members will have to be serviced in order for them to become blocked. On the other hand, not every request from a non-BSet member can be ignored. Consider the cases depicted in Figure 5. Node B must service the request from C because it is the nth consequent transaction of a transaction initiated by A, which must be completed for A to become blocked. In the second case on the right half of the figure, component F has initiated a transaction with G before getting a request from E. If G does not service the transaction, F will never be able to start attending E’s request since transactions do not interleave.
One could let BSet nodes unblock just in those situations but the authors think this is non-trivial and has great run-time overhead. Instead they propose the BSet to grow dynamically in step with outgoing transactions. When a node gets a request from a BSet member, it becomes a member too, and only requests from BSet members are attended; all other are queued and serviced after the reconfiguration. In the previous cases, it means that the BSet grows to encompass the whole system, and therefore D and G will service the transactions initiated by C and F respectively.
Notice that the BSet has two kinds of members: those that “really” must block due to the reconfiguration and those that block in order to let members of the first kind to get blocked. Therefore a distinction is made between the original BSet and the extended BSet. Their union is the BSet. When all the original BSet nodes become blocked, the components in the extended BSet can be unblocked since their raison d’être has ceased. The disruption thus first grows and then shrinks.
As the calculation of the BSet is dynamic, the reconfiguration algorithm is distributed through the configuration manager and the nodes. Each node runs the same code in a transparent way using hooks that are called upon relevant events like message arrival (from another node or from the configuration manager), transaction begin and transaction end. The application programmer only has to mark in the component’s code the last two hooks have to be activated. The code run by each hook basically updates local variables and sends messages to other nodes or to the configuration manager when necessary. The main variables and messages are those that concern the BSet. The configuration manager computes the original BSet (in the same way as the passive approach, since it is the quiescent set) and the so-called PSet (short for primed set), the set of all nodes that may be recipients of transactions initiated by BSet members. Whenever such a node receives a message from a BSet member, it informs the configuration manager that it must be added to the (extended) BSet. The configuration manager calculates the new PSet and sends the updated value of the BSet to all those nodes.
3. Discussion
The authors of the approaches just described discuss their results, but since [2] contains not a single example, comparison with [6] is stated in brief and vague terms. Since we
use the same framework, we take a closer look at the two different methods in order to gain a better insight into the reconfiguration process to achieve further reduction in disruption. Both approaches will be analyzed in terms of disruption, run-time overhead, implementation, and how they deal with hierarchic systems.
We adopted this model because, as stated in [2], other work in dynamic reconfiguration either only deals with tool and language support to describe and execute the changes [1] assuming that the system is already in a safe state, or it imposes limitations to guarantee maintenance of the system’s state [4, 3, 9]. Limitations can be on the kind of system (e.g., only client-server) or on the kind of changes handled (e.g., a component may only be replaced by a specialization of it). Sometimes they are due to the existence of special mechanisms to capture and recover the application state prior to the change. The described framework is more general: it allows any kind of changes, it provides a means to achieve the stable state, and it does not require special mechanisms.
3.1. Implementation
In the first approach the application programmer is expected to provide code that will allow the component to reach the passive state and keep it, whereas in the second approach this happens transparently due to the added assumption that nodes are consistent when there are no interactions with the rest of the system. Of course, the other side of the coin is that the implementation is hidden away into the hooks which must trap low level events like message arrival. This means that the implementor of this approach must have access to the operating system source or else program a new layer that will be used by the applications.
On the other hand, the first approach requires just one passive message for each node in the extended passive set, while the second method generates initially \(|PSet_0|\) messages and then \(1 + |PSet|\) messages for the addition of the \(i\)th member of the extended BSet. Also, the messages in the static method are just tokens, while those in the dynamic approach are descriptions of (potentially large) sets. The blocking approach has thus much greater run-time overhead and is more complex to implement, but imposes less burden on the component programmer.
3.2. Disruption
The important point in any dynamic reconfiguration method is that the “freezing” of a node \(N\) does not prevent other nodes from reaching their “frozen” state. Basically, both approaches solve the problem by “freezing” also every node that depends on \(N\) or on which \(N\) depends. This does not minimize disruption and in fact may involve many components besides those that will be affected by reconfiguration.
To illustrate the differences between both approaches, let us apply them to common examples. We will write \(OBS\) and \(EBS\) for the original and the extended BSet, respectively. The first example is the system of Figure 2. If the server is to be replaced, we have seen that the first approach passivates all nodes. The second method considers \(OBS = \{M, S\}, EBS = \{\}\) and \(PSet = \{S\}\), because the only outgoing transaction from a BSet member is \(p\) and goes to the server. This means that on occurrence of \(p\), \(EBS = \{S\}\) and on its completion both \(M\) and \(S\) block because they are idle and in the BSet. Notice that the clients are not blocked and therefore may initiate new transactions during reconfiguration. Since \(M\) is blocked, it will queue the requests and service them after the changes done to the system. This was considered an inconsistency in the passive approach, but in our opinion this is perfectly acceptable because the server manager has not been changed. Therefore its interface with the agents and the new server is the same as previously. This means that the new server is able to attend requests sent to the old one. To sum up, the blocking approach causes less disruption. The reason is that a passive node (and in particular a quiescent one) is active regarding transactions it services. Therefore, to achieve inactivation the node must be “shielded” from outside requests and that shield (the extended passive set) must remain during reconfiguration. No such shield is required in the second approach since the components actually stop.
Now consider the same system but where the first client has to be replaced. In this case \(QS = EPS = \{C_1\}\) since no component depends on \(C_1\). Therefore, as soon as the transaction terminates, \(C_1\) will become passive and automatically quiescent. Reconfiguration can start, while all other components remain active. Applying the blocking approach one has \(OBS = \{C_1\}, PSet_0 = \{A_1\}, EBS_0 = \{\}\). If there is a pending client request, \(EBS_1 = \{A_1\}\) and \(PSet_1 = \{M\}\). Since the transaction is dependent, after two more steps \(EBS_2 = \{A_1, M, S\}\). In other words, to replace a client, the server is blocked (even if temporarily)! This would remain so even if all transactions being executed were independent. In this example the first approach causes much less disruption, contrary to the claim in [2] that the blocking approach performs always at least as well as the passive method. The reason is that the blocking approach is purely dynamic: it does not precompute the dependencies between nodes, which is essential to determine whether the blocking of two components will interfere with each other. Therefore at run-time the method goes through all the nodes an \(OBS\) member depends on, which form the \(EBS\). If the configuration manager would compute the paths between \(OBS\) members, disruption could be greatly reduced in most cases.
The last example is the left half of the system in Figure 5. In the second approach, if $A$ is not engaged in any transaction with $B$, it will block immediately. Thus as soon as $D$ is idle it will get blocked too and reconfiguration starts. In the first approach, all nodes from $B$ to $C$ will be passivated even if no dependent transaction will occur. This is the advantage of a dynamic method. It only takes into account transactions that are actually occurring in the running system, while a static analysis must involve all transactions that may occur.
The authors have concentrated on the number of nodes that are passivated or blocked by their methods, but we think that indirect disruption must also be taken into account. Since a blocked node does not do any processing whatever, any transaction it services or initiates unrelated to the reconfiguration will also be stopped and that may lead to (partial) inactivation of other components. Since passive nodes still service requests they cause indirect disruption in smaller scale. But internal processing that requires initiation of transactions is still hindered. This is recognized in [6]. The authors observe that the replacement of the server in Figure 2 passivates the clients thus stopping them from interacting with other nodes not shown on the figure. Therefore, they should only be passive with respect to the server being replaced, not other nodes unrelated to the change. This could be achieved by distinguishing the relevant connections and modeling their state (connected-passive, connected-active, disconnected). This would allow more granularity, but the authors think it would lead to more complex substates and more complex actions to obtain consistency since the nodes would be partially active. Therefore they think their approach, while not minimal, is simple and sufficient.
In our opinion there is another factor that contributes to a greater disruption than necessary in some cases: the requirement for quiescence of the initiator node in (un)link changes.
Let us assume that the change specification contains a command $\text{unlink } N$ from $N'$ for a nonconsequent transaction. It is not necessary for $N$ to be quiescent. It is enough to be passive, thus not starting any new transaction with $N'$. Consider the right subsystem of Figure 5 where connection 1 will be removed. If $F \in QS$ then $E$ and every node that depends on transaction 2 would be in $EPS$. Therefore they and all nodes on which they can initiate transactions would be partially inactive. If $F$ were only passivated, the extended passive set would not include the other nodes, reducing direct and indirect disruption greatly.
Also, if there is a $\text{link } N \rightarrow N'$ command but neither $N$ nor $N'$ are changed, then the new connection is the replacement of a previously existing connection or it is an optional connection (because $N$ was already working without it). In any case $N$ does not have to be quiescent or even passive. It is only in those states if it has to be replaced or if some of its connections will be removed. In our opinion, the addition of connections by itself should not impose passiveness.
Both approaches measure disruption only in terms of nodes, neglecting the time factor. In the configuration model described in section 2 first components are “frozen”, then change commands are applied, and finally components are activated. This does not minimize disruption time because each phase can only begin after the previous one ended. Moreover, commands are performed in a fixed sequence (first all $\text{unlink}$, then all $\text{remove}$, etc.). It is obvious that in many cases some changes are independent of others. In those cases a part of the system might be changed without having to wait for nodes in other parts to be “frozen”, or commands of different kinds might be performed in parallel.
### 3.3. Hierarchic systems
In [2] no reference is made to hierarchic systems. In fact, the blocking approach does not work for them since a composite node will in the general case interleave transactions, because its subcomponents run in parallel. As written before, [6] deals with such systems but their treatment is still very sketchy. Basically, it only indicates how to compute a composite node’s dependencies from its subcomponents. From there the extended passive set at the higher level can be computed. If the composite node has to be passivated, all its subcomponents should. This certainly does not minimize disruption. We also feel that requiring independent transactions between composite components (as in CONIC [8]) to reduce the number of those to be passivated may lead to extremely large components or to many small ones. In any case it may force the system designer to partition the system into artificial composite components that are uneasy to work with. But more importantly, [6] does not deal with the interaction between changes at different levels or how changes at a lower level will affect higher levels of the component hierarchy.
### 4. The refined model
Although the original analysis of the requirements for dynamic configuration [5] stressed the importance of modularity and well-defined component interfaces, the model presented in [6] does not support it. However, the concrete configuration language presented in [5], CONIC, and its successor DARWIN [7] provide a mechanism to specify the communication points of a component, called ports. Our model will thus support that notion, too. An interface is just a set of ports, each being used either to initiate transactions or to receive requests. Since the environment has no access to the inner structure of a component, the programmer must provide in the interface the dependencies between initiator ports and recipient ports.
Definition 1 A node interface is a triple \( \langle I, R, D \rangle \) where
- \( I \) is the finite set of initiator ports;
- \( R \) is the finite set of recipient ports such that \( I \cap R = \emptyset \);
- \( D \subseteq R \times I \) is the port dependency relation.
A system is simply a set of connected nodes, where a connection is given by an initiator port and a recipient port. To capture sound software engineering principles (modularity, encapsulation, data hiding, etc.), a system has no access to the inner structure of its nodes; it knows only their interfaces.
The original model is intended for node based reconfiguration, i.e., “freezing” is done upon nodes. Moreover, the computation of the passive and blocked sets depends only on the pattern of connections, not on their number. Therefore the model can assume without loss of generality that there is only one arc between a given pair of components. A connection based approach like ours distinguishes individual transactions and thus one must allow several connections to be linked to the same port (but only one transaction for any given pair of ports). This covers typical situations like client-server (all client transactions linked to the same server recipient port) and broadcast (many transactions linked to the same server recipient port) and broadcast (many transactions linked to the same server recipient port) and broadcast (many transactions linked to the same server recipient port) and broadcast (many transactions linked to the same server recipient port) and broadcast (many transactions linked to the same server recipient port and every transaction received by the system is passed on to its recipient port). To avoid deadlock, the connections (together with the port dependencies) may form no cycle. Formally, there may be no closed sequence of alternating recipient and initiator ports such that every initiator port depends on the preceding recipient port which in turn is linked to the next initiator port.
Definition 2 A system is a pair \( \langle N, T \rangle \) where
- \( N \) is a non-empty finite set of node interfaces;
- \( T \subseteq \bigcup_{n \in N} I_n \times \bigcup_{n \in N} R_n \) is the set of transactions.
A non-empty path is a sequence of ports \( r_1 i_1 r_2 i_2 \cdots r_m i_m \) with \( m > 0 \) such that
- \( \forall j \in \{1, \ldots, m-1\} \langle i_j, r_{j+1} \rangle \in T \);
- \( \forall j \in \{1, \ldots, m\} \exists n \in N \langle r_j, i_j \rangle \in D_n \).
For every non-empty path \( r_1 \cdots i_m \) one has \( \langle i_m, r_1 \rangle \notin T \).
The original model assumes that the dependencies among transactions are given with the system. We feel that our notion of port dependency is more realistic and more flexible since it allows the system architect to work with components he has not programmed himself. Besides, it is a more primitive notion because the dependencies among connections can be computed from those between ports: if recipient port \( r \) depends on initiator port \( i \), then any transaction received by \( r \) starts a transaction (i.e., depends) on every connection from \( i \). As in the original model, the inverse is not true: the component might start a transaction on port \( i \) without having received any request on port \( r \). The transaction dependency relation is closed under transitivity.
Definition 3 Given a system \( \langle N, T \rangle \), the transaction dependency relation \( \subseteq T \times T \) is defined as \( \langle i, r \rangle / \langle i', r' \rangle \iff (\exists n \in N \langle r, i \rangle / \langle i', r' \rangle) \vee (\exists n \in N \langle r, i \rangle / \langle i', r' \rangle) \).
A transaction \( t \) is dependent (on the consequent transaction \( t' \)) if \( \forall t' \in T t/t' \), otherwise \( t \) is independent.
The acyclic condition on port paths can thus be restated as: transaction dependency is anti-reflexive.
Proposition 4 In a system \( \langle N, T \rangle \), \( \exists t \in T t/t. \)
To build modular architectures it must be possible to abstract systems into nodes which will be part of other systems. A system will be encapsulated in a composite node by hiding part of the system’s ports. The dependencies of the remaining visible ones (i.e., the ports of the composite node) are given by the underlying system.
Definition 5 A composite node consists of an interface \( \langle I, R, D \rangle \) and a system \( \langle N, T \rangle \) such that
- \( I \subseteq \bigcup_{n \in N} I_n \);
- \( R \subseteq \bigcup_{n \in N} R_n \);
- \( D = \{ (r, i) \in R \times I \mid r_i \cdots r_m, i \) is a non-empty path in \( \langle N, T \rangle \} \).
If a node is not decomposed into further nodes, then it is called simple. Formally, only its interface is available. A system is hierarchical if it contains at least one composite node. Strictly speaking, given a system it is impossible to know for any of its nodes whether it is simple or composite because the formal definition of a system only provides the node interfaces. Thus it is possible for a simple node to be changed into a composite one and vice-versa in a transparent manner to the system.
5. Minimizing disruption
From the long summary and analysis of the passive and blocking approaches it becomes clear that to minimize disruption we must look for a static blocking method at the connection level. To ensure that blocking a connection will not prevent others from reaching the blocked state, we can use a previously mentioned idea: to order the execution of
“freeze” commands. This works at the connection level because transactions do not form cycles. Extending the execution ordering to all commands one can define precisely what changes may be performed in parallel to reduce disruption time.
5.1. The connection approach
The essence of our proposal is to block only those connections that will be removed. To block a connection its initiator node waits for any ongoing transaction (on that connection) to finish and then simply does not start a new one. For this to work we assume, as in the original model, that a transaction finishes in finite time and that its initiator knows when it ends. A simple implementation might be the following. For each component, assign to each transaction \( T_i \) it might initiate a boolean variable \( \text{blocked}[i] \) initialized to false and a semaphore \( S[i] \). Then substitute the transaction code \( T_i \) by
\[
\begin{align*}
\text{P}(S[i]); \\
\text{wait while blocked}[i]; T_i; \\
\text{V}(S[i]);
\end{align*}
\]
and add the following case to the code that dispatches the incoming requests:
\[
\text{if msg.command = block then begin} \\
i := msg.arg; \text{P}(S[i]); \\
\text{blocked}[i] := \text{true}; \text{V}(S[i]); \\
\text{send(config_manager, blocked, i)} \\
\text{end}
\]
This code can also be provided by three hooks if wished. One to be called on transaction begin, one on transaction end. These hooks must be explicitly called by the component’s programmer, passing the transaction identifier as argument. The third hook would be called transparently to the component on message arrival. Compared to the blocking approach, run-time overhead is small since only one simple block message per connection is sent and acknowledged. However, the number of messages is usually larger than in the passive approach because each node to be removed has to receive as many block messages as the connections it has.
Blocking a connection means that the node will not service any transaction that depends on the blocked one. To ensure that the blocking of one connection will not prevent other pending transactions to block, the configuration manager orders the blocking according to dependency: if transaction \( t \) depends on \( t' \) then the block message is sent to the initiator of \( t' \) only after \( t \) is known to be blocking. This is always possible because transactions do not depend cyclically on each other.
Consider again the client-server system of Figure 2. Let us assume that \( C_1 \) and the server will be replaced. Then \( s_1 \) and \( p \) must block because they will be removed, but \( p \) cannot simply block at once because it may have to service a pending \( s_1 \) request (or else \( s_1 \) could never terminate and get blocked). Therefore, blocking \( s_1 \) before \( p \) we are sure that the blocking state is reachable for each link. Also, any request received by manager \( M \) after \( p \) blocked can be safely queued until the server has been replaced because it is known that any connection that depends on \( p \) and that had to block has already done so.
Notice that this method would not work if the server would be allowed to be simply removed without being replaced by a new one. In that case a partially completed \( s_2 \) request could remain after reconfiguration: clearly an inconsistent state. We assume that the validation process has ruled out such cases. If a consequent transaction is removed, either a replacement connection is created or else the transactions which depend on the removed one are changed too.
The original reconfiguration model distinguished two kinds of commands: those that are given in the change specification (create, etc.) and those that are used to “freeze” the components (passivate, block) and to activate them again after reconfiguration end. The former are common to the passive and blocking approaches, while the latter are specific to each approach. In our model the “freeze” command blocks a connection and we will ignore the activation commands since they are not fundamental for the main issues of this paper, namely disruption minimization and hierarchic systems. Furthermore, as multiple transactions are allowed between the same pair of components, the syntax of the (un)link commands has to change slightly.
**Definition 6** A command is either of create \( n \), remove \( n \), link \( t \), unlink \( t \) or block \( t \), where \( n \) is a node interface and \( t \) a transaction.
5.2. The partial order
To minimize disruption time, the precise execution of the commands issued by the configuration manager is given by a temporal order \( \prec \): if \( c \prec c' \) then command \( c' \) can only be executed after command \( c \) has completed. Commands that are not related through the ordering can be executed in parallel. It is obvious that the order must include the following relationships:
1. If a transaction \( t \) depends on a transaction \( t' \), then \( t \) must be blocked before \( t' \).
2. A connection must be blocked before it is removed.
3. A node can only be removed after its connections have been removed.
4. A node can only be linked after its creation.
We will be conservative and impose a further restriction. In some systems it might not be necessary and thus further parallelization can be achieved. Consider a simple system with a client linked through transaction $c$ to a server. If the server is to be replaced then a new connection $c'$ is needed. However, since the client remains the same, the communication protocol with the new server is the same as with the old one. Therefore, $c'$ is the same transaction as $c$ and we feel it does not make sense to link $c'$ before unlinking $c$. Besides, it might lead to execution errors if the implementation of the client assumes that there is always only one connection on that particular port. The general rule is:
5. A transaction initiated by a node can be established only if no more transactions initiated by it will be removed.
As can be seen by exhaustive inspection of all possible interactions between the existing kinds of commands (block, link, unlink, remove, create) no further rules are necessary since there are no other dependencies between the commands and thus they may run in parallel.
**Definition 7** Given a set of commands $C$ for a system $\langle N, T \rangle$, the command order $\subseteq C \times C$ is the smallest relation that satisfies
1. block $i <$ block $t'$ if $i/t'$ and $\exists$ block $t'' \in C$ $t/t'' \land t''/t'$;
2. block $i <$ unlink $t$;
3. unlink $\langle i, r \rangle <$ remove $n$ if $i \in I_n$ or $r \in R_n$;
4. create $n <$ link $\langle i, r \rangle$ if $i \in I_n$ or $r \in R_n$;
5. unlink $\langle i, r \rangle <$ link $\langle i, r \rangle$.
Since the configuration manager will directly implement the command order, it is desirable to avoid redundancy. Therefore the ordering is an immediate precedence relation: if $c < c'$ then there is no command $c''$ such that $c < c'' < c'$. Due to the nature of the five cases this could only happen with block commands (case 1). Therefore the definition above imposes the additional condition.
Let us return to the example of Figure 2. Only 4 steps are necessary to replace the first client and the server whereby each step consists of several commands executing in parallel:
1. create $C'_1$, block $s_1$, create $S'$
2. unlink $s_1$, block $p$
3. link $s'_1$ (the connection from $C'_1$ to $A_1$), remove $C_1$, unlink $p$
4. link $p'$ (the connection from $M$ to $S'$), remove $S$
Notice that in some cases some commands of step $i+1$ can start without step $i$ being completed (the exact order is given by Figure 6 as explained in the next section). Since our rules take into account the specific components or connections on which the commands are to be executed, the disruption suffered by each system part being changed is greatly reduced since change actions are much more interleaved than in the original model.
To summarize, a connection based approach is not only advantageous in terms of the number of parts being "frozen", but also in terms of minimizing disruption time. In fact, in the node based approaches several nodes have to “freeze” just to let those nodes that really matter for the reconfiguration to become quiescent. In practice this means that reconfiguration can only start after all nodes have “frozen”. We think it is possible to have rules that allow one to calculate the exact set of nodes that have to “freeze” for a given change command to be executed, but those rules would be much more complicated than those shown above. Given that in a connection based approach the number of parts to be “frozen” is much smaller, and that “freeze” and change commands can be better interleaved, we conclude that our method can reduce disruption time considerably.
6. The configuration manager
Since a configuration manager executes several commands with some dependencies among them, we observe that such a manager can be seen as a parallel system too, with components and transactions. The goal is to have a precise definition of a configuration manager for a given set of commands to be applied to a given system. In this way the same framework can be used both for managers and the systems they reconfigure. In particular, the definition to be obtained can serve as a basis for a straightforward implementation of configuration managers, although our main goal is to provide a system view of a manager. To facilitate exposition we will start with flat systems.
The basic idea is that each change command is implemented by a component, and connections between components make dependencies between the corresponding commands explicit. To be more precise, if $c < c'$ then the component corresponding to $c'$ will initiate a transaction with the component corresponding to $c$. The transaction can be seen as a request from $c'$ to execute $c$. Once the acknowledgment is received, $c'$ can execute. If $c'$ depends on several commands it must wait for all its requests to be attended. A command is executed only once, even if several other commands are connected to (i.e., depend on) it.
A component implementing a command $c$ must therefore have two ports. The recipient port $s_c$ receives all requests
from the successors of \( c \), i.e., those nodes that can only execute after \( c \). The initiator port \( p_i \) sends requests to all predecessors of \( c \) to start execution and waits for the acknowledgments. It is obvious that \( s_c \) depends on \( p_i \).
In some cases a command \( c \) does not depend on the execution of others. In other words, there is no \( c' \) such that \( c' < c \). The inverse can also happen: no \( c' \) depends on \( c \). For example, if connections are to be removed, there is always at least one block command to be executed first (i.e., it depends on no other one) and at least one block to be executed last. In these cases the corresponding components only need one port. Instead of providing special component definitions we take a generic approach. The configuration manager has always one special \( \text{nop} \) component with one recipient port \( s_{\text{nop}} \) and one initiator port \( p_{\text{nop}} \) (like any regular component) but there is no dependency between them. For any request received by \( s_{\text{nop}} \), an acknowledgment is immediately sent. Likewise, any transaction linked to \( p_{\text{nop}} \) is immediately started. To see why this works, consider the case where there is no \( c' \) such that \( c' < c \). Since \( c \) depends on no other command, it can execute at once. In other words, the fact that \( c \) has no predecessor can be seen as its predecessor being the “empty” command \( \text{nop} \). Therefore, if \( c \)'s predecessor port \( p_i \) is linked to the successor port \( s_{\text{nop}} \), the request from \( c \) is immediately attended by \( \text{nop} \) and therefore \( c \) can execute at once as wished.
**Definition 8** The system configuration manager that reconfigures the flat system \( \langle N, T \rangle \) according to commands \( C \) is a system \( \langle N', T' \rangle \) where
\[
N' = \{ \langle p_c, s_c \rangle, \langle s_c, p_c \rangle \} \mid c \in C \\
\cup \{ \langle p_{\text{nop}}, s_{\text{nop}}, \# \} \}
\]
and \( T' \) is the smallest relation that satisfies
1. \( \langle p_c, s_c \rangle \in T' \) if \( c' < c \);
2. \( \langle p_c, s_{\text{nop}} \rangle \in T' \) if \( \exists c' \ c' < c \);
3. \( \langle p_{\text{nop}}, s_c \rangle \in T' \) if \( \exists c' \ c < c' \).
According to this definition the reconfiguration of the client-server system of Figure 2 can be done by the manager depicted in Figure 6 which allows us to quickly see the ordering of the commands, in particular which must be executed sequentially and which can run in parallel. Notice that the execution path starts and ends at the \( \text{nop} \) node, and that the four steps presented in the previous section correspond to the four levels of the topological sort of the graph.
Hierarchical systems pose a problem that does not occur in flat systems: if commands \( c \) and \( c' \) apply to different subsystems, it might still be the case that \( c < c' \) (or vice-versa) due to the way the subsystems are connected. As an example let us consider Figure 7 where the dotted lines indicate for each port of a composite node which is the corresponding port of the contained system. Assume further that for each of \( B, C, D, \) and \( E \), the recipient port depends on the initiator port. The same applies to \( N_2 \), according to the definitions of composite nodes and transaction dependency, and thus \( b/d \) as seen on the right. Moreover, for the given configuration one has \( a/c \), which is not apparent just by looking at \( N_1 \). If \( A \) and \( F \) are to be replaced, those two connections cannot be blocked in parallel. One could flatten the whole system to discover that \( \text{block} \ a < \text{block} \ c \), but that defeats the whole purpose of building a modular system.
Therefore, to reflect the hierarchy of a system and the benefits of its partitioning, we propose a configuration manager for each node. We have seen that a manager for a system is a system itself. Likewise, the manager of a node will be a node, with an interface that will allow it to be linked to other configuration managers. The problem is thus what interface a node manager needs and how should it be linked to other managers. The goal is to achieve the correct order
---
**Figure 6.** A specific configuration manager
of command execution in the most modular possible way. In other words, a node manager should only know about the subsystem it manages, not about the managers it is linked to. Therefore, the internal structure of a node manager should be such that it can work in any possible context.
The solution to the problem is based on the following observations. Let us assume that node \( x \) has an initiator port \( i \) linked to recipient port \( r \) of node \( y \). Thus any change inside \( x \) that depends on transaction \( \langle i, r \rangle \) must occur before the changes inside \( y \) that depend on \( \langle i, r \rangle \). Therefore the requests of the change commands inside \( y \) must be acknowledged by the change commands inside \( x \). Therefore the direction of requests is opposite to the direction of the transaction that establishes the dependency between \( x \) and \( y \). To sum up, the configuration manager \( x' \) for \( x \) has recipient port \( i \), the manager \( y' \) for \( y \) has initiator port \( r \), and the requests of \( y' \) are passed to \( x' \) through transaction \( \langle r, i \rangle \). If the system’s transaction \( \langle i, r \rangle \) is going to be blocked then the reconfiguration manager for \( x' \) to sub-manager \( y' \). In this case port \( r \) of \( y' \) is connected to the recipient port of block \( \langle i, r \rangle \) whose initiator port is linked to port \( i \) of \( x' \).
To put it in more general terms, the configuration manager for a hierarchical system \( S \) consists of one component for each command, one component called nop, and one configuration manager for each node in \( S \). A node manager has the same interface as the node whose reconfiguration it manages, except that initiator ports are exchanged with recipient ports. This implies that the manager’s port dependency relation is the inverse of the node’s dependencies, and that connections among node managers are the opposite of those between nodes, except for transactions that must be removed. Those will be of course substituted by the respective block command.
**Definition 9** The system configuration manager that reconfigures the hierarchical system \( \langle N, T \rangle \) according to commands \( C \) is a system \( \langle N', T' \rangle \) where
\[
N' = \{ \langle R_{n}, I_{n}, D_{n}^{-1} \rangle \mid n \in N \} \\
\cup \{ \langle p_{c}, s_{c} \rangle, \langle s_{c}, p_{c} \rangle \} \mid c \in C \} \\
\cup \{ \{ \text{nop} \}, \{ \text{nop} \}, \{ \} \}
\]
and \( T' \) is the smallest relation that satisfies
1. \( \langle r, i \rangle \in T' \) if \( \langle i, r \rangle \in T \land \text{block} \langle i, r \rangle \notin C \);
2. \( \langle r, s_{c} \rangle, \langle p_{c}, i \rangle \in T' \) if \( c = \text{block} \langle i, r \rangle \);
3. \( \langle p_{c}, s_{c} \rangle \in T' \) if \( c' < c \);
4. \( \langle p_{c}, \text{nop} \rangle \in T' \) if \( 3c' < c \);
5. \( \langle \text{nop}, s_{c} \rangle \in T' \) if \( 3c' < c \).
**Definition 10** The node configuration manager for a composite node with interface \( \langle J, R, D \rangle \) and system \( \langle N, T \rangle \), to which commands \( C \) will apply, is a composite node with interface \( \langle R, I, D^{-1} \rangle \) and system configuration manager \( \langle N', T' \rangle \).
Applying the definition to the example of Figure 7 we get the manager depicted in Figure 8. Notice how indeed \( e \) gets blocked only after \( a \), since the request of block \( e \) is passed along \( N' \) back through the other port of \( N' \) to block \( a \).
For the definition to be complete it remains to be said how a configuration manager \( x' \) for a simple node \( x \) behaves. As for any node manager its interface is the “mirror” of the node’s interface, and the same happens to port dependencies. If recipient port \( r \) of \( x' \) (the manager!) depends on initiator port \( i \), then \( x' \) must forward any request received on \( r \) to port \( i \). If \( r \) does not depend on any initiator port, then \( x' \) acknowledges immediately any request received by \( r \). As usual, all transactions connected to a initiator port are also immediately started.
Returning to our example, let us assume that all nodes from \( A \) to \( F \) are simple. Then \( a \) can be blocked at once since \( A' \) attends the request made by block \( a \). \( F' \) issues a request to block \( e \) which gets forwarded by \( C' \) and \( D' \) until \( A' \) which gets immediately acknowledged at that point. In a slightly optimized implementation of this model, if block \( a \) had already executed, it would acknowledge block \( e \)’s request without forwarding it to \( A' \). As a further example, consider that there is no dependency between the ports of \( C \) (i.e., \( b \) is independent of \( d \)). Then block \( e \) is acknowledged at the recipient port of \( C' \) and therefore \( a \) and \( e \) can be blocked in parallel as desired.
\(^2\) A composite node manager also does this, the only difference being that the forwarding is done through the dependency path made explicit by the composite node’s architecture.
7. Conclusions
Dynamic reconfiguration is a problem specific to parallel and distributed systems that has practical relevance. We have adopted a simple and general framework at the software architecture level stating which parts of the system should be “frozen” in order to achieve a stable consistent state and how the “freezing” and the changes are performed. We analyzed, formalized, refined, and extended the framework in order to minimize disruption and to handle hierarchic systems.
In fact, switching from a component based to a connection based approach, we have come up with a minimal solution (since it only blocks the connections that will be removed) that is conceptually very simple and not harder to implement. On the other hand, for the first time for this framework, we have concentrated on the time taken by the reconfiguration process. In particular we have defined an order for the change commands that may reduce, considerably, the disruption of independent parts of the system being reconfigured. The assumption is, again, that commands may be executed in parallel.
Since a configuration manager executes the commands of a given change specification, it can be seen as itself a system of interconnected components, where a component is a single change command and a connection denotes the dependency between the two commands it links together. This model gives a precise and complete account on how a configuration manager may execute a change specification. The model is also particularly useful for hierarchic systems, showing how the reconfiguration process of the whole system can be obtained simply by connecting the configuration managers of the subsystems together, in a way that mirrors the connections between the subsystems.
We plan to further develop this view of a configuration manager as a system like the one it manages. In particular, this view implies that a configuration manager might be subject to reconfiguration too. In other words, a change specification can be changed. We think this might be useful in two situations: failures and validation. If an ongoing reconfiguration fails for some reason, then one may try to find another but equivalent (or similar) reconfiguration. A simpler approach is to undo the changes done so far and re-establish the existing system. In both cases it means that the existing change specification has to be changed while it is being applied, i.e., the configuration manager which is executing the changes must be reconfigured dynamically.
The other situation concerns the validation process. A change in a subsystem (like the removal without replacement of a server) may force some changes to be done in other parts of the system (like substituting a dependent transaction by an independent one). Thus the validation of the change specification for a subsystem may force the change specifications of other subsystems to be changed. On the other hand, this means that the validation of those systems must be re-done which may cause further changes in the specifications of other subsystems and so on. Again, change specifications may change dynamically (in this case as they are validated).
References
|
{"Source-Url": "http://oro.open.ac.uk/41192/1/wermelinger97pdse.pdf", "len_cl100k_base": 12808, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 48785, "total-output-tokens": 14311, "length": "2e13", "weborganizer": {"__label__adult": 0.0002300739288330078, "__label__art_design": 0.0003833770751953125, "__label__crime_law": 0.00021278858184814453, "__label__education_jobs": 0.0007390975952148438, "__label__entertainment": 5.698204040527344e-05, "__label__fashion_beauty": 0.00010669231414794922, "__label__finance_business": 0.0002417564392089844, "__label__food_dining": 0.0002551078796386719, "__label__games": 0.0004930496215820312, "__label__hardware": 0.0007491111755371094, "__label__health": 0.0003147125244140625, "__label__history": 0.00024044513702392575, "__label__home_hobbies": 7.152557373046875e-05, "__label__industrial": 0.0003037452697753906, "__label__literature": 0.0002627372741699219, "__label__politics": 0.00018918514251708984, "__label__religion": 0.0003757476806640625, "__label__science_tech": 0.0264129638671875, "__label__social_life": 6.288290023803711e-05, "__label__software": 0.0108184814453125, "__label__software_dev": 0.95654296875, "__label__sports_fitness": 0.00018727779388427737, "__label__transportation": 0.000385284423828125, "__label__travel": 0.00018513202667236328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59868, 0.01588]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59868, 0.60807]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59868, 0.92781]], "google_gemma-3-12b-it_contains_pii": [[0, 419, false], [419, 4225, null], [4225, 8358, null], [8358, 13145, null], [13145, 17795, null], [17795, 23523, null], [23523, 29345, null], [29345, 34929, null], [34929, 40086, null], [40086, 45280, null], [45280, 49648, null], [49648, 54878, null], [54878, 59868, null]], "google_gemma-3-12b-it_is_public_document": [[0, 419, true], [419, 4225, null], [4225, 8358, null], [8358, 13145, null], [13145, 17795, null], [17795, 23523, null], [23523, 29345, null], [29345, 34929, null], [34929, 40086, null], [40086, 45280, null], [45280, 49648, null], [49648, 54878, null], [54878, 59868, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59868, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59868, null]], "pdf_page_numbers": [[0, 419, 1], [419, 4225, 2], [4225, 8358, 3], [8358, 13145, 4], [13145, 17795, 5], [17795, 23523, 6], [23523, 29345, 7], [29345, 34929, 8], [34929, 40086, 9], [40086, 45280, 10], [45280, 49648, 11], [49648, 54878, 12], [54878, 59868, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59868, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
354c0f9ef9a7f50dbfd23e76848994203fdc8e74
|
[REMOVED]
|
{"Source-Url": "http://orbit.dtu.dk/files/110988163/AERBAC_TrustBus_20150618_.pdf", "len_cl100k_base": 9288, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 40887, "total-output-tokens": 11480, "length": "2e13", "weborganizer": {"__label__adult": 0.0004336833953857422, "__label__art_design": 0.0007524490356445312, "__label__crime_law": 0.0016002655029296875, "__label__education_jobs": 0.0018033981323242188, "__label__entertainment": 0.0001575946807861328, "__label__fashion_beauty": 0.00026988983154296875, "__label__finance_business": 0.002826690673828125, "__label__food_dining": 0.0004267692565917969, "__label__games": 0.0008077621459960938, "__label__hardware": 0.0012569427490234375, "__label__health": 0.0010662078857421875, "__label__history": 0.0004346370697021485, "__label__home_hobbies": 0.000156402587890625, "__label__industrial": 0.0007977485656738281, "__label__literature": 0.0005240440368652344, "__label__politics": 0.0006651878356933594, "__label__religion": 0.0004208087921142578, "__label__science_tech": 0.325927734375, "__label__social_life": 0.0001703500747680664, "__label__software": 0.06805419921875, "__label__software_dev": 0.59033203125, "__label__sports_fitness": 0.00023543834686279297, "__label__transportation": 0.0004992485046386719, "__label__travel": 0.0002372264862060547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46089, 0.03123]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46089, 0.56831]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46089, 0.84552]], "google_gemma-3-12b-it_contains_pii": [[0, 754, false], [754, 3217, null], [3217, 6489, null], [6489, 9777, null], [9777, 12250, null], [12250, 15689, null], [15689, 18431, null], [18431, 21703, null], [21703, 23977, null], [23977, 26771, null], [26771, 30534, null], [30534, 33513, null], [33513, 36888, null], [36888, 40223, null], [40223, 42854, null], [42854, 46089, null]], "google_gemma-3-12b-it_is_public_document": [[0, 754, true], [754, 3217, null], [3217, 6489, null], [6489, 9777, null], [9777, 12250, null], [12250, 15689, null], [15689, 18431, null], [18431, 21703, null], [21703, 23977, null], [23977, 26771, null], [26771, 30534, null], [30534, 33513, null], [33513, 36888, null], [36888, 40223, null], [40223, 42854, null], [42854, 46089, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46089, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46089, null]], "pdf_page_numbers": [[0, 754, 1], [754, 3217, 2], [3217, 6489, 3], [6489, 9777, 4], [9777, 12250, 5], [12250, 15689, 6], [15689, 18431, 7], [18431, 21703, 8], [21703, 23977, 9], [23977, 26771, 10], [26771, 30534, 11], [30534, 33513, 12], [33513, 36888, 13], [36888, 40223, 14], [40223, 42854, 15], [42854, 46089, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46089, 0.04367]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
7c37ef1054152529a79831593092b0ee9cde9583
|
RESTAURANT MANAGEMENT SYSTEM
Submitted to
Dr. Lee Iverson
On July 25, 2006
By
Team 1
Corry Yang
Clement Wu
Tina Lin
Alan Chang
EECE 474
The University of British Columbia
RESTAURANT MANAGEMENT SYSTEM
Submitted to
Professor Lee Iverson
By
Team 1
Corry Yang
Clement Wu
Tina Lin
Alan Chang
EECE 474
The University of British Columbia
July 25, 2006
ABSTRACT
Customer satisfaction is the key to success for any business. In a restaurant, the traditional hand-waving method for calling services is inefficient often leading to many complaints. The Restaurant Management System increases operational efficiency through use of an internal wireless communications system and a statistical data processing unit. The communications system increases customer satisfaction by leaving a transmitter at each table which the customer can use to request for a server. A data processing unit allows managers and owners to easily monitor restaurant functions and employee progress. To make this system a reality, Atmel’s ATmega16 microcontroller, Maxstream’s XBee/XBee-PRO Zigbee transceivers and the TM162ADA7-2LCD Liquid Crystal Display (LCD) will be the key parts that will be used.
TABLE OF CONTENTS
ABSTRACT ........................................................................................................................ II
TABLE OF CONTENTS ....................................................................................................... III
LIST OF FIGURES .......................................................................................................... V
LIST OF TABLES ........................................................................................................... VI
LIST OF ABBREVIATIONS ............................................................................................ VII
1.0 INTRODUCTION ...................................................................................................... 1
1.1 PROJECT BACKGROUND .................................................................................. 2
1.2 SYSTEM DESIGN ............................................................................................... 3
2.0 DESIGN REQUIREMENT AND GOALS .................................................................. 5
2.1 CLIENT INTERACTION ...................................................................................... 5
2.2 HARDWARE DESIGN REQUIREMENT ................................................................ 9
2.2.1 The Transmitters ................................................................................... 9
2.2.2 The Receivers ....................................................................................... 9
2.3 SOFTWARE DESIGN REQUIREMENT .............................................................. 11
3.0 HARDWARE COMPONENTS .................................................................................. 12
3.1 TRANSMITTER MODULE ................................................................................ 12
3.1.1 Customer Interface .............................................................................. 12
3.1.2 Passive Power Circuit ....................................................................... 12
3.1.3 Multi-use Components ..................................................................... 13
3.1.4 Microcontroller ............................................................................... 14
3.1.5 Obstacles ......................................................................................... 15
3.1.6 Future Developments ..................................................................... 16
3.2 RECEIVER MODULE ........................................................................................ 17
3.2.1 Microcontroller ............................................................................... 20
3.2.2 Future Developments ..................................................................... 22
3.3 THE COMMUNICATIONS PROTOCOL ......................................................... 23
3.3.1 Universal Asynchronous Receiver Transmitter (UART) ...................... 24
3.3.2 Signal Format ................................................................................... 24
3.3.3 Protocols ......................................................................................... 25
3.3.4 Obstacles ....................................................................................... 26
3.3.5 Future Developments ..................................................................... 26
4.0 SOFTWARE PROGRAM ......................................................................................... 28
4.1 MAIN DISPATCHER SYSTEM .......................................................................... 28
4.1.1 Graphical User Interface (GUI) ............................................................ 29
4.1.2 Serial Port ......................................................................................... 29
4.1.3 Database ............................................................................................ 31
4.1.4 Data Flow ......................................................................................... 33
4.1.5 Functionality ................................................................................... 35
LIST OF FIGURES
Figure 1.0: Result of the Consumers’ Survey in Pie Graphs .............................................. P.6
Figure 2.0: Result of the Managers’ Survey in Pie Graphs .............................................. P.8
Figure 3.0: Data Signal and Dispatcher Flag ................................................................. P.15
Figure 4.0: Schematic of the Receiver Unit (Using Eagle) ............................................ P.18
Figure 5.0: CircuitMaker2000 Schematics for the Receiver Unit Power Circuit ........ P.19
Figure 6.0: Correct data from the Dispatcher to Receiver ........................................... P.21
Figure 7.0: An example of how the LCD displays the data signal .............................. P.22
Figure 8.0: Sample Table Data .................................................................................. P.23
Figure 9.0: Simplified Data Model ............................................................................. P.33
Figure 10.0: Data Flow Diagram ............................................................................... P.34
Figure 11.0: Table Tab Screen Shot ................................................................. P.37
Figure 12.0: Request Table Screen Shot ............................................................... P.38
Figure 13.0: UART Transmission ............................................................................. P.40
Figure 14.0: Switch Bouncing ............................................................................... P.41
Figure 15.0: CircuitMaker2000 Schematics and Testing Waveforms for the Receiver Unit Power Circuit ................................................................. P.42
Figure 16.0: Hapsim Simulation of the LCD Display using AVR Studio ............... P.43
LIST OF TABLES
Table 1.0: The Data Signal for Different Customer Requests ........................................ P.14
Table 2.0: XBee DO Output Voltage ............................................................................. P.19
Table 3.0: Atmega Iutput Voltage ................................................................................. P.20
Table 4.0: Interactions between State[] and Request_Display[] .................................. P.22
LIST OF ABBREVIATIONS
DBM ................................................................. Database Management System
GUI ........................................................................ Graphical User Interface
IDEs ............................................................. Integrated Development Environments
JRE ........................................................................ Java Runtime Environment
LSB .................................................................... Least Significant Bit
LED ..................................................................... Light Emitting Diode
LCD ..................................................................... Liquid Crystal Display
MCU ................................................................. Microcontroller Unit
OS ....................................................................... Operating System
RF ......................................................................... Radio Frequency
RDBMs ............................................................. Rational Database Management System
SWT ....................................................................... Standard Widget Toolkit
SQL ....................................................................... Structured Query Language
SDN ....................................................................... Sun Developer Network
TA ......................................................................... Teaching Assistant
UART ............................................................... Universal Asynchronous Receiver Transmitter
1.0 INTRODUCTION
In many popular restaurants, waiters/waitresses tend to miss out on tables or customers’ calls during busy hours potentially decreasing ones clientele. While this is an ongoing issue, there is still no product that drastically improves the communication between the servers and the customers in the current market. Hence, the goal is to design a system in which the customers can call their servers easily and help the restaurant increase overall efficiency.
The Restaurant Management System incorporates Radio Frequency (RF) communication hardware alongside a statistical data processing unit. An internal wireless communication system will allow prompt notification to the server when a customer requires service. Moreover, servers can also be more focused on serving their current customers and save their time and energy from always keeping an eye out for needy customers.
The data processing unit will have a database for incoming signals, a program to manipulate data and a Graphical User Interface (GUI). On top of meeting the needs of customers, restaurant managers can also monitor the response time of their waiters/waitresses through use of this system. Hardworking, proficient employees will become more recognized while lazy, inefficient employees become motivated to improve. As a result, the restaurant becomes more efficient and possibly increasing morale while improving the level of customer satisfaction.
There are three main components to the system: Transmitters, Receivers and the Main Dispatcher. This report will discuss the updated system design and specifications of each component. Further explanations will be provided reviewing the parts selection process of our main components and testing processes.
### 1.1 PROJECT BACKGROUND
One system that is currently in the market is the Coaster Lite™ by Long Range Systems. [http://pager.net/Long-Range-Systems/push-for-service-coaster-lite.html] The Coaster Lite consists of only one button. When the customers require assistance, they will press the button and the Coaster Lite will glow in the dark. The Servers will go to tables that have a glowing Coaster Lite. Nonetheless, this system remains inefficient because it requires servers’ constant visual attentions to the device.
The RF technology used in the project of Summer 2005 Team 1, “Computer Interface Tracking System”, inspires our group in our RF design. [http://www.ece.ubc.ca/~elec474/reports/summer05/Team%201%20Final%20Report.pdf]. It is a system which “involves 4 receiver modules and several transmitter modules” and “[t]he receiver-modules detect the received signal strength and output it to the central board”. Although the numbers of RF components and the principle of operations are different, our group still find their RF communication design useful in building our own system. For example, they have a central system which receives and processes the signals from the transmitters, a GUI which can “continuously listen for signals coming in from the microcontroller ATmega32”, and a functional RF communication
scheme. Moreover, their project has provided us a lot of ideas regarding signal transmission and identification.
Another project that can contribute to our design is Team 7’s “Radio Frequency Foot Pressure Measuring System” in also of the same semester. Our group finds that the ZigBee-PRO transceivers implementation and their detailed explanation in how data are transmitted using RF can be an important source of information for our RF communication design too.
In addition, Teaching Assistant (TA) Farshid mentioned about a hospital room occupancy project that was done last term in 2005-2006. We can definitely draw references to their dispatching system and microcontroller designs. Unfortunately, the report is not posted online yet. Hence, we are making a request to professor Iverson to see the final project report and are still waiting for his response.
Lastly, we also have conducted several interviews with waiters/waitresses who are currently working in various restaurants. According to their responses, we were able to sketch out the common requests and implement them in our designs.
1.2 SYSTEM DESIGN
Restaurant Application System is specifically made to increase efficiency of the restaurant with three distinct components: Transmitters, Receivers, and a Main Dispatcher software program. Whenever a customer requires help, their request can
be more promptly answered through use of the Transmitter which will be located on each table. The Transmitter will then send a wireless signal to the Main Dispatcher to be forwarded to the Receiver of your server.
The customer may send either a general request or a bill request by activating the appropriate switch on the Transmitter. When a general request is sent, your server will receive a notification on the LCD of their Receiver and will come to your table at the earliest convenience. To help decrease wait time, the bill request first signals the cashier to print out the bill. Once the bill is printed, your server will then be notified to pick up the bill and bring it to your table. Because of this functionality, the main dispatcher software is suggested to be installed at cashier so that bills may be printed once a bill request is received.
With the Main Dispatcher software, the store manager may manage waiter and table assignments through this software program. Further statistics such as incoming request time and request completion times will also be logged and saved for administrative purposes. Management users can use this data during promotion and awards processes. Restaurants will be able to significantly increase overall efficiency of operations and customer satisfaction through use of the System.
2.0 DESIGN REQUIREMENT AND GOALS
2.1 CLIENT INTERACTION
Two surveys were conducted on the application of Restaurant Management System. One survey is conducted with restaurant customers, and the other is conducted with restaurant owners and managers.
The following are the questions and the results from customer survey. There were 20 participants.
1. Do you find it hard to obtain attention from the waiters in a Restaurant?
2. Do you find it frustrating for not getting attention from the waiters?
3. Would you be impressed if a Restaurant has this application?
4. Would this application enhance your experience in a Restaurant?
5. Would you tip more if you get better services in a Restaurant?

The following are the questions and results for restaurant owners / manager survey.
There were 10 participants. Participants of the survey include: The Keg, Cactus Club, Whitespot, Boston Pizza, and TGI Fridays.
1. Are you impressed by the functionalities of this application?
2. Would you think this application will help your restaurant?
3. Would you like to have this installed in your restaurant?
4. Would this application enhance customers’ experience at your restaurant?
5. Would you install a transmitter in every table?
Following the survey, another meeting was conducted with the manager of TGI Friday in Burnaby. During the meeting, the manager expressed the interest to purchase this application with a budget around $2500. This budget will include the cost to install a transmitter in thirty-five tables, one dispatcher system, and six receivers for the waiters. The cost of each transmitter is roughly $40, receiver $60, and the main dispatcher system $100. The total cost of this application will be approximately $1860 with a gross margin of $640. If more functionality is added in the future, this system may be sold at $3300. The target gross margin is $1000+.
Figure 2.0: Result of the Managers’ Survey in Pie Graphs
2.2 HARDWARE DESIGN REQUIREMENT
2.2.1 The Transmitters
The Transmitter is the first stage of the Restaurant Management System that allows customer interaction. With a flick of a switch, a server will be notified and will come to the customer ending the days where they would need to search for a server or wave to get the attention of one. There are three main requirements that are adhered to when designing the Transmitter.
a. Ease of Use – The device must be as customer-friendly as possible. The design should be simple and straightforward to the extent that usage would be self-explanatory.
b. Low Power Consumption – Ideally, the transmitters should be able to run for a month without needing to change the battery.
c. Low Cost – Since the transmitter is the most widespread device in the system, unit cost must be kept to a minimum.
2.2.2 The Receivers
Waiter or waitress given this device will wear the Receiver unit during his or her shifts within the restaurant. In peak hours, he or she should be able to read off from the LCD display regarding pending customers in one’s assigned zone. Hence, a few key hardware requirements can be concluded.
1. The device should be mobile and portable enough for the restaurants servers to carry. In addition, it should also have a reasonable size, so that the waiter/waitress can keep it in his or her vision, such as the wrist area (like a watch) or around the waist (clipped on the belt).
2. Power consumption should be low enough, so the Receiver unit can use the same +9V battery for at least 2 weeks.
3. LCD should use a reasonable font size, so the waiter/waitress feels comfortable skimming through it during busy hours
4. Proper alarming method is also a nice feature to have, mechanism such as vibrations or flashings are good ways to notify the servers.
5. Communication between Dispatcher should be successful in most cases.
6. Able to have special visual cue for tables who have been waited for too long or for VIP guest tables.
In addition, to demonstrate the Dispatcher and Transmitter can send requests in a different zone, i.e. Zone2. The Receiver should also display Zone2 View using the same Receiver unit. However, this is only implemented for the demonstration.
2.3 SOFTWARE DESIGN REQUIREMENT
The main features of the main dispatcher software are receiving requests from customers properly, displaying requests on GUI, and send the requests out to the assigned waiter/waitress. The following is a list of the must haves with the main dispatcher software:
1. Any change made on GUI must also be changed in the database
2. Request Id of the request table should auto increment when a request is received
3. Request arrival time must be the same as current time when the request is received
4. Time must be shown in the correct format: (hh:mm:ss)
5. All contents in database tables must be shown correctly
6. Filter function must filter properly
7. All buttons on GUI should work properly
8. Software should be implemented to have table and waiter assignments feature
9. Monitor waiter/waitress performance by calculating time it takes to complete a request
10. Request table must be refreshed automatically every three seconds
All of the software requirements are tested and verified.
3.0 HARDWARE COMPONENTS
3.1 TRANSMITTER MODULE
The final design of the Transmitter consists of two Rocker Switches used to signal a waiter whenever you would like your bill or have a general request. When a switch is turned ON, an LED lights up to indicate that the request is active. Internally, the Transmitter is powered by a 9V battery coupled with a passive power circuit to conserve power. Other than the microcontroller and transmitter, low-cost components such as resistors and BJT transistors are used to minimize cost.
3.1.1 Customer Interface
The initial customer interface of the Transmitter consisted of only one rocker switch and one LED. Whenever the switch is activated, the LED would turn on and a server would be requested. After further thought and consultation with local restaurants, a second set was added to facilitate a Bill request. At the end of every meal, a bill is always requested so it is only logical to implement the function. Lastly, the traditional ON/OFF switch was removed to prevent accidentally turning off the device.
3.1.2 Passive Power Circuit
For the majority of time, both rocker switches are in the OFF position and the Transmitter is just idling away, wasting unnecessary power. Based on this observation, the rocker switches are given a second duty of controlling the
power in the circuit. When both switches are OFF, there will be no power to the circuit. Should any of the switches be ON, the device will be powered on. Hence, in stead of the traditional ON/OFF switch, a passive power supply circuit using the rocker switches was incorporated into the Transmitter.
The Transmitter currently draws up to 55mA of current when transmitting. Should the device be powered by a common 200mAH rechargeable battery, this constitutes at least 3.5hrs of continuous transmission. In a real-life scenario however, the device is transmitting at most 5% of the time so battery life can easily increase ten-fold. Due to time constraints, the Transmitter were not tested in a real-life scenario therefore it is unsure whether a battery would be able to last a month.
3.1.3 Multi-use Components
To keep costs low, inexpensive parts were used whenever performance would not be compromised and some components were even given more than one task. A transistor is used in place of an op amp to amplify current, LEDs and resistors replace the need for voltage regulators and as already mentioned, the rocker switches also serve as an ON/OFF switch. The only exceptions are the transmitter¹ and the microcontroller² as they were chosen to reduce the workload on the group.
¹ The Xbee used in our device is a transceiver however; it is only used in transmitter mode. Refer to the Parts Selection section for further details.
² See Recommended Upgrades section for less costly alternatives.
3.1.4 Microcontroller
Using CodeVisionAVR to program Atmel Atmega16 microcontroller unit, the group can build Transmitter units having the following functionalities.
- Denounce and read PORTA for customer requests
- Transmit Table Number and Request Type (i.e. the data signal) to the Dispatcher
- Transmit 3 redundant data signals to ensure the data reach Dispatcher
- Transmit the same data signal again when customer requests are not cancelled in 90 seconds
<table>
<thead>
<tr>
<th>Decimal</th>
<th>Table Number</th>
<th>Binary</th>
<th>Request Type</th>
<th>Hex</th>
</tr>
</thead>
<tbody>
<tr>
<td>Reserved for Other Uses (e.g. flags)</td>
<td>0 0 0 0 0 0 0 0</td>
<td>0 0 0 0 0 0 0 1</td>
<td></td>
<td>0x00</td>
</tr>
<tr>
<td></td>
<td>0 0 0 0 0 0 0 1</td>
<td>0 0 0 0 0 0 0 1</td>
<td></td>
<td>0x01</td>
</tr>
<tr>
<td></td>
<td>0 0 0 0 0 0 1 0</td>
<td>0 0 0 0 0 0 0 1</td>
<td></td>
<td>0x02</td>
</tr>
<tr>
<td></td>
<td>0 0 0 0 0 1 1</td>
<td>0 0 0 0 0 0 1 1</td>
<td></td>
<td>0x03</td>
</tr>
<tr>
<td>4</td>
<td>Table 1</td>
<td>0 0 0 0 0 1 0 0</td>
<td>Reset Both</td>
<td>0x04</td>
</tr>
<tr>
<td>5</td>
<td></td>
<td>0 0 0 0 0 1 0 1</td>
<td>G, Reset B</td>
<td>0x05</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0 0 0 0 0 1 1 0</td>
<td>B, Reset G</td>
<td>0x06</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0 0 0 0 0 1 1 1</td>
<td>Send Both</td>
<td>0x07</td>
</tr>
<tr>
<td>8</td>
<td>Table 2</td>
<td>0 0 0 0 1 0 0 0</td>
<td>Reset Both</td>
<td>0x08</td>
</tr>
<tr>
<td>9</td>
<td></td>
<td>0 0 0 0 1 0 1 0</td>
<td>G, Reset B</td>
<td>0x09</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0 0 0 0 1 0 1 1</td>
<td>B, Reset G</td>
<td>0x0A</td>
</tr>
<tr>
<td></td>
<td></td>
<td>0 0 0 0 1 1 1 1</td>
<td>Send Both</td>
<td>0x0B</td>
</tr>
</tbody>
</table>
**Table 1.0:** The Data Signal for Different Customer Requests.
To communicate with XBee Module, Atmega16 uses the Universal Asynchronous Receiver Transmitter (UART) protocol to send signals to the Dispatcher. Therefore, we can store the table numbers and table requests in the 8 data bits in the UART communication: 5 bits for table numbers and 2 bits for...
requests types. Bit 7 is reserved as Dispatcher Flag to distinguish between the
Transmitter data signals and the Dispatcher data signals. A restaurant can have a
maximum number of $2^5=32$ tables using this algorithm.
<table>
<thead>
<tr>
<th>Transmitter Data Signal:</th>
<th>Dispatcher Data Signal:</th>
</tr>
</thead>
<tbody>
<tr>
<td>0 0 0 0 0 1 X X</td>
<td>1 0 0 0 0 1 X X</td>
</tr>
</tbody>
</table>
**Figure 3.0:** Data Signals and Dispatcher Flag
Within the time range between 1 and 10 seconds, 3 Redundant signals are sent
in randomized time periods using the rand() function predefined in C.
Consequently, the method reduces the risks of collisions because not the
possibility the signals being transmitted and received in the same time is small.
In addition, the redundant signal which will be processed by the Dispatcher also
provides assurance to the accuracy of the signals.
If in any case, the data signals are not processed by the Dispatcher; for example,
the data signals are lost or the waiters are to busy helping other customers. The
transmitter will resend the original signal in 90 seconds using a simple counter
loop.
### 3.1.5 Obstacles
**Power Requirements:**
In the initial design of the transmitter circuitry, only Vcc was considered and the
components were naively powered using a simple resistor voltage divider
controlled by a two-transistor OR gate. After further examination of the ATMega16 and XBee datasheets were current requirements finally noted. Due to significantly different requirements of the two devices (ATMega16’s 5V @ 12ma vs XBee’s 3.3V @ 45ma), this issue proved to be a big obstacle.
The initial approach was to use an op-amp as a current amplifier but this idea would actually make the circuit even more complicated by adding many more components and requiring an additional set of voltages to power it. After extensive research on our requirements, a new Passive Power Circuit was implemented consisting of a two-diode OR gate to power the ATMega16 which in turn activates a transistor current amplifier that will power the XBee.
3.1.6 Future Developments
If we continue to use the XBee module beyond our prototypes, we can also connect the DO pin from the XBee to Atmega16. By receiving an ACK, acknowledgement packet, the Transmitter will be able to know exactly when the transmissions fail (pg.20 of the XBee product manual). In this way, the Transmitter unit will not need to send out redundant data signals as often and the data signals will be less likely to collide in RF channel.
Although the cost of XBee is a little bit high for the cost per table, decent wireless communication cannot be achieved with devices that transmit only. Mutual communication is essential between the Dispatcher and Transmitters to find the best time frame to send data signals in a clear channel.
### 3.2 RECEIVER MODULE
The hardware aspect of the Receiver Unit includes 5 different components: the power switch, the multiplexer switch, the Atmega16 MCU, the XBee unit and the TM162A LCD module.
- **Power Switch:** Turn the Receiver ON/OFF
- **Multiplexer Switch:** If it is on, then it will send a signal to PORTB to show Zone2 view on the LCD
- **Atmega16:** It receives, stores and manipulate incoming data signals from the XBee
- **XBee:** It receives the data from Dispatcher then uses UART to give data to Atmega16
- **LCD:** It prints out table numbers and pending requests
Here is a schematic diagram for the circuitry of our Receiver unit.

**Figure 4.0:** Schematic of the Receiver Unit (Using Eagle)
Our group also used CircuitMaker2000 to simulate the correct voltage and current flowing through each component (See Figure 4.0 below).
The voltage regulators keep the voltage flowing through LCD, Atmega16, and XBee constant. R1, R2, R3 are setup to control current flowing through each device. As for the communication between the Atmega16 RXD pin and XBee DO pin, a diode and a resistor is required to provide decent UART communication.
In specific, XBee DO pin can only output signal with a maximum output high of Vcc-0.5=2.8V (see Table 2.0). However, Atmega16 does not read the signal unless the signal has a minimum 0.7*Vcc=3.5 V (see Table 3.0). Therefore, In order to achieve proper communication, a diode and 1kΩ resistor is used.
| V_{DL} | Output Low Voltage | I_{DL} = -2 mA, VCC >= 2.7 V | - | - | 0.5 | V |
| V_{OH} | Output High Voltage | I_{OH} = -2 mA, VCC >= 27 V | VCC - 0.5 | - | - | V |
Table 2.0: XBee DO Output Voltage
Using CodeVisionAVR to program our Atmel Atmega16 microcontroller unit, our team can build Receiver units which have the following functionalities.
- Debounce and read PORTB for the multiplexer switch
- Receive Dispatcher flag and Zone number from the main computer
- Receive Table Numbers and Request Type (i.e. the data signal) from the Dispatcher
- Store data signals into appropriate State[] Array position
- Convert the State[] into LCD display arrays: Table_Display[] and Request_Display[]
- Print the display arrays on LCD
- If the multiplex switch is on, then the screen will switch between Zone1 view and Zone2 view
In the beginning, the Receiver unit will check the Dispatcher Flag (see Figure 5.0 below) to determine whether to process the incoming signal. Dispatcher flags are set to distinguish the incoming signals received from the Dispatcher and the Transmitters. Also, for the received_data from the dispatcher, bit 7 is marked as a 1 to indicate this is a signal from Dispatcher.
Figure 6.0: Correct data from the Dispatcher to Receiver
However, there are two methods for the Dispatcher to send the pending requests to the Receiver unit.
- Send all pending requests stored in Dispatcher constantly to each receiver.
- Send requests to the receiver only when the Dispatcher receives them from transmitter.
The advantage of the first method is that the Receiver microcontroller unit can simply update its LCD screen according to the incoming signals. Moreover, data signals can be processed more quickly in a computer than a microcontroller. However, the weakness of method 1 is that the Dispatcher will be always communicating with the receiver during busy hours. As a result, the XBee-PRO transceiver module will be more prone to lose data because the module sends the flags and data signals constantly. The module almost has no time to respond to the Transmitter Signals.
Hence, although method 2 requires the Atmega16 to interpret and store data in itself, a 16MHz Microcontroller Unit (MCU) with a 16K memory can still easily manage the received data in a reasonable time frame. Our group decides to use method 2 because it can guarantee better signal qualities.
Next, to manipulate the received data, the pending requests are stored into the State[Table_Number] array. Next, the State[] is used as a look up table for the Table_Display[] to look up the appropriate actions or character bytes to be stored in Request_Display[]. (See Table 4.0)
<table>
<thead>
<tr>
<th>State[]</th>
<th>Binary</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0 0</td>
<td>Clear Table and Request Array</td>
</tr>
<tr>
<td>1</td>
<td>0 1</td>
<td>Store 'G' and ' ' into Request_Display[]</td>
</tr>
<tr>
<td>2</td>
<td>1 0</td>
<td>Store 'B' and ' ' into Request_Display[]</td>
</tr>
<tr>
<td>3</td>
<td>0 1</td>
<td>Store 'G' and 'B ' into Request_Display[]</td>
</tr>
</tbody>
</table>
Table 4.0: Interactions Between State[] and Request_Display[]
In the end, the LCD will print the data stored in Table_Display[] and Request_Display[] in each row.
Figure 7.0: An example of how the LCD displays the data signals.
3.2.2 Future Developments
In our current design of the Receiver unit, data corruptions from the Transmitters are unavoidable. Moreover, not only the RF channel will be more jammed when the number of tables increases, the Receiver unit will also be more prone to read the wrong data signals because of data collisions.
Therefore, to reduce the possibility of data collisions and corruptions for the Receiver, data packets should have a larger “value-distance” between them. For example, the Dispatcher not only sends redundant signals, but also differentiates the redundant signals by increasing their value-distance (Figure 7.0). The advantage of this method is that the microcontroller can determine whether the data signal is corrupted more easily, because of the value-distance.

Moreover, like the Transmitter module, we can still use the XBee beyond our prototypes, so that the Receiver can send a confirmation signal to the Dispatcher to indicate that the message is received.
Another thing to note is that the multiplex switch and function is only implemented in the prototypes for demonstration. In the actual product, the Receiver unit should receive data signals for one Zone only.
### 3.3 THE COMMUNICATIONS PROTOCOL
Designing the Communications Protocol for the System was one of the greatest challenges since the Transmitter is a transmit-only device and the Receiver is a receive-only device preventing any form of handshaking. To help remedy this problem, the Communications Protocol utilizes a UART and a customized signal format.
3.3.1 Universal Asynchronous Receiver Transmitter (UART)
UART, it is a piece of computer hardware that allows the translation between parallel bits and serial bits. The general data format of each UART transmission consists of a Start bit, followed by five to eight Data bits (Least Significant Bit (LSB) first), an optional Parity bit and lastly, an End bit. The Current design sends eight Data bits and makes use of the Parity bit to aid in error-prevention.
3.3.2 Signal Format
The eight data bits consist of three types of data (refer to Protocol for more detailed information):
Bit 7: Source bit [One bit]
- Indicates the Source of Transmission (ie. Transmitter vs Dispatcher)
- 0 = Transmitter, 1 = Dispatcher
Bit 6 – 2: Table bits [Five bits]
- Indicates the Table ID
- Table IDs range from 0 to 31 with Table ID 0 reserved for the Dispatcher
Bit 1 – 0: Request bits [Two bits]
- Indicates the Request ID
- Two sets of Request IDs are used depending on the preceding Table ID
Table ID 0 (Dispatcher) ~ Receiver ID ranging from 0 to 3
Others ~ Service Required: Bit 1 = Bill Request, Bit 0 = General Request
### 3.3.3 Protocols
Global Transmission Rule: All data transmissions will be in sets of three made at random
- Intervals of up to five seconds.
**Transmitter:**
- All data transmissions will have the Source bit set to 0.
- A transmission is made whenever there is a change in switch state.
- Should there be no change in state within 15 seconds; a retransmission will be made with the exception of both switches OFF in which case there will be no transmission.
**Dispatcher:**
- All data transmissions will have the Source bit set to 1.
- Two bytes of data will be sent:
- First byte: 1 + 00000 + ID of Receiver desired
- Second Byte: 1 + Table ID + Request ID
- Should no signal be received from the Transmitter for 45 seconds, it will be assumed that both switches OFF.
**Receiver:**
A transmission of 1 + 00000 + own ID must be received prior to accepting any requests.
Only requests sent by the Dispatcher can be accepted.
### 3.3.4 Obstacles
Transmitter and Dispatcher Transmissions:
Originally it was planned to have Transmitters and Receivers operating on different channels and the Dispatcher would be the link between the two devices.
After further investigation, it was noted that channel configuration cannot be changed during real-time operation hence all devices would need to operate on the same channel. Due to a late arrival of the XBee devices and time constraints, one major problem was overlooked.
Allowing the Receiver to differentiate between the transmissions is a problem that was not detected until recently. The Receiver should only acknowledge transmissions from the Dispatcher but since both the Transmitters and Dispatchers operate on the same channel and use the same format, incorrect data received is highly likely. The solution is to add a Source bit to the signal format. This idea is quite simple however, discovering this bug so late in the project required many functions to be updated.
### 3.3.5 Future Developments
Transmitter:
Cost can be further reduced by replacing the XBee with a true transmit-only circuit. The ATMega16 microcontroller could also be replaced with another microcontroller (such as a PIC) to further reduce costs.
Communications Protocol:
Currently, the Communications Protocol supports only eight bit transmissions. Should additional tables or function switches will be added in the future; adjustments in either the software or the protocol would be required.
Handshaking is crucial for reliable transmissions. Should costs become feasible, all devices should include a transceiver in order to provide feedback for handshaking protocols.
4.0 SOFTWARE PROGRAM
The Dispatcher System is written in Java. A Java-development platform is required to implement the System. The Dispatcher System was created in a platform called Eclipse version SDK 3.2. Eclipse, along with the Java Runtime Environment (also known as JRE), provides a user-friendly platform. Both the Eclipse and the JRE is available for download at http://www.eclipse.org/downloads. To generate the GUI source code in Java, SWT designer was used. The SWT Designer version must match with the operating system (OS) and the Eclipse, and it can be downloaded at http://www.instantiations.com/swt-designer/download_content.html
4.1 MAIN DISPATCHER SYSTEM
The main dispatcher program is a software program that utilizes a personal computer to accept data via serial port of a wireless receiver, store data, display data on the screen and redistribute data to the designated receivers.
The software is implemented using Java programming language in the Eclipse platform, which was designed for building integrated development environments (IDEs).
The graphical user interface is implemented using Standard Widget Toolkit (SWT), a software component that delivers native widget functionality for the Eclipse platform in an operating system independent manner. The GUI display serves three main features; one, managing table assignments and waiter/waitress status using tables,
second, keeping track of waiter/waitress performances, and lastly, notifying cashier for billing requests.
MySQL, an open source rational database management system (RDBMs) that relies on structured query language (SQL) for requesting information from a database, is used in processing data in this dispatcher program.
4.1.1 Graphical User Interface (GUI)
The SWT Designer provides an easy to use environment for creating the GUI. The source code of the GUI is automatically generated when any graphics was added to the Java file. The code that is generated contains the properties of each individual GUI item. Some methods are created to control the entire GUI. Some methods are implemented to receive signals via serial port of a wireless receiver and redistribute signals via serial port to designated receiver.
4.1.2 Serial Port
RS-232 is used to communicate between the XBee and the Dispatcher System. Java itself doesn’t contain any class that communicates with the serial port. However, Sun Developer Network (SDN) provides an API extension for communicating with parallel and serial ports, specifically for Windows environments. The API can be downloaded at http://java.sun.com/products/javacomm. The Java Communications (a.k.a. javax.comm) API is a proposed standard extension that enables authors of communications applications to write
Java software that accesses communications ports in a platform-independent way.
It is very important to download the following files from SDN:
- comm.jar
- win32com.dll
- javax.comm.properties
And put these file into these directory:
- comm.jar should be placed in:
%JAVA%/jre/lib/ext
- win32com.dll should be placed in:
%JAVA%/jre/bin
%windows%/System32
- javax.comm.properties should be placed in:
%JAVA%/jre/lib
First, the Dispatcher System must detect the serial port that is connected with the XBee. After the serial port is located, the port must be identified and declared ownership by the Java program. Then, whenever there is data arriving at the serial port, the data will be stored in the buffer, waiting to be accessed.
For the Dispatcher System the following is the serial port parameters:
Baud Rate: 9600
- Data Bits: 8
- Stop Bits: 1
- Parity: None
These settings are the same as it is configured on the XBee.
4.1.3 Database
RDBM is a type database management system (DBM) that stores data in the form of related tables. There are five tables in the database: temp, request types, waiters, tables, and request.
1. “Temp”: This table has three columns: arrival time, table id, and type id. Arrival time indicates the time when main dispatcher program receives data via serial port of a wireless receiver. Therefore, all incoming data will temporarily be stored in this table first. The program will then determine the type of request by type id and add this request to the request table.
2. “Request Types”: This table has only two columns; type id and request type. The type id is stored as an integer and request type as a string. Thus, other methods in the database may retrieve request type string from an integer input for displaying data on the GUI.
3. “Waiters”: This table has four columns: waiter id, waiter first name, waiter last name, and whether or not the person is in the management position. When a waiter gets added or deleted to this table, the combo box on the ‘Tables’ tab will be refreshed to reflect the change.
4. “Tables”: This table has four columns: table id, waiter id, waiter first name and waiter last name. To add a table assignment, all it needs is the table id and a waiter id. Waiter first name and last name will automatically be stored in the table when a waiter id is specified.
5. “Request”: This table has eight columns: request id, arrival time, table id, request type, status, waiter first name, waiter last name, and waiter id. Request id is an auto increment integer value assigned to each request. Arrival time is directly retrieved from the temp table when the dispatcher program receives a signal. Waiter first name, last name, and waiter id are retrieved from tables table. Any request that gets added to the request table will have a “pending” status, only when a task is completed will have the status changed to “done.”
The following is a Simplified Data Model showing how each table are linked with each other.
4.1.4 Data Flow
The data flow of the main dispatcher system can be described by the following data flow diagram. The main dispatcher system is programmed to receive signals anytime when a signal is received through the serial port of the wireless device, not acquiring signals from the serial port. For this reason, the tables in the database have to be refreshed every few seconds. When the request has gotten its waiter id, the designated receiver, the main dispatcher program will send the signal out to the receiver. Two signals will be sent to the receiver, the first signal sent specifies which receiver to receive the data, and second signal contains its own table id and the request type id.
**Figure 10.0: Data Flow Diagram**
Diagram showing the flow of data and decision-making processes.
### 4.1.5 Functionality
There are three tables displaying on the GUI: Tables, Waiters, and Requests, each separated by tabs; one for table assignment, the other for waiter/waitress management, and third one for showing all requests from customers. The first two tables are mainly for managing purposes and the last table is an aid for the cashier to keep track of billing requests from customers, and for the store manager to keep track of waiter/waitress performances.
1. **“New” Button**: This button only appears in the Tables and Waiters tabs. It clears the data that is already appearing in the text fields which better prepares the manager for entering a new waiter/waitress information and/or table assignment. When this button is pressed, nothing is modified or added to the database.
2. **“Save” Button**: This button also, only appears in the Tables and Waiters tabs. When this button is pressed, the information that is entered into the text fields gets saved into the database and GUI table refreshes to reflect the change. This button is to save both new entries and modified entries to the table.
3. **“Delete” Button**: This button appears in all three tabs. It is to delete any single entry or multiple entries in the table. The user must select an
entry or pressing the Shift button down simultaneously to select multiple entries in order to delete it. By pressing the Delete button, data on GUI and database will be deleted.
4. “Waiter ID” Combo Box: The Waiter ID combo box from the Tables’ tab is a list all the available waiter/waitress in the restaurant, the same list of waiter Ids as the one in the Waiters table. When a waiter/waitress gets deleted from or added to the Waiters table, the change will also be reflected in this list. When making table assignments, the user may select a desired waiter/waitress, and automatically their first and last names will be passed on to the Waiter First Name and Waiter Last Name text fields.
5. “Filtering”: This function allows the user to filter out long entries in the Requests Table by Waiter Id, Task Status, or Request Type.
6. “Show All” Button: By pressing this button, the user will be allowed to view the complete Request Table again after filtering. It retrieves all the entries in the request table database.
7. “Clear Table” Button: This button allows the user to clear Request Table on GUI and the database. User confirmation is required before program clears the request table.
**Figure 11.0:** Table Tab Screen Shot
4.1.6 Obstacles
The Dispatcher System uses the RS-232 port instead of the USB port because Java currently doesn’t have the API extension for the USB port. There is only a partial Windows implementation of the usb.core for Java to communicate with the USB port. Initially the design of the Dispatcher System was to use the USB port to communicate with the XBee; soon after, we found out that the API extension of the USB was abandoned. When the USB API extension is completed, the Dispatcher System can be written for the USB port to communicate with XBee. Since, most laptops nowadays do not come with a RS-232 port.
Figure 12.0: Request Table Screen Shot
4.1.7 Future Developments
The main dispatcher system software may have a few areas to improve on in the future. The current system allows anyone to view and modify the database. Adding a user profiles with password will improve the overall security of the system. As for eccentric feature, colour code different request status, request type, or waiter id would make the request table easier to read. In the future, it would be efficient to join this main dispatcher software to the existing ordering software that restaurants use today to increase the productivity.
5.0 TESTING PHASE
5.1 TRANSMITTER
The Transmitter circuit was extensively tested to ensure that component requirements are met and usage is within specification. Current draw and voltage drop was measured for every component to determine power consumption and make certain that sufficient resources are available for proper functionality. Overall current draw was also used to help determine the battery life of the Transmitter.

**Figure 13.0**: UART Transmission
To test the output of the microcontroller, its transmissions were extended to 2 seconds each so that it may be more easily viewed on the oscilloscope. The output of the microcontroller was first predicted and probed to verify the predictions.
Lastly, to properly capture a change of state, a denouncer must be implemented. This component as implemented through the microcontroller. In order to determine the sampling interval for the denouncer, a switch was connected to the oscilloscope and repeatedly turned on and off to measure the bouncing. The test was performed fifty times and the worst case time was used in the program.
5.2 RECEIVER
Our group uses CircuitMaker2000 to simulate the voltage and current flowing through each component (See Fig 14.0 below). As a result, our team is able to debug our PCB design more easily.
Figure 15.0: CircuitMaker2000 Schematics and Testing Waveforms for the Receiver Unit Power Circuit
The next thing in the testing list is the LCD module, because the hardware won’t work unless the software portion works properly. By some simple AVR Studio programming, a quick simulation can be achieved using the Hapsim Simulator. However, during this phase, our group has discovered that the LCD does not have a clock source. As a result, an external clock is needed to drive the LCD. CodeVisionAVR would require the users to install an additional crystal oscillator for Atmega16, but on the other hand, AVR studio can set the internal clock of the chip.
Figure 16.0: Hapsim Simulation of the LCD Display using AVR Studio
5.3 MAIN DISPATCHER
This part of the testing phase is done on GUI software. Thus, the software program must be loaded and running.
5.3.1 The Initial State
After GUI has been loaded and running, it was verified that all text fields in the program are cleared. Waiter Id Combo Box on the tables tab and Waiter Id Combo Box on the request table were also empty, since these two combo boxes are retrieving data from waiters table and no data has yet been stored in the waiters table. The Status Combo Box on request tab should show “Pending” and “Done,” Request Type Combo Box should show “General” and “Bill,” and Management Combo Box should show “Yes” and “No.”
5.3.2 Tables and Waiter Tabs
First, some data must be entered and stored in the waiters table. Fill in all the text fields and click on Save. The new entry was shown on the waiters table. Select the entry that was just entered and click on Delete. The selected entry disappeared from the table. Add more entries into the table accordingly. To test the New button, select any entry from the table and click on New. All information that was originally in the text fields should now be cleared. Then, select a pre-existing entry, make changes in the text fields and click on Save. The entry was modified and no new entry is being added to the table. The main
dispatcher system is programmed so that waiter id and table id are unique. Therefore, the program will not allow duplicate waiter ids and table ids. Once there are multiple entries in the waiter table, check if the Waiter ID Combo Boxes in other tabs reflects the changes. For instance, there were initially five waiters in the waiters table, the Waiter ID Combo Boxes should have five entries, after deleting an entry in the waiters table, Waiter ID Combo Boxes should now have only four entries. It was verified that all these functionalities work in our dispatcher program.
5.3.3 Request Tabs
To test the request table properly without any incoming signal from an external source, the “receive” method is called in the main function with inputs. Load the program again, so that there are some entries already in the request table. Each filtering methods are tested and changes are reflected in the request table. The Show All button worked as expected in showing all entries in the request table. Delete button functionality was tested in the same manner as other delete buttons in other tabs. The delete confirmation dialogue box popped onto the screen as expected before data gets deleted from the table.
5.3.4 Testing Request Status
A button was added to the request tab. When clicking on this button, program will call the “receive” method again with a table id and a request complete signal that already exists in the request table. The purpose of this step is to
verify that the program calculates the time that a waiter/waitress takes to complete the task, also change the status of the request from pending to done. It was tested and verified these two functionalities worked properly.
5.3.5 Serial Port
To test if the XBee can communicate with Java, a simple program was written to open a serial port and read/write on to the port. With the help of this simple program it shows that XBee and Java can communicate with each other.
6.0 CONCLUSION
The purpose of the wireless restaurant management system is to improve worker efficiency and to maximize profit margin of restaurant owners by providing better service. Providing prompt response to customers through use of a Transmitter and data collection by the Main Dispatcher will allow this to happen. This project proved to be a larger task than expected due to lack of manpower and late arriving parts. Certain functionality also had to be abandoned to meet time constraints. The System is not designed to replace the existing ordering systems which are at many restaurants but to complement it. Once the Restaurant Management System becomes further refined with the ideas discussed in the previous section, it will pose to be an indispensable tool.
## APPENDIX A: BUDGET
<table>
<thead>
<tr>
<th>PART</th>
<th>QTY</th>
<th>UNIT PRICE</th>
<th>COST</th>
</tr>
</thead>
<tbody>
<tr>
<td>MAXSTREAM XBee Starter Kit</td>
<td>1</td>
<td>129 USD</td>
<td>129</td>
</tr>
<tr>
<td>XBee Transceiver</td>
<td>2</td>
<td>19 USD</td>
<td>38</td>
</tr>
<tr>
<td>XBee-PRO Transceiver</td>
<td>1</td>
<td>32 USD</td>
<td>32</td>
</tr>
<tr>
<td><strong>Subtotal</strong></td>
<td></td>
<td></td>
<td><strong>199</strong></td>
</tr>
<tr>
<td>Educational Discount</td>
<td>0.25</td>
<td></td>
<td>-49.75</td>
</tr>
<tr>
<td><strong>Total (USD)</strong></td>
<td></td>
<td></td>
<td><strong>149.25</strong></td>
</tr>
<tr>
<td>Exchange Rate</td>
<td></td>
<td></td>
<td>1.1</td>
</tr>
<tr>
<td><strong>Total (CDN)</strong></td>
<td></td>
<td></td>
<td><strong>164.175</strong></td>
</tr>
<tr>
<td>Microcontroller</td>
<td>3</td>
<td>7.93 CDN</td>
<td>23.79</td>
</tr>
<tr>
<td>LCD</td>
<td>1</td>
<td>15.58 CDN</td>
<td>15.58</td>
</tr>
<tr>
<td>Rocker Switch</td>
<td>4</td>
<td>3.09 CDN</td>
<td>12.36</td>
</tr>
<tr>
<td>PCB</td>
<td>1</td>
<td>50 CDN</td>
<td>0 *</td>
</tr>
<tr>
<td>Transmitter Case</td>
<td>1</td>
<td>25 CDN</td>
<td>25</td>
</tr>
<tr>
<td>Receiver Case</td>
<td>2</td>
<td>7.5 CDN</td>
<td>15</td>
</tr>
<tr>
<td>Misc. Components (ie Headers, Resistors, Capacitors, LEDs, etc.)</td>
<td></td>
<td></td>
<td>50</td>
</tr>
<tr>
<td><strong>TOTAL BUDGET</strong></td>
<td></td>
<td>CDN</td>
<td><strong>305.905</strong></td>
</tr>
<tr>
<td>Residual</td>
<td></td>
<td>CDN</td>
<td><strong>94.095</strong></td>
</tr>
</tbody>
</table>
* - After $50 discount. Actual Cost = $47.04
Prices do not include taxes and shipping
|
{"Source-Url": "http://mina.ubc.ca/files/474/su2006/Team%201%20-%20Final%20Report.pdf", "len_cl100k_base": 12087, "olmocr-version": "0.1.50", "pdf-total-pages": 56, "total-fallback-pages": 0, "total-input-tokens": 89269, "total-output-tokens": 13756, "length": "2e13", "weborganizer": {"__label__adult": 0.00228118896484375, "__label__art_design": 0.00353240966796875, "__label__crime_law": 0.0013685226440429688, "__label__education_jobs": 0.0106201171875, "__label__entertainment": 0.0003333091735839844, "__label__fashion_beauty": 0.000759124755859375, "__label__finance_business": 0.00644683837890625, "__label__food_dining": 0.01690673828125, "__label__games": 0.0034160614013671875, "__label__hardware": 0.1318359375, "__label__health": 0.0025386810302734375, "__label__history": 0.001575469970703125, "__label__home_hobbies": 0.0018739700317382812, "__label__industrial": 0.0162200927734375, "__label__literature": 0.0008668899536132812, "__label__politics": 0.0006971359252929688, "__label__religion": 0.0015773773193359375, "__label__science_tech": 0.1546630859375, "__label__social_life": 0.00024235248565673828, "__label__software": 0.01666259765625, "__label__software_dev": 0.61572265625, "__label__sports_fitness": 0.0007343292236328125, "__label__transportation": 0.00836944580078125, "__label__travel": 0.0009245872497558594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55288, 0.04317]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55288, 0.268]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55288, 0.88106]], "google_gemma-3-12b-it_contains_pii": [[0, 174, false], [174, 352, null], [352, 1175, null], [1175, 5482, null], [5482, 5482, null], [5482, 7284, null], [7284, 7744, null], [7744, 9347, null], [9347, 10791, null], [10791, 12429, null], [12429, 13795, null], [13795, 15127, null], [15127, 15857, null], [15857, 16070, null], [16070, 16386, null], [16386, 17094, null], [17094, 18256, null], [18256, 19337, null], [19337, 20362, null], [20362, 21683, null], [21683, 23188, null], [23188, 24733, null], [24733, 26056, null], [26056, 27257, null], [27257, 28141, null], [28141, 28437, null], [28437, 29246, null], [29246, 30246, null], [30246, 31436, null], [31436, 32616, null], [32616, 33889, null], [33889, 34878, null], [34878, 35808, null], [35808, 36996, null], [36996, 37631, null], [37631, 39028, null], [39028, 40380, null], [40380, 41211, null], [41211, 42183, null], [42183, 43391, null], [43391, 44092, null], [44092, 44192, null], [44192, 45461, null], [45461, 46659, null], [46659, 46698, null], [46698, 47356, null], [47356, 47923, null], [47923, 48663, null], [48663, 49253, null], [49253, 49352, null], [49352, 49977, null], [49977, 51298, null], [51298, 52774, null], [52774, 53246, null], [53246, 54019, null], [54019, 55288, null]], "google_gemma-3-12b-it_is_public_document": [[0, 174, true], [174, 352, null], [352, 1175, null], [1175, 5482, null], [5482, 5482, null], [5482, 7284, null], [7284, 7744, null], [7744, 9347, null], [9347, 10791, null], [10791, 12429, null], [12429, 13795, null], [13795, 15127, null], [15127, 15857, null], [15857, 16070, null], [16070, 16386, null], [16386, 17094, null], [17094, 18256, null], [18256, 19337, null], [19337, 20362, null], [20362, 21683, null], [21683, 23188, null], [23188, 24733, null], [24733, 26056, null], [26056, 27257, null], [27257, 28141, null], [28141, 28437, null], [28437, 29246, null], [29246, 30246, null], [30246, 31436, null], [31436, 32616, null], [32616, 33889, null], [33889, 34878, null], [34878, 35808, null], [35808, 36996, null], [36996, 37631, null], [37631, 39028, null], [39028, 40380, null], [40380, 41211, null], [41211, 42183, null], [42183, 43391, null], [43391, 44092, null], [44092, 44192, null], [44192, 45461, null], [45461, 46659, null], [46659, 46698, null], [46698, 47356, null], [47356, 47923, null], [47923, 48663, null], [48663, 49253, null], [49253, 49352, null], [49352, 49977, null], [49977, 51298, null], [51298, 52774, null], [52774, 53246, null], [53246, 54019, null], [54019, 55288, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55288, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55288, null]], "pdf_page_numbers": [[0, 174, 1], [174, 352, 2], [352, 1175, 3], [1175, 5482, 4], [5482, 5482, 5], [5482, 7284, 6], [7284, 7744, 7], [7744, 9347, 8], [9347, 10791, 9], [10791, 12429, 10], [12429, 13795, 11], [13795, 15127, 12], [15127, 15857, 13], [15857, 16070, 14], [16070, 16386, 15], [16386, 17094, 16], [17094, 18256, 17], [18256, 19337, 18], [19337, 20362, 19], [20362, 21683, 20], [21683, 23188, 21], [23188, 24733, 22], [24733, 26056, 23], [26056, 27257, 24], [27257, 28141, 25], [28141, 28437, 26], [28437, 29246, 27], [29246, 30246, 28], [30246, 31436, 29], [31436, 32616, 30], [32616, 33889, 31], [33889, 34878, 32], [34878, 35808, 33], [35808, 36996, 34], [36996, 37631, 35], [37631, 39028, 36], [39028, 40380, 37], [40380, 41211, 38], [41211, 42183, 39], [42183, 43391, 40], [43391, 44092, 41], [44092, 44192, 42], [44192, 45461, 43], [45461, 46659, 44], [46659, 46698, 45], [46698, 47356, 46], [47356, 47923, 47], [47923, 48663, 48], [48663, 49253, 49], [49253, 49352, 50], [49352, 49977, 51], [49977, 51298, 52], [51298, 52774, 53], [52774, 53246, 54], [53246, 54019, 55], [54019, 55288, 56]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55288, 0.10233]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
be13a38790993f40a690ce11810e391a6f3b94dd
|
On Fair Relational Conjunction∗
PETR LOZOV, Saint Petersburg State University, Russia and JetBrains Research, Russia
DMITRY BOULYTCHEV, Saint Petersburg State University, Russia and JetBrains Research, Russia
We present a new, more symmetric evaluation strategy for conjunctions in miniKanren. Unlike the original unfair directed conjunction, our approach controls the order of conjunct execution based on the properties of structurally recursive relations. In this paper we describe operational semantics for both “classical” and “fair” conjunctions. We also compare the performance of classical and fair conjunctions on a number of examples and discuss the results of the evaluation.
CCS Concepts: • Software and its engineering → Constraint and logic languages; Semantics;
Additional Key Words and Phrases: relational programming, miniKanren, evaluation strategies, operational semantics
1 INTRODUCTION
miniKanren [7, 8] is known for its capability to express solutions for complex problems [4, 6, 11] in the form of compact declarative specifications. This minimalistic language has various extensions [1, 3, 5, 14] designed to increase its expressiveness and declarativeness. However, conjunction in miniKanren has somewhat imperative flavor. The evaluation of conjunction is asymmetrical and the order of conjuncts affects not only the performance of the program but even the convergence. As a result, the order of conjuncts determines control flow in a relational program. We may call this directed behavior of conjunction unfair.
The problem of unfair behavior of conjunction has already been examined from several different points of view. One aspect of the unfair behavior of conjunction is to prioritize the evaluation of the independent branches which conjunction generates. In the original miniKanren a higher priority is given to an earlier branch. However, there is an approach [10] which allows one to balance the evaluation time of different branches. This makes the conjunction behavior fairer, but the order of the conjuncts still affects both performance and convergence. Also, the conjunction can be made fairer if we are capable of detecting the divergence in its conjuncts. The approach [12] detects the divergence at run time and performs switching of conjuncts. In this case, the data that was received during the evaluation of the diverging conjunct is erased. The approach turned out to be efficient in practice. However, the conservative rearrangement of the conjuncts does not use the information obtained when evaluating the conjunct before the rearrangement. There are also examples for this approach where the order of the conjuncts affects convergence.
The contribution of this paper is a more declarative approach to the evaluation of relational programs of miniKanren. This approach executes the conjuncts alternately, choosing a more optimal execution order. The fair conjunction that we propose is comparable in efficiency to the classic unfair one, but the order of the conjuncts weakly affects both efficiency and convergence. Our approach also demonstrates a more convergent behavior: we
∗The reported study was funded by RFBR, project number 19-31-90053
Authors’ addresses: Petr Lozov, lozov.peter@gmail.com, Saint Petersburg State University, Russia, JetBrains Research, Russia; Dmitry Boulytchev, dboulytchev@math.spbu.ru, Saint Petersburg State University, Russia, JetBrains Research, Russia.
This work is licensed under a Creative Commons “Attribution-ShareAlike 4.0 International” license.
© 2020 Copyright held by the author(s).
miniKanren.org/workshop/2021/8-ART1
present some examples where classical conjunction diverges for any order of conjuncts while the fair conjunction converges.
The paper is organized as follows. In Section 2 we discuss the advantages and drawbacks of the classical directed conjunction. Section 3 contains a description of miniKanren syntax as well as operational semantics based on the unfolding operation. In Section 4 we present the semantics of a naive fair conjunction, and in Section 5 we extend these semantics by controlling the conjunction order based on structural recursion. Section 6 is devoted to the evaluation and performance comparison on different semantics in the form of interpreters. The final section concludes.
2 DIRECTED CONJUNCTION
In this section we consider the classic directed conjunction in the original miniKanren and demonstrate its advantages and drawbacks on examples.
In miniKanren there is a significant difference between disjunction and conjunction evaluation strategy. The arguments of disjunction are evaluated in an interleaving manner, switching elementary evaluation steps between disjuncts, which provides the completeness of the search. Conjunction, on the other hand, waits for the answers from the first conjunct and then calculates the second conjunct in the context of each answer.
On the one hand, this strategy is easy to implement and allows one to explicitly specify the order of evaluation when this order is essential. On the other hand, the strategy amounts to non-commutativity: the convergence of a conjunction can depend on the order of its arguments. For example, the relation
\[
\text{let rec } \text{freeze}^o x = x \equiv \text{true} \land \text{freeze}^o x
\]
either converges in one recursion step or diverges. The conjunction \((x \equiv \text{false} \land \text{freeze}^o x)\) converges, but the same conjunction with the reverse order of conjuncts \((\text{freeze}^o x \land x \equiv \text{false})\) diverges. Indeed, in the first case the first conjunct produces exactly one answer which contradicts the unification in the body of \(\text{freeze}^o\). In the second case the relation \(\text{freeze}^o\) diverges and does not produce any answer. As a result we will never begin to evaluate the second conjunct.
The problem in this particular example can be alleviated by using a conventional rule for miniKanren, which says that unifications must be moved first in a cluster of conjunctions. But the rule does not work for clusters with more than one relational call. Consider, for instance, the relation \(\text{revers}^o\) (Fig. 1), which associates an arbitrary list with the list containing the same elements in reverse order. In this relation we can see a couple of conjuncts: \(\text{revers}^o\) on line 11 and \(\text{append}^o\) on line 12. With this particular order, the call \((\text{revers}^o [1, 2, 3] q)\) converges, but in reverse order it diverges after an answer is found. Moreover, the reverse order negatively affects the performance of the answer evaluation.
At the same time the call \((\text{revers}^o q [1, 2, 3])\) for a given order of conjuncts diverges, and for the reverse order it converges. As a result a different order of conjuncts is desirable depending on their runtime values.
In the following sections we describe an approach for automatically determining a "good" order during program evaluation.
3 THE SEMANTICS OF DIRECTED CONJUNCTION
In this section we introduce a small-step operational semantics to define the behavior of the original miniKanren with directed conjunction.
Note, although at the moment there exists a certified semantics [13] of miniKanren, however, it makes a distinction between the first and the second conjuncts, which greatly complicates the task of rearranging the conjuncts in the process of program evaluation. Therefore, for this research, we have developed a new semantics that does not distinguish between conjuncts from the start.
The semantics which we propose are based on unfolding of relational calls. At each step we select a call from the current state of the program and unfold it. This process continues until no calls remain in the state. If at some step the state becomes empty then the evaluation converges. Otherwise, the evaluation diverges. Below we define these semantics formally.
\[
\begin{align*}
C &= \{c_{1}^{k_{1}}, c_{2}^{k_{2}}, \ldots \} \quad \text{constructors with arities} \\
X &= \{x_{1}, x_{2}, \ldots \} \quad \text{syntax variables} \\
A &= \{a_{1}, a_{2}, \ldots \} \quad \text{semantic variables} \\
T_{X} &= X \mid C_{i}^{k_{i}}(T_{X_{1}}^{k_{i}}, \ldots, T_{X_{n}}^{k_{i}}) \quad \text{syntax terms} \\
T_{A} &= A \mid C_{i}^{k_{i}}(T_{A_{1}}^{k_{i}}, \ldots, T_{A_{n}}^{k_{i}}) \quad \text{semantic terms} \\
F &= \{f_{1}^{k_{1}}, f_{2}^{k_{2}}, \ldots \} \quad \text{names of relations with arities} \\
G &= T_{X} \equiv T_{X} \quad \text{unification} \\
| G \lor G \quad \text{disjunction} \\
| G \land G \quad \text{conjunction} \\
| \text{fresh } (X) G \quad \text{fresh variable introduction} \\
| f_{i}^{k_{i}}(T_{X_{1}}^{k_{i}}, \ldots, T_{X_{n}}^{k_{i}}) \quad \text{relation call} \\
S &= f_{i}^{k_{i}}(X_{1}, \ldots, X_{n}, G) \quad \text{relations}
\end{align*}
\]
Fig. 2. The syntax of relational language
First, we define the syntax of the language (Fig. 2). We define the set of syntax terms \(T_{X}\) and the set of semantic terms \(T_{A}\) using constructors \(C\), syntactic variables \(X\) and semantic variables \(A\). Syntactic variables \(X\) are needed to introduce relation arguments and fresh variables. Semantic variables \(A\) can not occur in the source program, but they are introduced during the evaluation of the fresh construct.
Also we define the set \(F\) of relation names with arities. Next, we describe the set of goals \(G\). A goal is either a unification of terms, or a disjunction, conjunction, introduction of fresh variable, or a call of a relation. Finally, we define the set of relations \(S\). Each relation consists of a name with arity, a list of argument names, and a goal as its body.
In addition to syntax, we define an intermediate state of relational program.
\[
\begin{align*}
&c_{i} = f_{i}^{k_{i}}(t_{A_{1}}^{k_{i}}, \ldots, t_{A_{n}}^{k_{i}}) \quad \text{calls} \\
&C = c_{1} \land \ldots \land c_{n} \quad \text{conjunction of calls} \\
&T = T \lor T \quad \text{disjunction state} \\
| (\sigma; i; C) \quad \text{leaf state}
\end{align*}
\]
The state has a shape of a disjunction tree. An internal node \( \lor \) corresponds to the disjunction of two descendant states. Its leaves contain intermediate substitutions \( \sigma \), a counter of semantic variables \( i \) and a conjunction of calls \( C \). A substitution \( \sigma \) is a mapping from semantic variables to semantic terms. The counter of semantic variables is necessary to evaluate the fresh construct, which introduces a semantic variable with a new counter. The conjunction of calls contains calls \( c_i \) which must be evaluated in this branch. The number of conjuncts in a conjunction may be zero, which we denote as \( \varepsilon \).
We expand the set of states with an empty state \( \mathcal{T}^+ = \emptyset \).
Also we introduce two auxiliary functions for working with the program state. The first one, \( \text{union} \), combines two extended states:
\[
\text{union} (T_1, T_2) = \begin{cases}
T_2, & \text{if } T_1 = \emptyset \\
T_1, & \text{if } T_1 \neq \emptyset \text{ and } T_2 = \emptyset \\
T_1 \lor T_2, & \text{otherwise}
\end{cases}
\]
If one of the states is empty \( \text{union} \) returns another state. If both states are not empty then the function returns the combined state.
The next auxiliary function, \( \text{push} \), is needed to construct the state after the unfolding:
\[
\text{push} (C, T) = \begin{cases}
\emptyset, & \text{if } T = \emptyset \\
\langle \sigma; i; C_1 \land \check{C} \land C_2 \rangle, & \text{if } T = \langle \sigma; i; \check{C} \rangle \text{ and } C = C_1 \land \square \land C_2 \\
\text{push} (C, T_1) \lor \text{push} (C, T_2), & \text{if } T = T_1 \lor T_2
\end{cases}
\]
The first argument of this function is a conjunction of calls which contains a hole \( \square \). The hole corresponds to a position of the call which we are unfolding. The second argument is the state to unfold. This function recursively traverses the state and for any leaf replaces its calls, making a substitution of this leaf calls into the hole in the first argument of \( \text{push} \).
Now we define the semantics for the unfolding operation. This semantics (Fig. 3) evaluates a call of a relation and a substitution into a state which corresponds to the body of this relation. Since unfolding is a finite process we can describe it in a big-step style, defining a relation \( \Rightarrow \).
The top-level rule in [Unfold]. Thus, this is the only rule which infers \( \Rightarrow \). It starts the unfolding process of call \( F \) with the list of arguments \( \bar{t} \) in the context of substitution \( \sigma \) and counter of semantic variables \( i \). First of all, the call \( F \) is replaced by the body \( b \) of the relation. Also the arguments \( \bar{x} \) are substituted by terms \( \bar{t} \) and the state \( \langle \sigma; i; \varepsilon \rangle \) is initialized. Next, we evaluate the relation body into the corresponding state using the rest of the rules.
The rule [EmptyState] handles the empty state case. The rules [UnifyFail] and [UnifySuccess] perform unification. If the most general unifier (MGU) exists, then we apply rule [UnifySuccess], which updates the substitution \( \sigma \). If the MGU does not exist, then we apply rule [UnifyFail], which leads to the empty state.
Since this semantics should unfold a call exactly once, we leave all the nested calls unchanged. This behavior is specified by rule [Call]. The nested call is not evaluated, but added to the conjunction, which is contained in the state.
The rule [Fresh] corresponds to the introduction of a fresh variable. In this rule we replace a syntax variable \( x \) with a semantic variable \( q_i \). We also increment the counter of semantic variables.
The rules [DisjGoal] and [DisjState] are required to evaluate disjunctions. The first rule evaluates both disjuncts and combines them into a new state using auxiliary function \( \text{union} \). The second rule handles a disjunction
\[
\begin{align*}
F = \lambda \overline{x}. b & \quad (\sigma; i; e) \vdash b[\overline{x} \leftarrow i] \leadsto T \quad \text{[Unfold]} \\
\emptyset \vdash g \leadsto \emptyset & \quad \text{[EmptyState]} \\
\exists \text{mgu}(t_1, t_2, \sigma) & \quad \langle \sigma; i; C \rangle \vdash (t_1 \equiv t_2) \leadsto \emptyset \quad \text{[UnifyFail]} \\
\hat{\sigma} = \text{mgu}(t_1, t_2, \sigma) & \quad \langle \sigma; i; C \rangle \vdash (t_1 \equiv t_2) \leadsto \langle \hat{\sigma}; i; C \rangle \quad \text{[UnifySuccess]} \\
\langle \sigma; i; C \rangle \vdash F(i) \leadsto \langle \sigma; i; F(i) \wedge C \rangle & \quad \text{[Call]} \\
\langle \sigma; i; C \rangle \vdash g[x \leftarrow a_i] \leadsto T & \quad \langle \sigma; i; C \rangle \vdash \text{fresh } x. g \leadsto T \quad \text{[Fresh]} \\
\langle \sigma; i; C \rangle \vdash g_1 \leadsto T_1 & \quad \langle \sigma; i; C \rangle \vdash g_2 \leadsto T_2 \quad \text{[DisjGoal]} \\
\langle \sigma; i; C \rangle \vdash g_1 \vee g_2 \leadsto \text{union}(T_1, T_2) & \\
g \neq g_1 \vee g_2 & \quad T_1 \vdash g \leadsto T_3 \quad T_2 \vdash g \leadsto T_4 \quad \text{[DisjState]} \\
T_1 \vee T_2 \vdash g \leadsto \text{union}(T_1, T_4) & \\
\langle \sigma; i; C \rangle \vdash g_1 \leadsto T & \quad T \vdash g_2 \leadsto \tilde{T} \quad \text{[Conj]} \\
\end{align*}
\]
Fig. 3. Big step semantics of unfolding
which is contained in the state. As in the previous rule we perform two independent evaluations and then combine the results into a new state.
The last rule [Conj] describes the evaluation of conjunction. In this case we evaluate the first conjunct into a state \(T_1\), and then evaluate the second conjunct in the context of \(T_1\). Thus, the second conjunct will be evaluated in the context of all leaves of the state \(T_1\). Note, if the first conjunct is evaluated into empty state then we can only apply the rule [EmptySet] to the second conjunct. Applying this rule will result in an empty state.
Now we have everything we need to define the semantics of a relational language with directed conjunction (Fig. 4). This small-step semantics sequentially evaluates a state and periodically produces answer substitutions. If an answer is found during program evaluation it is indicated above the transition symbol "\(\rightarrow\)"; otherwise, "\(\circ\)" is indicated.
If the current state is a leaf and does not contain any calls then we have an answer in the form of a substitution. In this case, we apply the rule [Answer].
Also, if the current state is a leaf but contains at least one call, we apply rule [ConjUnfold]. In this case we unfold the leftmost call \(c\). Then we construct a new state from the remaining calls \(C\) and the unfolding result \(T\) using the function \(\text{push}\).
Finally, if the current state is a disjunction then we evaluate the left disjunct \(T_1\). We apply either rule [Disj] or rule [DisjStep] depending on the results of the evaluation for the left disjunct. The first rule corresponds to the empty state and returns the second disjunct \(T_2\) as a result. The second rule corresponds to a non-empty state and returns a new state \((T_2 \vee \tilde{T}_1)\). Rearrangement of disjuncts is a necessary action called \(\text{interleaving}\) [9]. It guarantees the completeness of the search.
To make initial state from a call \(c\) we need to replace all its syntactic variables with semantic ones:
\[ \langle \sigma; i; e \rangle \xrightarrow{\sigma} \emptyset \] [Answer]
\[ (\sigma, i) \vdash c \Rightarrow T \] [CONJUNFOLD]
\[ \langle \sigma; i; c \land C \rangle \xrightarrow{\sigma} \text{push}(\Box \land C, T) \]
\[ T_1 \xrightarrow{\sigma} \emptyset \] [DISJ]
\[ T_1 \lor T_2 \xrightarrow{\sigma} T_2 \]
\[ T_1 \xrightarrow{\sigma} \bar{T}_1 \quad \bar{T}_1 \neq \emptyset \] [DISJSTEP]
\[ T_1 \lor T_2 \xrightarrow{\sigma} T_2 \lor \emptyset \]
Fig. 4. Semantics with directed conjunction
\[ \{ \}; n; c[x_0 \leftarrow a_0, \ldots, x_{n-1} \leftarrow a_{n-1}] \].
This semantics differs from certified semantics and classical implementations primarily in step size. The unfolding operation performs many actions in a row. But in the classical case interleaving is performed after each elementary action. However, the semantics we presented has retained some common features: disjuncts are switched after each step, and conjunctions are evaluated strictly from left to right.
The order of conjuncts strongly affects the results of the evaluation precisely because of the strictly fixed order of evaluation of the conjuncts. In the following sections we propose two semantics that handles conjunctions more flexibly.
4 A NAIVE FAIR CONJUNCTION
In this section we consider the semantics of miniKanren which fairly unfolds conjuncts. Also, we discuss their advantages and drawbacks.
Instead of unfolding the leftmost call to completion we take some finite number \( N \) and bound the number of unfolding steps by \( N \). If after \( N \) unfoldings the leftmost call is not eliminated we start to unfold the next call. This process will continue for all calls of the leaf state. When all calls are unfolded \( N \) times, we again return the leftmost once again. We call \( N \) unfolding bound.
To implement this behavior, we need to modify the state structure.
\[
\begin{align*}
c_i & = \mathcal{F}_{k_i}^{k_i} (t_{1_i}^{k_i}, \ldots, t_{n_i}^{k_i}) \quad \text{calls} \\
C & = c_1^{m_1} \land \cdots \land c_n^{m_n} \quad \text{conjunction of marked calls} \\
\mathcal{T} & = \mathcal{T} \lor \mathcal{T} \quad \text{disjunction state} \\
| & \langle \sigma; i; C \rangle \quad \text{leaf state}
\end{align*}
\]
For each call \( c_i \) of the leaf we add a natural number \( m_i \) which specifies the remaining number of unfoldings. Therefore, each call in the state is marked with an unfolding counter.
Note that the syntax, auxiliary function union, the semantics of unfolding are all remained unchanged. The function push also preserves its behavior, but now it takes a conjunction of marked calls with the hole and a state in a new form. In addition we need yet another function set, which takes an old state without counters in the leaves and a natural number. This number is attached to each call in the state:
On Fair Relational Conjunction
\[
\text{set}(T, m) = \begin{cases}
\varnothing, & \text{if } T = \varnothing \\
\langle \sigma; i; c_1^m \land \ldots \land c_n^m \rangle, & \text{if } T = \langle \sigma; i; c_1 \land \ldots \land c_n \rangle \\
\text{set}(T_1, m) \lor \text{set}(T_2, m), & \text{if } T = T_1 \lor T_2
\end{cases}
\]
Now we are ready to modify the semantics. A new semantics (Fig. 5) evaluates disjuncts in the old way, but it unfolds conjuncts fairly.
\[
\langle \sigma; i; e \rangle \xrightarrow{\sigma} \varnothing \\
\langle \sigma; i; c_1^0 \land \ldots \land c_n^0 \rangle \xrightarrow{\sigma} \langle \sigma, i; c_1^N \land \ldots \land c_n^N \rangle \\
\begin{array}{l}
m > 0 \\
\end{array} \quad (\sigma, i) + c_k \Rightarrow T \quad \text{set}(T, m - 1) = \hat{T} \\
\begin{array}{l}
\langle \sigma; i; c_1^0 \land \ldots \land c_{k-1}^0 \land c_k^M \land C \rangle \xrightarrow{\sigma} \text{push}(c_1^0 \land \ldots \land c_{k-1}^0 \land \square \land C, \hat{T}) \\
T_1 \xrightarrow{\sigma} \varnothing \\
T_1 \lor T_2 \xrightarrow{\sigma} T_2 \\
T_1 \xrightarrow{\sigma} \hat{T}_1 \quad \hat{T}_1 \neq \varnothing \\
T_1 \lor T_2 \xrightarrow{\sigma} T_2 \lor \hat{T}_1
\end{array}
\]
Fig. 5. Simple fair semantics
First of all, we note that semantics depends on unfolding bound. If the bound is 1, then the evaluation of conjunctions becomes very similar to that for disjunctions. As in the case of disjunction, we switch to the unfolding of a next conjunct after each step. If the bound is set to infinity, then the conjunction will behave like in the directed case. Indeed, the counter of the leftmost conjunct will never become zero and this conjunct will unfold until completion.
Now we consider the semantics in more detail. The rules [Answer], [Disj] and [DisjStep] remain unchanged. However, we introduced two new rules for handling conjunctions. The rule [ConjUnfold] unfolds the leftmost conjunct \(c_k\) whose counter \(m\) is greater than zero. All calls in the new state \(T\), which we have after the unfolding, require to attach an updated counter; we do this using the function set. If all calls in the leaf have a zero counter, then we apply the rule [ConjZero]. This rule updates all counters in the leaf, setting them all to unfolding bound.
\[
\begin{array}{l}
\text{let rec repeat}_o e \ 1 = \\
\quad (1 \equiv []) \lor \\
\quad \text{fresh} \ (1) \\
\quad (1 \equiv e : 1) \land \\
\quad \text{repeat}_o e \ 1)
\end{array}
\]
\[
\begin{array}{l}
\text{let divergence}_o \ 1 = \\
\quad \text{repeat}_o \ C_1 \ 1 \land \\
\quad \text{repeat}_o \ C_2 \ 1
\end{array}
\]
Fig. 6. An example to demonstrate fair conjunction superiority
This semantics more fairly distributes resources between conjuncts. Because of this, relational queries converge more often. Let’s go back to the \texttt{reverse} example (Fig. 1). As we said earlier, for directed conjunction the query \texttt{(reverse \([1, 2, 3]\) q)} converges in the specified order of conjuncts and diverges in the reverse order. At the same time, the query \texttt{(reverse \([1, 2, 3]\) q)} diverges in the specified conjunct order but converges in the reverse order. In the case of fair conjunction, however, both queries converge in both conjunct orders for any finite unfolding bound.
Moreover, some examples diverge for any order of conjuncts in case of directed conjunction but converge in case of fair conjunction (see Fig. 6). The relation searches for lists which on the one hand contain terms \(C_1\) only, and on the other, contain terms \(C_2\) only. Obviously, only an empty list has this property.
We can find this answer by evaluating query divergence\(^1\) under directed conjunction. However, the search for other answers will diverge, and any order of conjuncts preserves this effect. At the same time fair conjunction converges for any finite unfolding bound and any order of conjuncts.
However, in practice this approach has an unstable performance. On the one hand, with a certain unfolding bound the efficiency of a fair conjunction is comparable to the directed conjunction with optimal order of conjunctions. On the other hand, with the wrong unfolding bound we can get an extremely inefficient evaluation, which is hundreds of times slower than the directed conjunction. Therefore, instead of choosing the unfolding bound once and for all we would like to determine it dynamically for each conjunct.
### 5 FAIR CONJUNCTION BY STRUCTURAL RECURSION
In this section we consider a generalized semantics of \textsc{miniKanren} with a fair conjunction which determines the unfolding bound dynamically. We also consider its specific implementation which makes use of structural recursion of relations.
In the general case we want to parameterize the semantics with an unfolding predicate \(\texttt{pred}\). This predicate takes a substitution and a call as arguments. It returns \texttt{true} if the call needs to be unfolded further, and \texttt{false}, if we need to move on to the next conjunct. We do not get rid of the unfolding bound completely since it is still needed to handle the case when \(\texttt{pred}\) is false for all calls in a leaf.
\[
\begin{align*}
\langle \sigma; i; e \rangle & \xrightarrow{\alpha} \emptyset \\
\bigvee_{j=1}^{n} \text{pred}(\sigma, c_j) &= \bot \\
m_k > 0 \quad \bigvee_{j=1}^{n} \text{pred}(\sigma, c_j) &= \bot \quad (\sigma, i) + c_k \Rightarrow T \quad \text{set}(T, m_k - 1) = \bar{T} \\
\bigvee_{j=1}^{k-1} \text{pred}(\sigma, c_j) &= \bot \quad \text{pred}(\sigma, c_k) = \top \quad (\sigma, i) + c_k \Rightarrow T \quad \text{set}(T, \max(0, m_k - 1)) = \bar{T} \\
\langle \sigma; i; c_1^m \land \ldots \land c_{k-1}^m \land c_k^m \land \ldots \land c_n^m \rangle & \xrightarrow{\alpha} \text{push}(c_1^m \land \ldots \land c_{k-1}^m \land \emptyset \land C_2, \bar{T}) \\
\frac{T_1 \alpha \Rightarrow \emptyset}{T_1 \lor T_2 \alpha \Rightarrow T_2} \\
\frac{T_1 \alpha \Rightarrow \bar{T}_1 \quad \bar{T}_1 \neq \emptyset}{T_1 \lor T_2 \alpha \Rightarrow T_2 \lor \bar{T}_1}
\end{align*}
\]
Fig. 7. Semantics of fair conjunction by structural recursion
The semantics parameterized by the unfolding predicate is shown in Fig. 7. Since we modify only the behavior of conjunction the rules [ANSWER], [DISJ] and [DISJSTEP] remain unchanged. Three updated rules are responsible for conjunction behavior. If the predicate \( \text{pred} \) is \( \top \) for at least one call, then we apply the rule [CONJUNFOLDPRED], which unfolds the leftmost such call and decrements its counter. If the predicate \( \text{pred} \) is \( \bot \) for all calls, but there is at least one call with a nonzero counter, then we apply the rule [CONJUNFOLD], which unfolds the leftmost such call and decrements its counter. If the predicate is \( \bot \) for all calls and all the counters are equal to zero, then we apply the rule [CONJZERO], which sets all the counters to unfolding bound.
As for the predicate, we need a criterion that can tell a call that is profitable to unfold now apart from a call which is worth deferring. We propose a criterion that works correctly for structurally recursive relations. Such relations have at least one argument which structurally decreases with each step of the recursion. This property allows us to control the depth of unfolding. We propose to use the following predicate:
\[
\text{pred}(\sigma, f^k(t_1, \ldots, t_k)) =
\begin{cases}
\top, & \text{if } f^k \text{ is structural recursion relation,} \\
\tau, & i \text{ is number of structural recursion argument,} \\
t_i \text{ is not fresh variable in } \sigma, & \\
\bot, & \text{otherwise.}
\end{cases}
\]
As long as at least one argument along which structural recursion is performed is not a free variable, we continue to unfold this call. If all such arguments are free, then the call will diverge in the current substitution, so we proceed to evaluate the next call. Since structurally recursive arguments decrease, in a finite number of steps the evaluation will either complete, or all arguments of structural recursion will become free variables.
\[
\text{let rec append}^o \ x \ y \ xy =
(x \equiv [] \land y \equiv xy) \lor
\text{fresh } (e \ x s \ xys) (
\quad x \equiv e : x s \land
\quad x s \equiv e : xys \land
\quad \text{append}^o \ x s \ y \ xys)
\]
Fig. 8. Relational concatenation
For example, the relation append\(^o\) (Fig. 8) is structurally recursive on its first and third arguments. Indeed, the nested call append\(^o\) takes \(x s\) as its first argument, which is a subterm of \(x\). Also, append\(^o\) takes \(x y s\) as the third argument, which is a subterm of \(xy\). If at least one of them is a fixed-length list, then the relation will converge. Otherwise, \(x \equiv t_1 : \ldots : t_n : \alpha_1\) and \(xy \equiv t_1 : \ldots : t_m : \alpha_2\). Therefore, in \(\max(n, m)\) steps, both arguments become free variables.
We are currently working on proving the independence of this semantics from the order of the conjuncts in the case when all relations are structurally recursive.
6 EVALUATION
In this section we present the results of the evaluation of three semantics on a set of examples; the semantics were implemented in Haskell in the form of interpreters. For evaluation we’ve chosen two simple programs (list reversing and list sorting) and three more complicated (the "Hanoi Towers"^1 solver, the "Bridge and torch
problem² solver and “Water pouring puzzle”³ solver). Each program was written in two versions: “optimistic” (with the order of important conjuncts set to provide the best performance) and “pessimistic” (with the order of important conjuncts set to provide the worst performance). Also we evaluated list reversing and list sorting in both directions. In the case of the list reversing, queries \((\text{revers}^o [1;2;3] \ q)\) and \((\text{revers}^o q [1;2;3])\) will give the same answer \(q = [3;2;1]\) but the “optimistic” order of conjuncts is different for them. In the case of list sorting, queries \((\text{sort}^o [1;2;3] \ q)\) and \((\text{sort}^o q [1;2;3])\) will give different answers. The first one gives sorted list \(q = [1;2;3]\), the second one gives all permutations of list \([1;2;3]\).
All benchmarks were run ten times, and the average time was taken. For the naive fair conjunction we cherry-picked the best value of unfolding bound manually. For the fair conjunction based on structural recursion the bound was set to 100.
Fig. 9-12 show the results of evaluation in the form of bar charts. In the optimistic case, the results are similar for all semantics. In the pessimistic case the evaluation time of the directed conjunction rapidly increases, the evaluation time of the naive fair conjunction also increases, but not so much. The fair conjunction based on structural recursion demonstrates a similar efficiency as in the optimistic case.
³https://en.wikipedia.org/wiki/Water_pouring_puzzle
The results are presented in more detail in Fig. 13. "Hanoi Towers" solver has name hanoi₀, "Bridge and torch problem" solver has name bridge₀ and "Water pouring puzzle" solver has name water₀. We can conclude that forward and backward sort₀ runtime in the pessimistic case increases very rapidly with increasing the list length for directed and naive fair conjunctions. In the case of the fair conjunction based on structural recursion the running time in pessimistic case increases on a par with that in the optimistic one. Also the solver water₀ very slow in the pessimistic case for directed and naive fair. However, fair conjunction based on structural recursion pessimistic case is no different from an optimistic case.
<table>
<thead>
<tr>
<th>relation</th>
<th>size</th>
<th>directed conjunction</th>
<th>naive fair conjunction</th>
<th>structural recursion</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>optimistic</td>
<td>pessimistic</td>
<td>optimistic</td>
</tr>
<tr>
<td>forward</td>
<td>30</td>
<td>0.465</td>
<td>0.532</td>
<td>0.468</td>
</tr>
<tr>
<td></td>
<td>60</td>
<td>0.579</td>
<td>0.828</td>
<td>0.577</td>
</tr>
<tr>
<td></td>
<td>90</td>
<td>1.142</td>
<td>2.073</td>
<td>1.151</td>
</tr>
<tr>
<td>revers₀</td>
<td>30</td>
<td>0.541</td>
<td>0.573</td>
<td>0.550</td>
</tr>
<tr>
<td></td>
<td>60</td>
<td>0.637</td>
<td>0.867</td>
<td>0.642</td>
</tr>
<tr>
<td></td>
<td>90</td>
<td>1.268</td>
<td>1.778</td>
<td>1.274</td>
</tr>
<tr>
<td>backward</td>
<td>3</td>
<td>0.418</td>
<td>0.432</td>
<td>0.420</td>
</tr>
<tr>
<td></td>
<td>4</td>
<td>0.424</td>
<td>3.924</td>
<td>0.424</td>
</tr>
<tr>
<td></td>
<td>5</td>
<td>0.430</td>
<td>>300</td>
<td>0.428</td>
</tr>
<tr>
<td></td>
<td>6</td>
<td>0.434</td>
<td>>300</td>
<td>0.430</td>
</tr>
<tr>
<td>sort₀</td>
<td>30</td>
<td>1.664</td>
<td>>300</td>
<td>1.636</td>
</tr>
<tr>
<td>backward</td>
<td>3</td>
<td>0.511</td>
<td>0.511</td>
<td>0.509</td>
</tr>
<tr>
<td></td>
<td>4</td>
<td>0.525</td>
<td>0.823</td>
<td>0.534</td>
</tr>
<tr>
<td></td>
<td>5</td>
<td>0.667</td>
<td>69.725</td>
<td>0.692</td>
</tr>
<tr>
<td></td>
<td>6</td>
<td>2.880</td>
<td>>300</td>
<td>2.891</td>
</tr>
<tr>
<td>sort₀</td>
<td>-</td>
<td>1.574</td>
<td>>300</td>
<td>1.579</td>
</tr>
<tr>
<td>hanoi₀</td>
<td>-</td>
<td>0.669</td>
<td>4.956</td>
<td>0.663</td>
</tr>
<tr>
<td>bridge₀</td>
<td>-</td>
<td>3.132</td>
<td>>300</td>
<td>3.168</td>
</tr>
<tr>
<td>water₀</td>
<td>-</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Fig. 13. The results of evaluation: running times of benchmarks in seconds
To summarize, the fair conjunction based on structural recursion does not introduce any essential overhead in comparison with directed conjunction in an optimistic case. At the same time it weakly depends on the order of the conjuncts, and thus demonstrates much better performance in the pessimistic case.
7 CONCLUSION
In this paper we proposed a new approach for the execution of relational programs with structural recursion. This approach reduces the performance impact of conjunct order.
In the future we plan to generalize the proposed approach to a larger class of programs. We also plan to formalize our approach in Coq [2] proof assistant system and prove that the convergence of the execution does not depend on the order of the conjuncts.
REFERENCES
1 Petr Lozov and Dmitry Boulytchev
|
{"Source-Url": "http://minikanren.org/workshop/2020/minikanren-2020-paper1.pdf", "len_cl100k_base": 9581, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 44875, "total-output-tokens": 11686, "length": "2e13", "weborganizer": {"__label__adult": 0.0003376007080078125, "__label__art_design": 0.0003349781036376953, "__label__crime_law": 0.0003936290740966797, "__label__education_jobs": 0.0005784034729003906, "__label__entertainment": 7.772445678710938e-05, "__label__fashion_beauty": 0.00014197826385498047, "__label__finance_business": 0.00022733211517333984, "__label__food_dining": 0.0004138946533203125, "__label__games": 0.0006365776062011719, "__label__hardware": 0.0005288124084472656, "__label__health": 0.0004799365997314453, "__label__history": 0.0002143383026123047, "__label__home_hobbies": 8.797645568847656e-05, "__label__industrial": 0.0004432201385498047, "__label__literature": 0.0003762245178222656, "__label__politics": 0.00032067298889160156, "__label__religion": 0.0005211830139160156, "__label__science_tech": 0.0255126953125, "__label__social_life": 9.495019912719728e-05, "__label__software": 0.005977630615234375, "__label__software_dev": 0.96142578125, "__label__sports_fitness": 0.00025200843811035156, "__label__transportation": 0.0005125999450683594, "__label__travel": 0.00017726421356201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37987, 0.03421]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37987, 0.15031]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37987, 0.81513]], "google_gemma-3-12b-it_contains_pii": [[0, 3624, false], [3624, 6876, null], [6876, 10080, null], [10080, 14065, null], [14065, 17507, null], [17507, 20354, null], [20354, 23048, null], [23048, 26500, null], [26500, 29841, null], [29841, 31421, null], [31421, 35535, null], [35535, 37987, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3624, true], [3624, 6876, null], [6876, 10080, null], [10080, 14065, null], [14065, 17507, null], [17507, 20354, null], [20354, 23048, null], [23048, 26500, null], [26500, 29841, null], [29841, 31421, null], [31421, 35535, null], [35535, 37987, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37987, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37987, null]], "pdf_page_numbers": [[0, 3624, 1], [3624, 6876, 2], [6876, 10080, 3], [10080, 14065, 4], [14065, 17507, 5], [17507, 20354, 6], [20354, 23048, 7], [23048, 26500, 8], [26500, 29841, 9], [29841, 31421, 10], [31421, 35535, 11], [35535, 37987, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37987, 0.08118]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
dbdedc49d81dafa67145a644459823bc0e64762c
|
A Proposed Taxonomy for Software Development Risks for High-Performance Computing (HPC) Scientific/Engineering Applications
Richard P. Kendall
Douglass E. Post
Jeffrey C. Carver
Dale B. Henderson
David A. Fisher
January 2007
TECHNICAL NOTE
CMU/SEI-2006-TN-039
Unlimited distribution subject to the copyright.
# Table of Contents
<table>
<thead>
<tr>
<th>Section</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>Abstract</td>
<td>iii</td>
</tr>
<tr>
<td>Introduction</td>
<td>1</td>
</tr>
<tr>
<td>A. Development Cycle Risks</td>
<td>5</td>
</tr>
<tr>
<td>B. Development Environment Risks</td>
<td>13</td>
</tr>
<tr>
<td>C. Programmatic Risks</td>
<td>21</td>
</tr>
<tr>
<td>References</td>
<td>25</td>
</tr>
<tr>
<td>Glossary</td>
<td>27</td>
</tr>
</tbody>
</table>
Abstract
Because the development of large-scale scientific/engineering application codes is an often difficult, complicated, and sometimes uncertain process, success depends on identifying and managing risk. One of the drivers of the evolution of software engineering, as a discipline, has been the desire to identify reliable, quantifiable ways to manage software development risks. The taxonomy that follows represents an attempt to organize the sources of software development risk for scientific/engineering applications around three principal aspects of the software development activity: the software development cycle, the development environment, and the programmatic environment. These taxonomic classes are divided into elements and each element is further characterized by its attributes.
Introduction
Because the development of large-scale scientific/engineering application codes is an often difficult, complicated, and sometimes uncertain process, success depends on identifying and managing risk. Failure of some sort has been a common occurrence in the software development milieu; the literature indicates that more than 25% of all software development projects are cancelled outright before completion and something like 80% overrun their budgets. It is no surprise, then, that one of the drivers of the evolution of software engineering, as a discipline, has been the desire to identify reliable, quantifiable ways to manage software development risks (the possibility of suffering harm or loss, or “the product of uncertainty associated with project risks times some measure of the magnitude of the consequences” [Schmidt 2001]), stemming from, for example
- uncertain or inaccurate requirements
- requirements that change too rapidly
- overly optimistic scheduling
- institutional turmoil, including too much employee turnover
- poor team performance [DeMarco 1999]
Of course, these are risks for software development projects of every stripe, not just scientific/engineering applications. Some important attributes specific to scientific/engineering software application development projects that impact risk include the following:
- Although the laws of nature, the ultimate source of requirements for scientific/engineering applications, are fixed, they may not be well understood for a given application. For example, there is the issue of emergent behavior of physical phenomena that cannot be anticipated at the start of a project. Moreover, a given set of physical requirements may be represented by different, equally valid, but possibly mutually inconsistent algorithms in multi-physics applications.
- Scientific and engineering code development is often very lengthy—spanning decades and careers, so that the target problems of interest and the needs of the users necessarily evolve and change during code development.
- To some extent it is true of most such projects that the requirements at levels below the most obvious are not specified by the sponsor or customer because of (1) a desire to allow the project some flexibility in execution, and (2) the fact that lower level details are not known or even understood by the sponsor or customer. General project goals may be specified by the sponsor or customer, but these stakeholders often rely on the software development team itself, or its management, to translate these very-high-level goals into requirements.
- Scientists tend to be averse to complicated or expensive “process”-oriented software development methodologies whose value they question.
- The principal driver of scientific/engineering applications is, not surprisingly, science and engineering; the developers of these codes are often not explicitly funded or trained to do software engineering.
• Any scientific/engineering code running on a finite state machine—a computer—can only approximate the generally continuous laws of nature. There are inherent inaccuracies that arise from representing physical entities as object-based models.
• Many scientific/engineering software application development projects start out as research projects, and the codes as research codes. In this state there cannot be a definitive relationship between deliverables, schedule, and resources.
• It is often true that the developers are also the users or a significant part of the user community.
• Scientific and engineering code development is strongly driven by prototypes, for example prior codes that provide simpler, usually less comprehensive simulations of the laws of nature. In a sense, science is a model of nature that scientists are continually improving and refining. Scientific/engineering software is usually the latest embodiment of scientific models.
The taxonomy that follows represents an attempt to organize the sources of software development risk for scientific/engineering applications around three principal aspects of the software development activity:
• the software development cycle
• the development environment
• the programmatic environment
These taxonomic classes are divided into elements and each element is further characterized by its attributes.
<table>
<thead>
<tr>
<th>A. Development Cycle Risks</th>
<th>B. Development Environment Risks</th>
<th>C. Programmatic Risks</th>
</tr>
</thead>
<tbody>
<tr>
<td>a. Predictability</td>
<td>a. Repeatability</td>
<td>a. Schedule</td>
</tr>
<tr>
<td>b. Evolvability</td>
<td>b. Suitability</td>
<td>b. Staff</td>
</tr>
<tr>
<td>c. Completeness</td>
<td>c. Control of Process</td>
<td>c. Budget</td>
</tr>
<tr>
<td>d. Clarity</td>
<td>d. Familiarity with Process or Practice</td>
<td></td>
</tr>
<tr>
<td>e. Accuracy</td>
<td>e. Environment</td>
<td>d. Facilities</td>
</tr>
<tr>
<td>f. Precedence</td>
<td>f. Change Control</td>
<td>e. Management</td>
</tr>
<tr>
<td>g. Execution Performance Expectations</td>
<td></td>
<td>f. Commitment</td>
</tr>
<tr>
<td>h. Proportionality</td>
<td></td>
<td></td>
</tr>
<tr>
<td>a. Difficulty</td>
<td>a. Hardware Capacity</td>
<td>a. Contract Type</td>
</tr>
<tr>
<td>c. Usability</td>
<td>c. Suitability</td>
<td>c. Dependencies</td>
</tr>
<tr>
<td>d. Maintainability</td>
<td>d. Usability</td>
<td></td>
</tr>
<tr>
<td>e. Portability</td>
<td>e. Familiarity</td>
<td></td>
</tr>
<tr>
<td>f. Reliability</td>
<td>f. Reliability</td>
<td></td>
</tr>
<tr>
<td>3. Implementation Risks</td>
<td>g. Target-Unique System Support</td>
<td></td>
</tr>
<tr>
<td>a. Specifications</td>
<td>h. Security</td>
<td></td>
</tr>
<tr>
<td>b. Project Plan</td>
<td></td>
<td></td>
</tr>
<tr>
<td>c. Scale of Effort</td>
<td>3. Program Interface Risks</td>
<td></td>
</tr>
<tr>
<td>4. Test and Evaluation Risks</td>
<td></td>
<td></td>
</tr>
<tr>
<td>i. Unit Testing</td>
<td>b. Project Organization</td>
<td>c. User Commitment</td>
</tr>
<tr>
<td>ii. Integration Testing</td>
<td>c. Management Experience</td>
<td>c. Sponsor Alignment</td>
</tr>
<tr>
<td>iii. Interoperability Testing</td>
<td></td>
<td>d. Subcontractor Alignment</td>
</tr>
<tr>
<td>b. Validation</td>
<td>d. Program Interfaces</td>
<td>e. Prime Contractor</td>
</tr>
<tr>
<td></td>
<td>e. Reward Systems</td>
<td>f. Corporate Communi</td>
</tr>
<tr>
<td></td>
<td>4. Management Methods Risks</td>
<td>g. Vendor Performance</td>
</tr>
<tr>
<td></td>
<td>a. Monitoring</td>
<td>h. Political</td>
</tr>
<tr>
<td></td>
<td>b. Personnel Manage-</td>
<td></td>
</tr>
<tr>
<td></td>
<td>ment (Staffing and Training)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>c. Quality Assurance</td>
<td></td>
</tr>
<tr>
<td></td>
<td>d. Configuration Management</td>
<td></td>
</tr>
<tr>
<td></td>
<td>5. Work Environment Risks</td>
<td></td>
</tr>
<tr>
<td></td>
<td>a. Quality Attitude</td>
<td></td>
</tr>
<tr>
<td></td>
<td>b. Cooperation</td>
<td></td>
</tr>
<tr>
<td></td>
<td>c. Communication</td>
<td></td>
</tr>
<tr>
<td></td>
<td>d. Morale</td>
<td></td>
</tr>
<tr>
<td></td>
<td>e. Trust</td>
<td></td>
</tr>
</tbody>
</table>
SOFTWARE ENGINEERING INSTITUTE | 3
A. Development Cycle Risks
The development cycle encompasses the activities that are associated with the development of production-worthy code: requirements gathering, code design, the formulation of specifications, project planning, implementation, and testing.
The elements/attributes associated with this class of risks will be limited in this taxonomy to those sources of risk associated with the deliverable itself, independent of sources of risk associated with the processes or tools used to produce it or programmatic risks introduced by finite resources or external factors beyond project control. The risks arising from this class are usually considered to be intrinsic risks, that is, risks that are manageable from within the software development project itself. Risks that derive from external constraints are usually extrinsic, and those associated with processes or tools lie somewhere in between.
1. Requirements Risks
Requirements analysis, definition and management are intrinsic elements of life-cycle management. Risk attributes of the requirements risk element are associated with both the quality of the software requirements specification and also the difficulty of implementing software that satisfies the requirements.
In projects that start from poorly articulated requirements, as scientific/engineering projects often do, there is inherently far more risk that imprecisely expressed expectations will not be met. Technically difficult or imprecise requirements, coupled with the inability to negotiate relaxed requirements or budgets or schedules is a well-recognized source of software engineering risk.
The following attributes will be employed to illuminate the nature of the risks that are associated with the “requirements” element.
a. Predictability
Unexpected changes in requirements—that is, “unpredictability”—has been cited as the sixth highest source of risk that all software projects face [Keil 1998].
Within the scientific/engineering software development environment, a lack of predictability in requirements is often a consequence of the evolutionary nature of the requirements themselves. Many scientific/engineering code development projects begin as research projects or have research components throughout their life cycles. As such there is an inherent unpredictability about the requirements that must be addressed in the budgets and schedules of the project. Often the “iron triangle” of requirements, budgets, and schedules is inverted, with budgets and schedules fixed and requirements the only unconstrained variable. Even so, change control remains an important risk management tool.
This attribute also covers the risk associated with an evolving technical architecture.
b. **Evolvability**
The failure to recognize and adequately address the continuous evolution of requirements, that is “evolvability,” is an especially important source of risk in long-lived scientific and engineering projects. This is particularly true in the period before the first significant deliverable, which may be the better part of a decade for a complex multi-physics code. Such projects sometimes fail because they cannot manage evolving requirements.
c. **Completeness**
Incomplete requirements fail to describe either the full intent or true intent (or both) of the customer. The principal consequence of this source of risk is that scope cannot be aligned with schedule and budget (resources). One purpose of the specification step (below) is to better codify the requirements and the intended design so that schedule and budget issues may be more fully addressed. Moreover, testing and code verification, also described below, cannot be very rigorous or complete without requirements against which to test.
d. **Clarity**
Clarity here is synonymous with understandability. Understandability is especially important when high-level goals are expressed by a customer who expects the developers to translate them into actionable requirements or a complete specification. The consequence of the lack of “clarity” is that the true intent of the requirements may not be discovered until it impacts negatively the schedule or budget of the project.
Lack of clarity of the requirements has been cited as the third highest source of risk faced by all software development projects [Schmidt 2001, Keil 1998].
e. **Accuracy**
Accuracy refers to the expectation that the aggregate requirements, which are likely to evolve in the case of many scientific/engineering software projects, reflect customer intentions or expectations for the application. If the requirements do not capture customer expectations, customer commitment to the project may be jeopardized. User commitment, which typically depends strongly on validity of the requirements, has been cited as the second highest source of software risk [Schmidt 2001, Keil 1998].
f. **Precedence**
Any software development project that posits capabilities that have not been demonstrated in existing software or that are beyond the experience of the project team or institution—that is, for which there is no “precedent”—may be vulnerable to this source of risk. The consequence may be that the project managers and team may not recognize that the objectives are infeasible.
g. **Execution Performance Expectations**
If execution performance is a major driver of the code development project, then these expectations must be addressed in the requirements, design, specifications, and testing of the application. Sometimes prototypes offer the best way to determine if performance expectations can be at-
tained. Too little attention to this source of risk usually results in a discarded code that is otherwise a technical success.
Especially in the high-performance computing (HPC) environment of cutting-edge hardware, there exists the possibility that tacit and/or written performance expectations cannot be met. Examples of performance metrics sometimes specified in contracts include:
- degree of performance optimization
- degree of parallel scaling
- fraction of theoretical peak performance for specified benchmarks
- job processing time for important applications of the code
- number of production runs per unit time (week, month, etc.)
Execution performance expectations sometimes drive optimization to the detriment of the accuracy, flexibility and utility of the resulting code.
### h. Proportionality
Proportionality refers to the possibility that the requirements may be disproportionate to the solution, that is, that the problem is over-specified. For example, too many and too specific nonessential requirements can preclude feasible solutions. This source of risk is not confined to technical requirements; they often enter through management mandates that impact the function of the development team.
### 2. Design Risks
Design encompasses those steps through which requirements are translated into an actionable development plan. We distinguish three steps: software architecture (abstract or conceptual design), specification, and design per se. The software architecture should be influenced by the scientific domain and the mathematical attributes of the application (e.g., initial value problem, steady-state problem, eigenvalue problem, time evolution problem). With only the requirements and architecture, many software implementations are admitted; with a complete design and complete specification, there are far fewer options. It is important therefore to vet these documents (usually referred to as a “baseline”) both ways: with the sponsor/customer to ensure that requirements (even unstated) and expectations will be met, and with the implementation team to ensure that they are confident of successful implementation. Finally, it is important that specifications and design be documented and kept up-to-date (this is referred to as “baseline management”); otherwise the work breakdown structure, scheduling, and budgeting (which should be based upon them) will be faulty. This is typically assessed in a critical design review (CDR).
Another sometimes overlooked design risk is the impact of design on testing. Difficulty in testing may begin with failure to include test features, especially those important to users, in the design.
The following attributes characterize different aspects of the risks inherent in the design element. It is also important to recognize that while documentation is very important, there is a risk of becoming too enamored with this aspect of project management at the expense of continuous validation against changing needs.
a. Difficulty
The existence of functional or performance requirements or expectations that are believed at the outset to be “difficult” should be viewed as a potential source of risk. The obvious consequence is that these requirements may not be met. Scientific/engineering software systems must deal with complications like algorithm adequacy, mesh generation, problem setup, very complex debugging and visualization, and the sheer size of the calculations. The most serious manifestation of this complexity may be that the requirements are discovered to be infeasible, that is, in conflict. Often a major project should be preceded by a serious feasibility study; the results of which may cause redefinition of requirements or even abandonment of the project before any coding is begun.
b. Modularity
Modularity refers to the extent to which the code has been created using components or units that function independently from the other components. Software that has many direct interrelationships between different parts of the code is said to be less modular. Ideally, scientific code should be developed in modules that interact through well-defined interfaces and that capture functionality that can be independently tested (verified and validated). Generally speaking, the less modular a code is, the more likely it will not be maintainable or portable.
c. Usability
Usability is in the eye of the beholder, and since it is often true that the developers of scientific/engineering codes are often users, this aspect of the requirements receives too little attention. Even for developers, code that is difficult to use can strongly penalize the production phase and even the testing phase of a software project. In scientific codes, a lack of usability often manifests as opaque configuration options or grids that are difficult to set up. Scientific code developers, while they may be experts in their scientific domains, may not be experts in usability, human factors, or even the use of their own codes by others. Usability is emerging as a major risk within the HPC development environment as multi-discipline applications become ever more complex.
d. Maintainability
Maintainability, the ability to support the production phase of the product’s life cycle with a reasonable level of resources, may be placed at risk by poor software architecture, design, specification, coding, or documentation. These failures may result from undefined or un-enforced standards, or from neglecting to analyze the system from the perspective of future maintainability. Maintainability is a strong function of attributes such as
- module cohesiveness and exclusivity
- interface minimization
- avoidance of complexity (the “KISS” principle)
- transparency and coding style
Because many significant scientific/engineering applications spend decades in the production/maintenance stage of the software life cycle, risks associated with a lack of maintainability must be addressed in design and implementation. The main consequence of a lack of maintain-
ability is a shortened life expectancy of the code. Some typical measures or indicators of maintainability include [Process Impact]
- lines of code (the most common measure but least indicative of maintainability)
- function points
- cyclomatic or Halstead complexity
- data coupling
- comment lines
- modularity (cited above)
- level of documentation (including programmer documentation)
- logical flow
e. Portability
While some scientific/engineering codes are used only once, or only with one type of computer, the majority of these codes outlast the generation of computers that they are first installed on, or are required to run on multiple hardware platforms from the beginning. Portability is often a necessity when developing code for HPC environments, because access to the target platform may be too limited to support the development timelines. Consequently, codes must be designed with portability as a conscious goal. The consequences of inattention to this issue range from unplanned effort to migrate the code to new hardware to, in the worst case, a complete rewrite. Codes that are not portable have short lives.
There is a strong link between portability and maintainability. The evolution of computer architectures is driven by the need to increase performance, not the need to promote portability. Ideally, the architectures of scientific/engineering software should be sufficiently flexible so that the software can be ported to future generations of computers with architectures that are currently unknown. To the extent that advances in performance are achieved through hardware, software portability becomes more important than software efficiency.
f. Reliability
Reliability refers to the ability of the software to be used in a production setting. Software unreliability has a number of sources:
- the target hardware not meeting its reliability specifications
- system complexity that creates the likelihood that schedules cannot be met
- unreliable supporting software in the development environment (e.g., compilers, debugging tools, trace tools)
These sources of risk should be addressed during the design phase and are usually consigned to the risk management agenda of the project.
3. Implementation Risks
This element addresses the sources of project risk associated with how the coding will be done, that is, how the design will be translated into unit specifications and ultimately “units” of code. Attributes of this element describe the nature of risks associated with the quality and stability of software or interface specifications, and coding constraints or even “styles” that, if left unspeci-fied, may exacerbate future maintenance and extensibility problems. Software specifications are as important to the project success as are the more obvious higher level “requirements” explored earlier. Project teams dominated by physical or natural scientists or engineers may not recognize this, which often exacerbates the impacts of these risks.
a. Specifications
Specifications are typically the output of the design step; they describe how the requirements are to be met in the code to be developed and drive the planning process. Requirements do not generally define an application code; the specification documentation (detailed design) should. Therefore, vetting the specifications back to the sponsor/customer and ahead to the implementers is important, as mentioned above. Module interfaces, for example, are beyond the scope of most requirements (sponsors have little reason to care), but should be fully spelled out in the specifications. Specifications may be inadequate in at least the following ways:
- they may not accurately reflect the requirements
- they may not be complete or detailed enough to guide the development activity
Specifications should also provide the basis for the test plan; often the adequacy of testing is judged against the specification, not the requirements.
Another source of risk associate with the specifications is the lack of coherence, especially with regard to third-party components.
b. Project Plan
A project plan translates the specifications into a plan of action with a schedule, resources, and budget. In the scientific software environment, the project plan must be flexible and adaptable to address the changing needs and goals of the project—especially those with research objectives or unknown requirements. It is often true that the achievement of a project milestone has the potential to change the direction of the project. Moreover, rapidly evolving software, hardware, and scientific technologies also have this potential. (“Rapidly evolving” refers to changes that occur over shorter time scales than the code development project itself.)
Nevertheless, to project stakeholders, the project plan may be the only tangible project asset in the initial phases. To the extent that there is no plan or one that does not adequately keep the stakeholders in the project (i.e., upper management, sponsors, customers) informed, there is a risk that the project may face problems with continued support. Of course, the execution is also at risk.
c. Scale of Effort
The technical challenges presented by the sheer scale of complex applications development typical of the HPC environment is a source of risks related to
• the ability to satisfy hardware performance expectations, especially the scaling of performance with more resources such as processors
• the ability to utilize system resources (e.g., distributed memory, caches, and threading)
• the complexity of system integration involving multiple programming languages and fragile operating systems
• the difficulty of debugging in an HPC environment
Also, as scientific/engineering software projects grow more complex, the ability of an individual team member to grasp the consequences of individual actions on the unfamiliar parts of the project is a source of risk. This is especially true in the “system of systems” case, that is, when the code under development is a part of a much larger system whose other components are developed by other teams.
In the Constructive Cost Model (COCOMO) estimation models, “scale” is the most important factor contributing to a project’s (or, in the case of a system of systems, a major component’s) duration and cost. Consequently, scale must be viewed as a potential source of risk [Boehm 1995].
4. Testing and Evaluation Risks
In the original [Carr 1993], “testability” risks were an attribute of design risk, not a class by itself. Owing to the importance of the verification and validation of scientific/engineering software, it has been included as a source of risk at a higher level in this taxonomy. Just as scientific/engineering software must have requirements and a design codified into a specification document, it must also have a documented test plan. Most testing will address specifications, but important validation (in part B, below) will address the requirements. All test plans should include a test coverage matrix documenting just what is being tested and how. The main consequence of the sources of risk cited below is that it will not be possible to demonstrate that the code is actually fit to purpose.
a. Verification
Verification refers to ensuring that the code solves the equations of the model correctly. Since scientific/engineering software cannot be exhaustively tested through a deterministic, combinatorial approach, there is always a risk that some feature or aspect of it cannot be verified. Project planning therefore demands the inclusion of better and perhaps more statistically sophisticated test methods, often requiring the expertise of a group (typically statisticians) distinct from the development team, to minimize the risk that the code does not implement the algorithms of the model correctly. Another good reason to use an independent test organization is that they are less prone to share unrecognized assumptions. Verification is typically conducted at different stages of development:
i. Unit Testing
Unit testing refers to the testing of the basic features of the code, usually found in individual modules or “units.” (A software “unit” is a component that is not subdivided into other components [IEEE 1990]. Risk factors affecting unit testing include:
- availability of pre-planned test cases that have been verified to test unit requirements
- availability of a test bed consisting of the necessary hardware or emulators, and software or simulators
- availability of test data to satisfy the planned test
- sufficient schedule to plan and carry out the test plan
ii. Integration Testing
Integration testing refers to the testing of multiple units of the code as an ensemble. The risk factors cited above for unit testing also apply here; however, the first one, the availability of pre-planned cases, is often a larger issue and a more significant source of risk.
iii. Interoperability Testing
Here the scale of testing advances to include the interaction with the target hardware, if that has not already occurred, as well as the interfaces to third-party applications that users, not developers, employ (like visualization tools), and other aspects of the actual user environment.
b. Validation
Validation refers to determining whether the mathematical model instantiated in the code faithfully mimics the intended physical behavior. This is a central difficulty for scientific/engineering codes because, in many instances, the software is developed to model behavior that is too expensive, too dangerous, or impossible to test in the first place. Another manifestation of the risk associated with validation is that the region of applicability of the underlying model upon which the code is based may not be known. These risks should be quantified up front as accurately as possible to ensure that unrealizable expectations are avoided. Finally, there is an increasing possibility that the code is part of a larger system, each component of which carries the risks described above in unknown proportions. Validating the components of a system is not the same as validating the whole system. In a sense the users of scientific codes are the final arbiters of the domain of applicability of these codes, but there is a risk that their determinations will not benefit from any knowledge of the assumptions of the developers. It can be argued that one of the goals of validation testing should be to determine the region of applicability of the code. Validation testing can usually only be done at the end of the development process.
B. Development Environment Risks
The “development environment risk” class addresses the sources of risk inherent in an environment and the processes used to develop a software application. The risks here are usually intrinsic, but in some instances the choice of development environment, or some of its features, is beyond the control of the code development team. This environment includes the development philosophy, (e.g., Capability Maturity Model [CMM], agile), workflow management model (e.g., incremental, iterative, spiral, and others), the development system, project management methods, and work environment. The risk elements associated with the development environment are characterized below.
1. Development Process Risks
This element refers to risks that can be experienced through a process or processes by which the development team proposes to satisfy the customer’s requirements. The process is the sequence of steps leading from the initial requirements gathering and specification to the final delivered software product. Development processes themselves have attributes. Most conform to some degree to a development philosophy like CMM, ISO, or agile. Most development processes can also be identified with a workflow management model (called “development models” in the original SEI risk taxonomy).
The development philosophy typically describes the approach to processes used to create a software product [Paulk 1993]. Examples include formal methods favored by CMM or ISO, and agile methods, which are often encountered in scientific/engineering code development projects. CMM-endorsed processes emphasize a formal approach to the customary development phases (i.e., life-cycle elements [IEEE 1990]) of requirements analysis, product design, product creation, testing, delivery, and maintenance (sometimes called “production,” ending ultimately in the eventual retirement or decommissioning of the application). It includes both general management processes such as costing, schedule tracking, and personnel assignment, and also project-specific processes such as feasibility studies, design reviews, and regression testing. Importantly, advanced CMM organizations collect and utilize metrics about their own development processes with a view to process improvements. Agile methods, on the other hand, focus at a philosophical level on software development practices and people, not processes. Note that some agile methods are very prescriptive; the reference above is intended to capture the shared philosophical basis of this development methodology [Agile Software]. The lack of a methodology has been recognized as a risk in and of itself. Specific sources of risk associated with the absence of a development methodology include the absence of coherent change control, no project planning, and no repeatable processes or practices. Of course, the adoption of—or more likely, the imposition of—a methodology incompatible with the goals of the project or the development team is also a source of risk.
Workflow management models describe different approaches to the management and organization of the development project workflow elements cited above [Beck 1999]. Various models have been proposed for this: waterfall (the original conceptual model for software development),
incremental, iterative, evolutionary, spiral (emphasizing prototyping), and others. At the opposite end of the spectrum from the waterfall model are approaches like extreme programming (XP) and rapid application development (RAD). Note that the software engineering literature often aligns these workflow management models with certain development methodologies, e.g., RAD with agile.
This element groups risks that result from a development philosophy and/or workflow management approach that
- does not reflect what is known at the beginning of the project
- is not suited to the activities necessary to accomplish the project goals
- is poorly communicated to the project staff and lacks enforceability
a. Repeatability
Product quality is strongly correlated with development process repeatability. Whether repeatability is associated with formal development processes or rigorously followed practices, it is cited by all of the major development philosophies as a requirement for success. The lack of repeatability may result in the inability of the team to reconstruct, extend, or even modify in a deliberate way its approach.
b. Suitability
Suitability refers to the support for the type and scope of the activities required for a specific software development project provided by the selected development philosophy, process, methods, and tools. For example, the adoption of too much formality may put agility at risk in projects where flexibility is important.
c. Control of Process
Some form of process control is usually necessary to ensure that
- the processes or practices adopted by the project are adhered to
- monitoring of quality and productivity goals occurs
Control may be complicated when development occurs at distributed sites. Control of process is an important aspect of scheduling. Two significant control-related sources of risk here are (1) artificial deadlines, that is, deadlines not reflected in the project plan derived from the specifications, and (2) preemption of the schedule by a project with higher priority. The main consequence of a lack of control of process is that the software project management is not able to assess the state of the project at any point in time (the “lost in the woods” syndrome).
d. Familiarity with Process or Practice
Lack of familiarity with the development process or practices often results in the failure of the development team to adopt them. Scientific/engineering code developers tend to be process-averse. Most are scientists or engineers, not software engineers or even professional programmers. A special effort is usually necessary to get such teams to follow development processes, in par-
ticular. Success is greatest when the teams recognize the value and benefits of the process or practice.
e. Environment Change Control
The development environment itself will inevitably not be static during long software development cycles. Some orderly way to adapt to change is necessary, but is often overlooked by scientific code developers. Unanticipated and unplanned changes in the development environment—even something as simple as a compiler upgrade—can disrupt the development schedule.
2. Development System Risks
The development system risk element addresses those risks related to the choices of hardware and software tools used in application development. The purpose of these tools is to facilitate application development and in some cases (such as integrated development environments) to reduce performance risk as well (for example, by introducing automated product control).
a. Hardware Capacity
Inadequate capacity of the development system may result from too few development workstations, insufficient access to the target platform, or other inadequacies in equipment to support the scheduled pursuit of unit development, code integration, tuning, and testing activities. One or another of these sources of risk exists for almost all projects at some point in their lives. The consequence is project delay.
b. Development System Capability
This attribute refers primarily to the completeness and maturity of the tools of the trade for the scientific/engineering software developer:
- compilers
- linkers
- schedulers
- debuggers
- memory checkers
- profiling toolkits and APIs
- tracers
- visualizers
- bug tracking tools
- integrated development environments
- mathematical program libraries
- memory management libraries
Secondarily, it refers to the capabilities of the hardware used for development, including the target hardware. The performance, availability and long-term support of development tools is often (correctly) considered to be a major source of risk by scientific/engineering software developers.
c. Suitability
A development system that does not support the specific development models, processes, practices, methods, procedures, and activities required and selected for application development is a source of code team performance risk. This attribute also includes risks introduced by the management, documentation, and configuration management processes. In HPC environments there are often gaps in the availability of tools to support these activities. The closer the project is to the cutting edge of hardware evolution, the greater the likelihood that the software development environment will exhibit deficiencies that may not have been foreseen during scheduling.
d. Usability
Usability usually manifests in the presence of development system documentation, the accessibility of the system itself, and the ease of use of the features of the system. It is not uncommon for the software environments of state-of-the-art HPC machines to be fragile (e.g., unstable compilers or even operating systems), which limits the usability of the machines well into the development cycle. Unusable or difficult-to-use systems endanger project schedules and budgets in ways that may be difficult to quantify in advance.
e. Familiarity
Development system familiarity is a function of the prior use of the system by the host organization and by project personnel, as well as adequate training for new developers. Software developers for state-of-the-art HPC machines, no matter how experienced, often face steep learning curves when confronted with new languages, compilers, and computer architectures. It can be difficult to predict the impact of this learning curve on code team productivity. The lack of familiarity usually manifests in unreliable project development schedules and budgets.
f. Reliability
Here reliability means dependability, not usability. An unreliable development system is a major source of risk to code team productivity.
g. Target-Unique System Support
System support, including training and access to expert users and prompt resolution of problems by vendors, is crucial in the HPC environment. Lack of it can stop a development project in its tracks.
h. Security
Dealing with access security, especially in secure environments, usually adds steps to the development process and typically an underestimation of the effort required to address them. The long times required to obtain security clearances for capable and ready project staff is a common costly example.
3. Management Process Risks
This is the category of risks associated with planning, monitoring, and controlling budget and schedule; controlling factors involved in defining, implementing, and testing the software application; managing project personnel; and handling external organizations, including the customer, senior management, matrix management, and other contractors. It is widely recognized that management actions determine, and management is ultimately responsibility for, much of the risk associated with software development projects. Management processes must support the following central objectives [DeMarco 1999]:
- recruit the right staff
- match them to the right tasks
- keep them motivated
- help teams jell
Moreover, management commitment has been cited as the number one risk to long term project success [Schmidt 2001, Keil 1998].
a. Contingency Planning
The existence of a well-defined plan that is responsive to contingencies as well as long-range goals is necessary for the proper management of project resources, schedule, and budget. The plan must be formulated with the input or at least acquiescence of those affected by it. Not doing so has led to many software development failures.
b. Project Organization
The goal of project organization and management is to foster the creation and nurturing of a well-functioning team. In a poorly organized team the roles and responsibilities are not understood or followed. The importance of this attribute increases in proportion to the size and scope of the project. One project organization scheme does not fit all situations. The most egregious examples of faulty organization usually come from large, very informal, process-averse teams.
c. Management Experience
A lack of management experience can impede effective communication and decision making in software projects, and can manifest at all levels regarding
- general management
- software development management
- the application domain
- scale and complexity of the project and targeted hardware system(s)
- selected development process or practices
- development environment
d. Program Interfaces
Ineffective interactions have a negative impact on decision making and can occur among managers at all levels with program personnel at all levels, and with external personnel such as the customer, senior management, and peer managers.
e. Reward Systems
Reward systems are often a tacit component of the management process. Scientific/engineering software development projects are usually meritocracies. Consequently, if the rewards system is not perceived to be aligned with merit, there can be a negative impact on project morale.
4. Management Methods Risks
This element refers to the risks associated with methods adopted for managing both the development of the product and program personnel. These include risks related to quality assurance, configuration management, staff development with respect to program needs, and maintaining communication about program status and needs. The continuity of management support over the life of the project is an important facet of this element. Continuity is especially challenging in view of the fact that many important scientific code development projects have a production phase that spans careers—that is, decades long.
a. Monitoring
It is impossible to address problems if there is no mechanism in place to detect them. The main consequence of risk associated with unmonitored projects is that they will exhibit unpredictable and unexpected outcomes.
b. Personnel Management (Staffing and Training)
Personnel management generally refers to selection and training of program members to ensure that they
- take part in planning and customer interaction for their areas of responsibility
- work according to plan or at least expectations
- receive the help they need or ask for to carry out their responsibilities
Poor team performance may stem from failures to address personnel management issues. Sources of staffing risks include
- insufficient/inappropriate project staff
- staff volatility
- unnecessary use of outside consultants
- lack of domain and programming expertise
c. Quality Assurance
The term “software quality” typically refers to code that is as defect-free as is practical, and is maintainable, portable, and well-written (transparent). In the typical scientific/engineering soft-
ware development project, these attributes are not customarily specified contractually, but are expected deliverables of the development team. This does not necessarily happen spontaneously. Without management attention, there is the possibility that quality assurance will be either lacking or uncertain.
Another aspect of quality assurance is related to the concept of validation—can the code be validated as consistent with the laws of nature that it is intended to model. The consequence here is that even the perfect specimen satisfying the definition of the previous paragraph is of unknown value.
d. Configuration Management
For scientific/engineering codes the consequences of faulty configuration management (of both code and documentation) grow in proportion to
- the age of the code
- the size of the code
- the size of the code team
- the failure to use repeatable processes
- the failure to enforce standards
The main consequence of faulty configuration management is an unmanageable program library.
5. Work Environment Risks
This element refers to risks arising from subjective aspects of the environment such as the amount of care given to ensuring that stakeholders, including the management, users, sponsors, and the development team itself, are kept informed of program goals and information, the way they work together, their responsiveness to staff inputs, and the attitude and morale of the program personnel. A well-functioning development team has already been identified as a critical success factor for software development projects, scientific/engineering or otherwise.
a. Quality Attitude
It is important to recognize that scientists and engineers are usually more concerned with developing code that supports their scientific goals than with code that conforms to the customary notions of IT software quality. As far as the science is concerned, the code may be excellent, but it may be lacking in quality attributes important to sponsors and users. Nevertheless, it is the drive, focus, and scientific integrity of scientific code developers that is the source of quality in scientific/engineering applications. Misunderstandings about this are a constant source of tension between sponsors, managers, and code teams; education about the importance of sound software engineering process and practice continues to be needed.
b. Cooperation
Poor team relationships, which engender a lack of cooperation, can destroy code development projects. These may result from factors such as conflicting egos or even burnout. Management may not identify problems here soon enough to avoid damage to the project.
c. Communication
The goal of management communication is to ensure that knowledge of the mission, goals, requirements, and design goals and methods of the project are broadly understood by all of the stakeholders, specifically including the development team itself. Ineffective communications usually result in a misalignment between the goals of the stakeholders.
d. Morale
Morale has a strong impact on enthusiasm, performance, productivity and creativity. At the extreme end of consequences is anger that may result in intentional damage to the project or the product, an exodus of staff from the project, and harm to the reputation of the project organization that makes it difficult to recruit.
e. Trust
Trust is an attribute that is often taken for granted in the work environment. The consequence of a lack of trust is that all of the preceding attributes—cooperation, communication, morale, and even a quality attitude—will be diminished with an accompanying impact on project deliverables.
C. Programmatic Risks
Programmatic risks refer to those project risks emanating from “external” forces acting on scientific/engineering software development projects. These are sources of risk that are usually outside the direct control of the code development team, that is, extrinsic risks. From the development team’s point-of-view, these risks are often considered “acts of God.”
1. Resources Risks
This element addresses sources of project risk arising from resource dependencies or constraints that the project must honor. These dependencies/constraints include schedule, staff, budget, and facilities.
a. Schedule
The stability (and in some cases, feasibility) of the project schedule in the presence of changing internal and external events or dependencies—as well as the validity of estimates and planning for all phases and aspects of the project—is a source of risk that almost all software development projects face. Tight schedules and rigid deadlines are usually incompatible with scientific/engineering software development projects, which rarely can be planned at a fine level of granularity. Experience has shown that when schedules and milestones are dictated, projects are likely to fail.
b. Staff
The availability of project staff with adequate skills and experience is a prerequisite for success. Commitments to milestones and schedules are at risk if the project staff is deficient in numbers or skills and experience.
c. Budget
Like the schedule, the budget is a well-recognized [Boehm 1991] source of project risk. This tends to be a greater risk for software projects that extend over many budget cycles. Many long-lived scientific/engineering development projects are tied to annual budget cycles that force the code teams to manufacture artificial deliverables to ensure continued funding. There is an inviolate relationship between requirements, specifications, budget and schedule: imposing all of them a priori—absent design, specification and agreement from the implementers—is a recipe for failure.
d. Facilities
The availability of adequate project facilities, including computer and software support for development, integration, and testing of the application can impact project schedules. This is often overlooked in the project design and planning phases.
e. Management Commitment
A lack of management commitment has been cited as the greatest risk to software development projects of all stripes [Schmidt 2001, Keil 1998]. For many scientific/engineering software development projects in start-up mode, the first significant deliverable may not be available for three to six years from the start of the project. The managers who approved the project may well have moved on to other jobs, forcing the project team to remarket itself to new managers. A lack of management commitment is often fatal to a software development project.
2. Contract Risks
Risks associated with the program contract are classified according to contract type, restrictions, and dependencies.
a. Contract Type
Scientific/engineering code projects are often governed by level-of-effort agreements, cost plus award fee, cost plus fixed fee, or research grants. Any contract agreement that does not recognize the inherent difficulty associated with rigorous specification of the requirements increases the risk that contractual expectations will not be met. For example, cost and schedule are often estimated based on the history of previous similar projects. The contract vehicle must recognize the inherent uncertainties in this approach. Contract elements like the statement of work, data collection, testing requirements, and the amount and conditions of customer involvement are all subject to misinterpretation and are, therefore, potential sources of risk.
b. Restrictions
Contractual directives to use specific development methods, third-party software, or equipment may introduce uncertainties that cannot be addressed without evaluation. If development starts without this step, the project may founder.
c. Dependencies
Contractual dependencies on outside contractors or vendors, customer-furnished equipment or software, or other outside products and services are well-recognized sources of software development risk.
3. Program Interface Risks
This element consists of the various interfaces with entities and organizations outside the development program itself.
a. Customer Communication
Difficult working relationships or poor mechanisms for attaining customer agreement and approvals, not having access to certain customer factions, or not being able to communicate with the customer in a forthright manner are all sources of risk to the continued funding and ultimate acceptance of the software application.
b. User Commitment
Customers and users are not synonymous. Failure to gain user commitment and to manage user expectations has been cited as one of the top five threats to the success of all software development projects [Keil 1998].
c. Sponsor Alignment
In many cases, the customer, end user, and sponsor of a scientific/engineering software development project may not be the same, as is the case with most federally funded projects. The misalignment of the goals and expectations of the sponsor(s) with those of the customer(s) or end users is a source of project risk.
d. Subcontractor Alignment
Subcontractor alignment risks refer to those risks that arise from inadequate task definitions and subcontractor management mechanisms, or the failure to transfer subcontractor technology and knowledge to the program or host organization. Failure to transfer key technology from subcontractors places the sustainability of the code at risk.
e. Prime Contractor
When the project is a subcontract, performance risks may arise from poorly defined task definitions, complex reporting arrangements, or dependencies on technical or programmatic information.
f. Corporate Communication
Risks in the corporate management arena include poor communication and direction from senior management as well as non-optimum levels of support. Long-term projects are often buffeted by changes in the senior management of the host organization.
g. Vendor Performance
Vendor performance risks may present themselves in the form of unanticipated dependencies on deliveries and support for critical system components.
h. Political
Political risks may accrue from relationships with the company, customer, associate contractors, or subcontractors, and may affect technical decisions, schedules, and even support for the project.
References
[ACM]
[Agile Software]
[Beck 1999]
[Boehm 1991]
[Boehm 1995]
[Carr 1993]
[DeMarco 1999]
[DeMarco 2003]
[IEEE 1990]
[Keil 1998]
[Paulk 1993]
[Process Impact]
[Schmidt 2001]
[Weinberg 1998]
Glossary
acceptance criteria
The criteria that a system or component must satisfy to be accepted by a user, customer, or other authorized entity. [IEEE-STD-610.12]
acceptance testing
Formal testing conducted to determine whether or not a system satisfies its acceptance criteria and to enable the customer to determine whether or not to accept the system. [IEEE-STD-610.12]
application domain
Refers to the nature of the application. Here we are concerned with the high performance end of domain of scientific and engineering application.
audit
An independent examination of a work product or set of work products to assess compliance with specifications, standards, contractual agreements, or other criteria. [IEEE-STD-610.12]
availability
The degree to which a system or component is operational and accessible when required for use. Usually expressed as the ratio of time available for use to some total time period or as specific hours of operation. [IEEE-STD-610.12]
baseline
A specification or product that has been formally reviewed and agreed upon, that thereafter serves as the basis for further development, and that can be changed only through formal change control procedures. [IEEE-STD-610.12]
baseline management
In configuration management, the application of technical and administrative direction to designate the documents and changes to those documents that formally identify and establish baselines at specific times during the life cycle of a configuration item. [IEEE-STD-610.12]
benchmark
A standard against which measurements or comparisons can be made. [IEEE-STD-610.12]
change control
A part of configuration management that reviews, approves, and tracks progress of alterations in the configuration of a configuration item delivered, to be delivered, or under formal development, after formal establishment of its configuration identification. [IEEE-STD-610.12].
configuration
In configuration management, the functional and physical characteristics of hardware or software as set forth in technical documentation or achieved in a product [IEEE-STD-610.12].
configuration management
A discipline applying technical and administrative direction and surveillance to identify and document the functional and physical characteristics of a controlled item, control changes to a
configuration item and its documentation, and record and report change processing and implementa-
tion status [IEEE-STD-610.12].
**configuration management function**
The organizational element charged with configuration management.
**configuration management system**
The processes, procedures, and tools used by the development organization to accomplish con-
figuration management.
**critical design review (CDR)**
(1) A review conducted to verify that the detailed design of one or more configuration items sat-
isfy specified requirements; to establish the compatibility among the configuration items and
other items of equipment, facilities, software, and personnel; to assess risk areas for each configu-
ration item; and, as applicable, to assess the results of producibility analyses, review preliminary
hardware product specifications, evaluate preliminary test planning, and evaluate the adequacy of
preliminary operation and support documents. See also: preliminary design review; system design
review. (2) A review as in (1) of any hardware or software component. [IEEE-STD-610.12]
**customer**
The person or organization receiving a product or service. There may be many different customers
for individual organizations within a program structure. Government program offices may view
the customer as the user organization for which they are managing the project. Contractors may
view the program office as well as the user organization as customers.
**design specifications**
A document that prescribes the form, parts, and details of the product according to a plan (also see
design description. [IEEE-STD-610.12]
**detailed design**
(1) The process of refining and expanding the preliminary design of a system or component to the
extent that the design is sufficiently complete to be implemented. See also: software development
process. (2) The result of the process in (1). [IEEE-STD-610.12]
**development computer**
The hardware and supporting software system used for software development.
**development facilities**
The office space, furnishings, and equipment that support the development staff.
**development model (also workflow management model)**
The abstract visualization of how the software development functions (such as requirements defi-
nition, design, code, test, and implementation) are organized. Typical models are the waterfall
model, the iterative model, and the spiral model.
**development process**
The implemented process for managing the development of the deliverable product. For software,
the development process includes the following major activities: translating user needs into soft-
ware requirements, transforming the software requirements into design, implementing the design
in code, testing the code, and sometimes, installing and checking out the software for operational
use. These activities may overlap and may be applied iteratively or recursively.
development sites
The locations at which development work is being conducted.
development system
The hardware and software tools and supporting equipment that will be used in product development including such items as computer-aided software engineering (CASE) tools, compilers, configuration management systems, and the like.
external dependencies
Any deliverables from other organizations that are critical to a product's success.
external interfaces
The points where the software system under development interacts with other systems, sites, or people.
hardware specifications
A document that prescribes the functions, materials, dimensions, and quality that a hardware item must meet.
implementation
The process of translating a design into software. [IEEE-STD-610.12]
integration
The process of combining software components, hardware components, or both, into an overall system. [IEEE-STD-610.12]
integration environment
The hardware, software, and supporting tools that will be used to support product integration.
integration testing
Testing in which software components, hardware components, or both are combined and tested to evaluate the interaction between them. See also: component testing; interface testing; system testing; unit testing. [IEEE-STD-610.12]
internal interfaces
The points where the software system under development interacts with other components of the system under development.
maintainability
The ease with which a software system can be modified to correct faults, improve performance or other attributes, or adapt to a changed environment. [IEEE-STD-D610.12]
modularity
The degree to which a computer program is composed of discrete components such that a change to one component has a minimal impact on other components. [IEEE-STD-610.12]
portability
The ease with which a system or component can be transferred from one hardware or software environment to another. [IEEE-STD-610.12]
**preliminary design**
The process of analyzing design alternatives and defining the architecture, components, interfaces, and timing and sizing estimates for a system or component. See also: detailed design.
**procedure**
A written description of a course of action to be taken to perform a given task. [IEEE-STD-610.12]
**process**
A sequence of steps performed for a given purpose; for example, the software development process. [IEEE-STD-610.12]
**process control (as in management)**
The direction, control and coordination of work performed to develop a product. [IEEE-STD-610.12]
**product integration**
The act of assembling individual hardware and software components into a functional whole.
**quality assurance**
A planned and systematic pattern of actions necessary to provide adequate confidence that a product conforms to established technical requirements. [IEEE-STD-610.12]
**reliability**
The ability of a system or component to perform its required functions under stated conditions for a specified period of time. Usually expressed as the mean time to failure. [IEEE-STD-610.12]
**requirements analysis**
(1) The process of studying user needs to arrive at a definition of system, hardware, or software requirements. (2) The process of studying and refining system, hardware, or software requirements. [IEEE-STD-610.12]
**reuse**
Hardware or software developed in response to the requirements of one application that can be used, in whole or in part, to satisfy the requirements of another application.
**safety**
The degree to which the software product minimizes the potential for hazardous conditions during its operational mission.
**security**
The degree to which a software product is safe from unauthorized use.
**software architecture**
The organizational structure of the software or module.
**software life cycle**
The period of time that begins when a software product is conceived and ends when the software is no longer available for use. The software life cycle typically includes a concept phase, requirements phase, design phase, implementation phase, test phase, installation and checkout phase, operation and maintenance phase, and, sometimes, retirement phase. [IEEE-STD-610.12]
**software requirement**
A condition or capability that must be met by software needed by a user to solve a problem or achieve an objective. [IEEE-STD-610.12]
**software requirements specification (SRS)**
Documentation of the essential requirements (functions, performance, design constraints, and attributes) of the software and its external interfaces. [IEEE-STD-610.12]
**system integration**
The act of assembling hardware and/or software components into a deliverable product.
**system requirement**
A condition or capability that must be met or possessed by a system or system component to satisfy a condition or capability needed by a user to solve a problem.
**system testing**
Testing conducted on a complete, integrated system to evaluate the system's compliance with its specified requirements. See also: component testing; integration testing; interface testing; unit testing. [IEEE-STD-610.12]
**target computer (machine)**
The computer on which a program is intended to execute. [IEEE-STD-610.12]
**test specifications**
A document that prescribes the process and procedures to be used to verify that a product meets its requirements (sometimes referred to as a test plan). [IEEE-STD-610.12]
**traceability**
The degree to which a relationship can be established between two or more products of the development process, especially products having a predecessor-successor or master-subordinate relationship to one another. [IEEE-STD-610.12]
**unit**
(1) A separately testable element specified in the design of a computer software component. (2) A logically separable part of a computer program. (3) A software component that is not subdivided into other components. [IEEE-STD-610.12]
**unit testing**
Testing of individual hardware or software units or groups of related units. See also: component testing; integration testing; interface testing; system testing. [IEEE-STD-610.12]
**Title:** A Proposed Taxonomy for Software Development Risks for High-Performance Computing (HPC) Scientific/Engineering Applications
**Authors:** Richard P. Kendall; Douglass E. Post; Jeffrey C. Carver; Dale B. Henderson; & David A. Fisher
**Performing Organization:** Software Engineering Institute, Carnegie Mellon University, Pittsburgh, PA 15213
**Funding Number:** FA8721-05-C-0003
**Abstract:**
Because the development of large-scale scientific/engineering application codes is an often difficult, complicated, and sometimes uncertain process, success depends on identifying and managing risk. One of the drivers of the evolution of software engineering, as a discipline, has been the desire to identify reliable, quantifiable ways to manage software development risks. The taxonomy that follows represents an attempt to organize the sources of software development risk for scientific/engineering applications around three principal aspects of the software development activity: the software development cycle, the development environment, and the programmatic environment. These taxonomic classes are divided into elements and each element is further characterized by its attributes.
|
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a468594.pdf", "len_cl100k_base": 13348, "olmocr-version": "0.1.53", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 71947, "total-output-tokens": 15464, "length": "2e13", "weborganizer": {"__label__adult": 0.00032973289489746094, "__label__art_design": 0.0003104209899902344, "__label__crime_law": 0.0003018379211425781, "__label__education_jobs": 0.0016107559204101562, "__label__entertainment": 5.435943603515625e-05, "__label__fashion_beauty": 0.00017118453979492188, "__label__finance_business": 0.0003859996795654297, "__label__food_dining": 0.0002586841583251953, "__label__games": 0.0006451606750488281, "__label__hardware": 0.0012903213500976562, "__label__health": 0.0004363059997558594, "__label__history": 0.00020325183868408203, "__label__home_hobbies": 9.965896606445312e-05, "__label__industrial": 0.0004093647003173828, "__label__literature": 0.00026488304138183594, "__label__politics": 0.0001920461654663086, "__label__religion": 0.0004444122314453125, "__label__science_tech": 0.013153076171875, "__label__social_life": 7.95125961303711e-05, "__label__software": 0.004680633544921875, "__label__software_dev": 0.9736328125, "__label__sports_fitness": 0.0002684593200683594, "__label__transportation": 0.0003843307495117187, "__label__travel": 0.00014901161193847656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71444, 0.01585]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71444, 0.67386]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71444, 0.92253]], "google_gemma-3-12b-it_contains_pii": [[0, 313, false], [313, 313, null], [313, 838, null], [838, 838, null], [838, 1639, null], [1639, 1639, null], [1639, 4598, null], [4598, 5978, null], [5978, 9549, null], [9549, 9549, null], [9549, 12286, null], [12286, 15158, null], [15158, 18153, null], [18153, 21207, null], [21207, 23430, null], [23430, 26533, null], [26533, 29530, null], [29530, 31815, null], [31815, 35123, null], [35123, 37802, null], [37802, 39557, null], [39557, 42351, null], [42351, 44472, null], [44472, 46748, null], [46748, 49388, null], [49388, 50392, null], [50392, 52720, null], [52720, 55174, null], [55174, 56985, null], [56985, 56985, null], [56985, 58658, null], [58658, 58950, null], [58950, 61261, null], [61261, 64179, null], [64179, 66113, null], [66113, 68342, null], [68342, 70246, null], [70246, 71444, null], [71444, 71444, null]], "google_gemma-3-12b-it_is_public_document": [[0, 313, true], [313, 313, null], [313, 838, null], [838, 838, null], [838, 1639, null], [1639, 1639, null], [1639, 4598, null], [4598, 5978, null], [5978, 9549, null], [9549, 9549, null], [9549, 12286, null], [12286, 15158, null], [15158, 18153, null], [18153, 21207, null], [21207, 23430, null], [23430, 26533, null], [26533, 29530, null], [29530, 31815, null], [31815, 35123, null], [35123, 37802, null], [37802, 39557, null], [39557, 42351, null], [42351, 44472, null], [44472, 46748, null], [46748, 49388, null], [49388, 50392, null], [50392, 52720, null], [52720, 55174, null], [55174, 56985, null], [56985, 56985, null], [56985, 58658, null], [58658, 58950, null], [58950, 61261, null], [61261, 64179, null], [64179, 66113, null], [66113, 68342, null], [68342, 70246, null], [70246, 71444, null], [71444, 71444, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71444, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71444, null]], "pdf_page_numbers": [[0, 313, 1], [313, 313, 2], [313, 838, 3], [838, 838, 4], [838, 1639, 5], [1639, 1639, 6], [1639, 4598, 7], [4598, 5978, 8], [5978, 9549, 9], [9549, 9549, 10], [9549, 12286, 11], [12286, 15158, 12], [15158, 18153, 13], [18153, 21207, 14], [21207, 23430, 15], [23430, 26533, 16], [26533, 29530, 17], [29530, 31815, 18], [31815, 35123, 19], [35123, 37802, 20], [37802, 39557, 21], [39557, 42351, 22], [42351, 44472, 23], [44472, 46748, 24], [46748, 49388, 25], [49388, 50392, 26], [50392, 52720, 27], [52720, 55174, 28], [55174, 56985, 29], [56985, 56985, 30], [56985, 58658, 31], [58658, 58950, 32], [58950, 61261, 33], [61261, 64179, 34], [64179, 66113, 35], [66113, 68342, 36], [68342, 70246, 37], [70246, 71444, 38], [71444, 71444, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71444, 0.09459]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
4b8630ba2476ba62a05a20f5ff29d4da0b0b3e0b
|
An Empirical Study on Challenges of Application Development in Serverless Computing
Jinfeng Wen†
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
jinfeng.wen@stu.pku.edu.cn
Zhenpeng Chen†
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
czp@pku.edu.cn
Yi Liu
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
liuyi14@pku.edu.cn
Yiling Lou
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
yiling.lou@pku.edu.cn
Yun Ma†
Institute for Artificial Intelligence,
Peking University
Beijing, China
mayun@pku.edu.cn
Gang Huang
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
hg@pku.edu.cn
Xin Jin
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
xjinfku@pku.edu.cn
Xuanzhe Liu†
Key Lab of High-Confidence Software Technology, MoE (Peking University)
Beijing, China
xzl@pku.edu.cn
ABSTRACT
Serverless computing is an emerging paradigm for cloud computing, gaining traction in a wide range of applications such as video processing and machine learning. This new paradigm allows developers to focus on the development of the logic of serverless computing-based applications (abbreviated as serverless-based applications) in the granularity of function, thereby freeing developers from tedious and error-prone infrastructure management. Meanwhile, it also introduces new challenges on the design, implementation, and deployment of serverless-based applications, and current serverless computing platforms are far away from satisfactory. However, to the best of our knowledge, these challenges have not been well studied. To fill this knowledge gap, this paper presents the first comprehensive study on understanding the challenges in developing serverless-based applications from the developers’ perspective. We mine and analyze 22,731 relevant questions from Stack Overflow (a popular Q&A website for developers), and show the increasing popularity trend and the high difficulty level of serverless computing for developers. Through manual inspection of 619 sampled questions, we construct a taxonomy of challenges that developers encounter, and report a series of findings and actionable implications. Stakeholders including application developers, researchers, and cloud providers can leverage these findings and implications to better understand and further explore the serverless computing paradigm.
CCS CONCEPTS
• Software and its engineering → Software creation and management; • Computer systems organization → Cloud computing; • General and reference → Empirical studies.
KEYWORDS
Serverless Computing, Application Development, Empirical Study, Stack Overflow
ACM Reference Format:
1 INTRODUCTION
Serverless computing is an emerging paradigm for cloud computing, gaining traction in a wide range of domains including video processing [79, 90], scientific computing [91, 104], machine learning [83, 89], big data processing [108], Internet of things [97], etc. It has been estimated that the market of serverless computing is expected to grow from USD 1.88 billion in 2016 to USD 7.72 billion by 2021 [64]. Moreover, it is predicted that 50% of global enterprises will employ serverless computing by 2025 [63]. The increasing popularity of serverless computing can be attributed to its benign characteristics. Specifically, it allows developers to focus on the application logic, where functions are composed...
and packaged as the format of services (i.e., Function-as-a-Service (FaaS) [77, 92, 96, 105, 106]), thereby freeing developers from tedious and error-prone infrastructure management like load-balancing, auto-scaling, fault tolerance, operational monitoring, etc. Moreover, it reduces the cost as developers pay for only the actual function executions. What is more, serverless computing also brings great benefits for cloud providers as it allows them to better utilize resources [92]. Therefore, major cloud providers have rolled out their serverless platforms, such as AWS Lambda [61], Microsoft Azure Functions [62], and Google Cloud Functions [65]. There are also increasing open-source implementations available for serverless computing like OpenWhisk [70] and OpenFaaS [69].
Given the popularity of serverless computing, there is a lot of room that can be explored by researchers and developers. Researchers have conducted a series of studies [96, 103, 107, 110] to compare the features, architectures, and performance properties, among different serverless platforms, in order to understand their differences and derive guidelines for choosing the most suitable platform for a given application scenario. Furthermore, since current serverless platforms have several shortcomings such as high startup time and limited communication bandwidth, recent work [77, 90, 99] has proposed new architectures and solutions to alleviate or eliminate them. Developers have also paid attention to the development of serverless computing based applications (in short of serverless-based applications). The specific programming challenges that developers encounter when developing serverless-based applications, e.g., the design, implementation, and deployment of serverless-based applications, configurations of related resources and environments, networking, etc., are frequently asked on developers’ Q&A forums [1–7]. However, to the best of our knowledge, these challenges have not been well studied.
To bridge the knowledge gap, we perform the first comprehensive study to identify challenges in developing serverless-based applications from the developers’ perspectives. Such a study is timely and valuable since it can aid developers in avoiding common pitfalls and make researchers and cloud providers better positioned to help developers develop serverless-based applications in a more targeted way. To this end, we mine and analyze the relevant questions from a variety of developers on Stack Overflow (SO), which is a popular Q&A forum for developers to seek advice from peers when they have programming issues [87]. Specifically, we collect 22,731 SO questions related to serverless computing to answer the following three research questions.
**RQ1 (Popularity trend):** What is the popularity trend of serverless computing among developers? Via quantitative analysis, we find that serverless computing is gaining increasing attention on Stack Overflow, demonstrating its rising popularity and the timeliness and the urgency of our study.
**RQ2 (Difficulty level):** How difficult is serverless computing for developers? To answer this question, we explore the difficulty of developers answering questions related to serverless computing. Results show that these questions are more difficult to answer than those related to other challenging topics in software engineering, which motivates us to further identify the specific challenges behind serverless computing.
**RQ3 (Taxonomy of challenges):** What specific challenges do developers encounter when developing serverless-based applications? To identify the challenges, we randomly sample 619 relevant SO questions for manual examination. For each question, we qualitatively extract the challenges behind it. Finally, we construct a taxonomy consisting of 36 categories, linked to challenges in developing serverless-based applications. It indicates that developers face a wide spectrum of challenges in serverless computing, covering conceptual questions, version control, programming language support, database connection, resource configuration, security, etc. Based on the taxonomy, we summarize a series of findings and actionable implications for developers, researchers, and cloud providers.
In addition, we offer the scripts and the dataset used in this study1 as an additional contribution to the research community for other researchers to replicate and build upon.
2 BACKGROUND
Cloud computing has become a widely adopted paradigm for the delivery of computing services via the Internet. It has various forms, including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), Software as a Service (SaaS), etc. They are built on top of each other and form a “cloud computing stack”, on which each layer gradually relieves the tedious and error-prone infrastructure management, e.g., load balancing and auto-scaling. Serverless computing currently is the ultimate paradigm of cloud computing. In this paradigm, it introduces opportunities for software development. Specifically, developers can focus on their own application logic and save cost without the need for cloud computing expertise. The function becomes the basic unit in serverless computing. Developers write only the function with a specific event trigger (e.g., adding a file into the cloud storage), package and upload their code, and specify the required environment (e.g., language runtime, memory). Serverless platforms provide sandboxing environments (virtual machines or containers) to host functions, and automatically deal with scalability, fault tolerance, and other runtime issues. Different from traditional cloud computing, where developers often need to continuously manage and run servers and pay for them, such a programming paradigm abstracts away most operational tasks and simplifies the application development on the cloud. Meanwhile, its storage and computation scale separately, and are provisioned and priced independently.
However, this new programming paradigm changes the way of traditional software development and may introduce new challenges for developers. First, inherent limits of serverless computing prevent the migration from serverful applications [83, 88, 92]. For example, serverless computing lacks an efficient communication channel among functions, and has restricted resources (e.g., short execution time, confined memory size). Second, existing serverless platforms lack a unified programming framework and rich support tools, making it more difficult to develop serverless-based applications [92, 94]. For example, due to the lack of support tools, debugging and testing serverless-based applications are more challenging than serverful applications for developers. Last but not least, developers have to follow the programming model of serverless computing, with special attention to the design, implementation and deployment of serverless-based applications, configurations of resources and environments, processing of events, etc. [88, 94].
1https://github.com/WenJinfeng/FSE21-Dataset_Script
These challenges may affect the developers’ practice, thereby reducing their enthusiasm for application development on the cloud. Thus, it is essential to understand the challenges in developing serverless-based applications, which can improve the development efficiency of developers, give actionable implications to researchers, and boost the usefulness of serverless platforms.
We briefly introduce the development process of serverless-based applications. Generally, to help developers develop better, serverless platforms provide local development tools, e.g., Command-Line Interfaces (CLIs), Software Development Kits (SDKs), etc. Moreover, some third-party tools like Serverless Framework [72], Local Stack [67] also emerge to allow developers to build and deploy their applications. Leveraging these development tools, the development process can be divided into five stages as shown in Figure 1.
Developers can have two cases for application development, i.e., (i) they develop new serverless-based applications from scratch, and (ii) they migrate legacy applications to serverless platforms to simplify the development or improve performance. For the first case, developers care about how to design the application functionality. For the second case, developers mainly take into account the migration design issues of existing legacy applications. They are called Application Design. After application design, developers configure the environment related to serverless computing to develop functions (called Environment Configuration). What is more, if functions require additional resources like compute and storage, developers also need to configure these resources and the corresponding permissions for functions leveraging the cloud console or a specific template. This configuration way can be viewed as Low-Code Development [68], which is performed through graphical user interfaces or configuration operation instead of traditional hand-coded programming. After accomplishing the required configurations, developers can focus on the code implementation of applications (called Application Implementation). Developers confirm the correctness of applications, then deploy applications to run on serverless platforms through the packaging way (called Application Deployment). Except for the above five stages, developers also need to consider Non-Functional Properties, e.g., performance, security and version control. These properties can be involved in one or more of the development stages. For instance, performance or security is considered in the low-code development and application implementation. Thus, non-functional properties are vital for the development of serverless-based applications.
3 METHODOLOGY
To understand the challenges that developers encounter when developing serverless-based applications, we follow previous studies [76, 78, 80, 95, 100, 109, 111] to collect and analyze the relevant questions posted on SO, where developers often seek technical assistance on unsolvable issues. In Figure 2, we show an overview of the methodology of our study.
Figure 2: An overview of the methodology.
Step 1: Download SO dataset. To collect questions related to serverless computing, we first download the entire SO dataset $S_{all}$ from the official Stack Exchange Data Dump [73] on December 9, 2020. The SO dataset includes 20,511,138 SO questions from July 31, 2008, to December 8, 2020. For each question, the metadata includes its identifier, creation date, body, title, answers, one to five tags that represent its topics, etc. In addition, the developer who posts a question can mark an answer as an accepted answer to indicate that it works for the question.
Step 2: Extract relevant questions. To collect serverless computing related questions from $S_{all}$, we follow previous work [80, 84, 95] to first construct a set of tags related to serverless computing and then extract questions tagged with at least one of these tags. The detailed procedures are as follows.
First, we use $T_{ini} =$ (“serverless”, “faas”) as our initial tag set, since this study focuses on serverless computing (also known as “FaaS” [77, 92, 96, 105, 106]).
Second, we extend the initial tag set by extracting all the tags of questions whose tags match at least one tag in $T_{ini}$ (denote these questions as $S_{cand}$), and refine the extended tag set (denoted as $T_{cand}$) by keeping tags that are significantly relevant to serverless computing and excluding others. Specifically, we follow previous work [80, 109] to use two heuristics $\mu$ and $\nu$ to measure the significance and relevance of a tag $t$ in $T_{cand}$:
\[
\text{(significance)} \quad \mu = \frac{\# \text{of questions with tag } t \text{ in } S_{cand}}{\# \text{of questions in } S_{cand}} \tag{1}
\]
\[
\text{(relevance)} \quad \nu = \frac{\# \text{of questions with tag } t \text{ in } S_{cand}}{\# \text{of questions with tag } t \text{ in } S_{all}} \tag{2}
\]
A tag $t$ is significantly relevant to serverless computing if its $\mu$ and $\nu$ are higher than the specific thresholds. To avoid omitting relevant tags, we employ the lowest thresholds used by previous studies [80, 95], and only the tags whose $\mu$ is higher than 0.005 and whose $\nu$ is higher than 0.05 are kept in $T_{cand}$.
Finally, the first two authors jointly examine each candidate tag in $T_{cand}$ to filter out tags that are not related to serverless computing. As a result, the final tag set $T_{final}$ consists of 13 tags, including “serverless”, “faas”, “serverless-framework”, “aws-serverless”, etc.
“openwhisk”, “aws-lambda”, “aws-sam”, “aws-sam-cli”, “serverless-architecture”, “serverless-offline”, “vercel”, “serverless-plugins” and “localstack”. We extract 22,731 questions tagged with at least one of the 13 tags as the relevant questions (denoted as $S_{eq}$).
**Step 3: Determine popularity trend (RQ1).** To analyze the popularity trend of the topic of serverless computing, we follow previous work [76, 78, 80, 81, 84, 100, 109, 111] to calculate the number of questions and users related to serverless computing per year. Since the concept of serverless computing has attracted widespread attention through AWS Lambda from 2015 [92], the metrics are calculated based on $S_{eq}$ for each of the past six years, i.e., from 2015 to 2020. Section 4 answers RQ1.
**Step 4: Determine difficulty level (RQ2).** To measure the difficulty level of answering questions related to serverless computing, we follow previous work [75, 76, 78, 80, 84, 100, 109, 111] to adopt two metrics, including the percentage of questions with no accepted answer (“%no acc.”) and the median response time needed to receive an accepted answer (“resp time”). We calculate the two metrics based on $S_{rel}$. In addition, we calculate the average difficulty level of SO questions (i.e., $\%no acc.$ and resp time for $S_{rel}$) as the baseline. For the first metric, we use the proportion test [98] to examine the statistical significance of comparison. Proportion test is used for testing the null hypothesis that the proportions in several groups are the same [71], and thus appropriate for the comparison in $\%no acc.$ [84]. For the second metric, we calculate the median value of response time to receive an accepted answer for both serverless-related questions (i.e., $S_{rel}$) and SO questions (i.e., $S_{all}$). Specifically, for each question, we extract the creation timestamps of this question and the corresponding accepted answer to calculate the time span between them as the response time. Section 5 answers RQ2.
**Step 5: Construct taxonomy of challenges (RQ3).** To analyze specific challenges that developers encounter and construct the taxonomy of challenges, we follow previous studies [85, 95] to use questions that have an accepted answer, ensuring that we consider only questions with a confirmed solution. As a result, 8,751 questions in $S_{rel}$ are kept. Due to the large sample size, manually labeling all questions is time-consuming and infeasible. Following previous work [74], we randomly select a statistically significant sample ensuring a 99% confidence level ± 5% from 8,751 questions. As a result, 619 questions constitute the taxonomy dataset of our study, and this dataset size is larger than the one in existing work [82, 85, 112] that needs also manual analysis. Next, we illustrate the process of constructing the taxonomy of challenges.
First, we randomly sample 70% of 619 questions to construct the initial taxonomy of challenges. We adopt an open coding procedure [102] to analyze the sampled questions, in order to inductively create categories and subcategories of our taxonomy in a bottom-up way. The first two authors, both of whom have two years of cloud/serverless computing experience, jointly participate in the taxonomy construction. They read the sampled questions over and over again, in order to be acquainted with them. In this process, all the elements of each question, including the title, body, code snippets, comments, and even URLs contained in questioners and answerers, are taken into account for careful inspection.
The detailed procedure of open coding is as follows. Questions not related to serverless computing are labeled as False positives, and thus not included in our taxonomy. Regarding the remaining questions, the authors give short phrases to represent the challenges that developers encounter. Specifically, some questions are raised without any attempts, and they are mainly in the form of “how”, e.g., “How to use request module in node.js lambda” [8]. For such questions, the authors often can clearly understand the challenges from the question description. Additionally, some questions describe the faults or unexpected results that developers are trying development practices. For such questions, the authors identify their causes as the challenges. For instance, when the developer posts an error message about the implementation of asynchronous functions [5], the authors find that the error is caused due to mixing asynchronous statements through checking the question descriptions, comments, and answers. Thus, the authors consider assigning asynchronous processing to be the challenge behind this question.
Second, the authors continue to group similar short phrases into categories and establish a hierarchical taxonomy of challenges. Regarding the grouping process, the authors iterate repeatedly between categories and questions. If questions are related to multiple categories, they are assigned to all related categories. In addition, if the authors have conflicts in labeling questions, a third arbitrator is introduced to discuss and resolve these conflicts. Particularly, the third arbitrator has seven years of cloud computing experiences. Through such a rigorous procedure, all questions come to an agreement and the final label results (i.e., the initial taxonomy) are confirmed by all the participants.
Finally, we perform reliability analysis and extended construction of the taxonomy of challenges. Based on the initial taxonomy, the remaining 30% questions are independently labeled by the first two authors to conduct reliability analysis. Each question is marked with False positives or the leaf categories of our taxonomy. Questions that cannot be classified into the current taxonomy are placed to a new category named Pending. We use Cohen’s Kappa (κ) [86] to calculate the inter-rater agreement during the independent labeling. The value of the inter-rater agreement is 0.836, which indicates an almost perfect agreement [93] and reliable labeling procedure. Existing conflicts are then discussed and resolved by the first two authors and the third arbitrator. In addition, questions in Pending category are also identified with the help of the third arbitrator, and some new categories are added to our taxonomy. As a result, five new leaf categories are added and all questions in Pending can be assigned into our taxonomy.
To sum up, for the 619 sampled questions, 4 questions are marked as False positives and 17 questions are assigned into two categories. As a result, 632 samples are contained in the final taxonomy. Section 6 answers RQ3.
### 4 RQ1: POPULARITY TREND
Figure 3 represents the popularity trend of serverless computing in terms of the number of questions and users on SO. We find that this topic has been gaining increasing attention since 2015, demonstrating the timeliness and urgency of this study.
For the topic of serverless computing, questions and users increase in a steady trend as shown in Figure 3. Since Amazon first
rolled out AWS Lambda in November 2014\(^2\), the concept of serverless computing has drawn widespread attention. We observe that both the number of questions and users related to serverless computing in 2016 increased by more than 340% compared to those of 2015. In addition, we calculate the annual growth rate of the SO dataset as the baseline. We find that the growth rate of SO questions and users from 2015 to 2020 ranges from 6% to 22%, while the growth rate of questions and users related to serverless computing ranges from 47% to 380%.

**Finding 1**: The topic of serverless computing is gaining increasing attention from developers, demonstrating the timeliness and urgency of this study.
### 5 RQ2: DIFFICULTY LEVEL
Table 1 shows metrics %no acc. and resp time of serverless-related questions and all SO questions. The values of %no acc. of serverless-related questions and all SO questions are 61.5% and 48.3%, respectively. The significance of this difference is ensured by the result of the proportion test (\(\chi^2 = 1.577, df = 1, p\text{-value} < 2.2e-16\)), indicating that questions related to serverless computing have a larger percentage of questions with no accepted answer. In addition, the values of resp time of serverless-related questions and all SO questions are 190 and 35 minutes, respectively. It implies that questions related to serverless computing need longer time to receive an accepted answer.
Based on the table, we can find that it is more challenging to answer questions related to serverless computing than other SE topics. In particular, 61.5% of questions related to serverless computing have no accepted answers, which is remarkably more frequent than other SE topics, such as Web development (i.e., 48.0% [78]), concurrency (i.e., 43.8% [76]), and mobile (i.e., 55.0% [100]). In addition, it often takes non-trivial time to respond questions related to serverless computing (i.e., 190 min), which is substantially more time-consuming than other SE topics, such as Web development (i.e., 19 min [78]), concurrency (i.e., 42 min [76]), mobile (i.e., 55 min [100]). Since answers are often edited on SO, to make our results more reliable, we also calculate the response time as the time span between the creation time of a question and the last editing time of its accepted answer. The obtained result is 242 min, which is longer than our previous result (190 min). In summary, answering questions related to serverless computing needs longer time. Long answering time could sometimes be caused by lacking experts [78]. However, the response time to receive an accepted answer is still a well-adopted metric for difficulty, since lacking experts indicates that a large proportion of developers have not yet mastered serverless-related development skills, making these questions difficult to answer. Overall, our results demonstrate the necessity of identifying the challenges behind questions related to serverless computing.
**Finding 2**: Questions related to serverless computing are more challenging to answer than the average level of all SO questions and other topics related to software development tasks, e.g., Web development, concurrency, and mobile.
### 6 RQ3: TAXONOMY OF CHALLENGES
Figure 4 illustrates the hierarchical taxonomy of challenges in developing serverless-based applications. Nodes are in descending grey-level along with their depth in the hierarchy (e.g., leaf nodes are in white). Each leaf node represents a category and its non-white parent node that consists of multiple categories is an inner category. For example, Performance (G.6) is an inner category that can be further divided into four leaf categories: Execution Latency (G.6.1), Resource Utilization (G.6.2), Cold Startup (G.6.3), and Throughput (G.6.4). The percentage for samples related to each category is in the parentheses. In total, our taxonomy consists of 11 inner categories and 36 leaf categories. We observe that when developing serverless-based applications, developers encounter problems in a broad spectrum of aspects, which indicates the diversity of challenges related to serverless computing. We next describe and exemplify each category by groups, and report our findings and implications for developers, researchers, and cloud providers.
**Finding 3**: The challenges that developers encounter have a broad spectrum of 36 leaf categories ranging from Conceptual Questions to Version Control, Programming Language Support to Database Connection and Resource Configuration to Security.
#### 6.1 General Questions (A)
General questions represent the challenges involving no specific implementation details, which are often proposed by developers when they are looking for primary knowledge related to serverless computing. Our results show that 7.9% of challenges belong to general questions. We then discuss several categories in detail as follows.
---
\(^2\)https://docs.aws.amazon.com/lambda/latest/dg/lambda-releases.html
Conceptional Questions (A.1) This category represents questions about basic concepts or background knowledge of serverless computing, such as how AWS Lambda works [1] and the difference between functions in idle state and not [9]. Answerers mainly handle these questions by providing documentation-like information or translate the jargon-heavy documentation into case-specific guidance phrased in a developer-friendly way. In our taxonomy, 5.5% of the total challenges appear in conceptional questions. It illustrates that developers are eager to gain a comprehensive understanding of concepts related to serverless computing.
Platform/Tool Support (A.2) Developers wonder whether a certain serverless platform or development tool can satisfy their specific requirements. Specifically, for serverless platforms, developers may have concerns about hard restrictions (e.g., memory [10]) or task types (e.g., machine learning [11]). For development tools like Serverless Framework [72], developers often ask whether certain features, e.g., user authentication [12], are integrated with them.
Cloud Service Comparison (A.3) Developers may have challenges in understanding and choosing cloud services with similar functionality. For example, it is often confusing for developers to choose an appropriate database service in their functions, since there are often various database services, such as Amazon DynamoDB [58] and RDS [59].
Discussion and implication: Our results show that developers encounter frequent challenges related to the basic concepts before actual practices. We further analyze the conceptual questions and find that there are mainly three aspects of understanding, i.e., underlying working mechanism, proprietary terms, and platform-specific restrictions. Developers need to spend non-negligible time on learning the required knowledge, especially proprietary terms and platform-specific restrictions, and think more about the working mechanism of serverless platforms. Questions of the underlying working mechanism are asked frequently in the way of how it works. Thus, cloud providers can supplement more organized documents to help developers search them and alleviate concerns.
With the popularity of machine learning and deep learning, more and more applications need to deal with data-intensive and computation-intensive tasks. However, due to inherent restrictions of serverless platforms (e.g., memory, storage, package size, and execution time), both data-processing applications with a large database and machine-learning applications with large libraries like TensorFlow cannot be handled normally. Thus, developers have to indirectly implement such serverless-based applications with other strategies that may increase the development complexity. Specifically, to avoid transmitting a large volume of data through the network, developers need to use other storage services to save query results [10]. They also need to pay attention to keep an efficient database connection to avoid exceeding the execution time limit. In addition, machine-learning applications may run for a long time with high memory demands, whose cost will skyrocket. The answerer suggests “you will be better off with something like EC2 and ECS” [11]. Thus, such computation-intensive applications may be more suitable to use the “traditional” IaaS paradigms such as virtual...
machines or containers compared to serverless computing. Moreover, existing serverless platforms do not support GPU well, which can prevent fast-growing deep-learning tasks. If developers hope to enjoy advantages in simplifying the application development, cloud providers need to lift some restrictions of serverless platforms to support various workloads. Currently, serverless-based applications are most commonly used for running short-lived, transient, and even emergent tasks with low data volume and hardware capacity.
6.2 Application Design (B)
The challenges of application design account for 16.3% of the total challenges. On the one hand, developers need to develop a serverless-based application from scratch, so they ask questions about specific functionality design in a serverless way. On the other hand, developers may have legacy applications, and want to migrate them to serverless platforms, in order to simplify the development, improve performance, and save cost. Thus, migration-related questions are issued. In addition, it is inevitable to ask questions about programming language support in this stage. Detailed leaf categories are illustrated as follows.
**Functionality Design (B.1)** This category covers design-related challenges for implementing specific functionalities during the development of a new serverless-based application. They are often described with the key words “best approach”, such as “What is the best approach for generating thumbnails [...]?” [2]. Answerers handle these questions by providing specific design steps or alternative options.
**Application Migration (B.2)** This category describes challenges in migrating from legacy applications to serverless-based applications. Developers wonder whether or how legacy applications can be migrated and run on serverless platforms, e.g., “Is it possible to run Beautiful Soup [...] on AWS Lambda?” [13] and “How can run Rails web app in AWS Lambda server” [14]. In addition, developers may need to migrate existing serverless-based applications due to the platform update or development tools update, so they may ask how to migrate integrated resources and services in Serverless Framework from version 0.5 to 1.0 in a safe manner [15].
**Programming Language Support (B.3)** This category covers challenges about the programming language support. They are often considered in the situation of constructing functions with different programming languages, e.g., “AWS lambda with both python and java language support” [16]. Developers also prefer to develop functions with the daily used language, e.g., creating Openwhisk actions with Swift [17].
**Finding 5:** The third-largest category in proportion (i.e., 16.3%) covers the challenges appearing in the Application Design stage. The majority (67.0%) of these challenges are thrown with Functionality Design.
**Discussion and implication:** In the application design stage, developers frequently ask Functionality Design-related questions. It shows that developers look forward to obtaining the guidance of best practices or examples for their requirements. Cloud providers should provide more practical function templates and detailed instructions to help developers construct their functions more easily and quickly. We further observe that the most questions (about 90%) discuss the functionality design integrating other services that are provided by the same cloud providers. This is a common pattern for developing serverless-based applications, since integrating such services can simplify the development of serverless-based applications and improve their performance. However, it can be challenging for developers to design functions with such a large number of cloud services. Thus, both researchers and cloud providers can summarize a standard design specification to help developers better construct their functions with cloud services. For example, if cloud providers can maintain a function store, it may be convenient for developers to reuse existing functions to construct their serverless-based applications. In addition, it can further make the serverless-based application development more compositional in nature.
With the popularity of serverless computing, the trend of migrating legacy applications to serverless platforms may also increase. Thus, the design issues arising from application migration need to be solved urgently. Both researchers and cloud providers can pay more attention to the migration approach of legacy applications to guide developers in practice. For example, researchers can identify and refactor specific APIs with dynamic and static analysis. Cloud providers can further support more mostly-used frameworks (e.g., Web frameworks like Spring) so that developers directly run their legacy applications on serverless platforms.
With serverless computing, it is easier for developers to develop their applications with different languages (as known as hybrid programming). In a collaborative team, different developers can construct their functions with their own familiar languages, and different functions will be hosted in a dedicated instance and communicate with each other. However, not all languages are well supported. Cloud providers can further support more languages and optimize their run-time performance. Every coin has two sides. It is notable that hybrid programming can also increase the complexity of the serverless-based application development, especially for testing and debugging, which should be addressed by researchers with more advanced code analysis techniques.
6.3 Environment Configuration (C)
Developers install and configure local environments for further development. 5.9% of the total challenges are related to the environment configuration, and detailed leaf categories are explained as follows.
**Tool Installation (C.1)** This category represents challenges in installing development tools (e.g., AWS CLIs, Azure CLIs, and Serverless Framework) for serverless-based applications. When developers fail to install Serverless Framework, they may ask the question like “Unable to install serverless framework on macosx” [18]. Based on our observations from all answers and comments, we find that most installation problems are caused by incorrectly configuring system variables and missing specific dependencies.
**Tool Usage (C.2)** This category represents challenges in using related development tools. They often happen when the command parameters are used incorrectly. For example, developers fail to update the value of EventSourceArn of a Lambda function with an update command, which is caused by the incorrectly configured parameter “EventSourceArn” in the update command [19].
Version Compatibility (C.3) This category refers to challenges in dealing with certain versions of tools. Specifically, we find that commands may not run correctly due to the inherent bugs in certain versions [20] or the incorrect usage of package versions [3]. For example, developers ask if the command "project" is not found for Serverless Framework [3]. After checking answers, the solution is to use the 0.5.x version of Serverless Framework instead of the 1.x version, because the 1.x version implements the "services" command to replace the "project" command. Therefore, ensuring version compatibility is a prerequisite that cannot be ignored in the environment configuration.
**Finding 6**: The challenges of development environment configuration (5.9%) include tool installation and usage, and version compatibility. Version Compatibility is dominating, accounting for 40.5% of the challenges in Environment Configuration.
Discussion and implication: In the environment configuration stage, how to install the appropriate version is the main concern for developers. Based on our observations, developers may use incorrect versions of tools, and endure inherent bugs of certain versions. The rapid evolution of development tools is making it challenging for developers to install the appropriate version, not only in the serverless-based application development, but also in many other software tasks, e.g., deep learning deployment [84] and software build [95]. Therefore, it is necessary for researchers to deliver more consistency detection techniques for version compatibility checking.
6.4 Low-code Development (D)
The significant feature of serverless computing is to represent infrastructure as code [66] that simplifies the management (i.e., creation and modification) of resources. Developers use the cloud console or a definition file written in JSON or YAML format to integrate with needed resources, which is known as low-code development [68]. This category covers challenges about low-code development and accounts for 19.6% of the total challenges. Detailed leaf categories are illustrated as follows.
**Provider/Function Configuration (D.1)** This category refers to challenges about configurations of cloud providers or functions. They often occur during the event and permission configurations. For the event configuration, the event source can be Amazon API Gateway [57], with which functions can be invoked once receiving an HTTPS request. In our study, we find that developers encounter request-related problems like "defining the request mapping template in serverless.yml" [21]. Additionally, the event source may come from other services (e.g., storage service like Amazon S3 [60]), which will be triggered when an object is added to a bucket on S3 [4]. Compared to developing a monolithic application, developers often need to specify the permissions of a function, such as the permission of accessing the network, and permission of accessing other services. If not correctly configured, the function will fail to access the target service due to access denied [22]. In addition, there are also some configuration challenges, such as choosing the appropriate region of cloud providers [23], specifying the function timeout [24], etc. Interestingly, we also find that even a small mistake in the definition file, e.g., wrong indentation [25] and typos of specific terms [26], can result in catastrophic consequences. However, there are few effective tools to deal with such urgent problems.
**Resource Configuration (D.2)** This category represents challenges about the configuration of integrated resources in serverless-based applications. Developers configure specifications (e.g., database name, table information, etc.) when integrating other cloud services (e.g., Amazon DynamoDB) [27]. Other functions can also be referenced as resources to compose a complicated serverless-based application [28].
**Custom Configuration (D.3)** In addition to the above configurations, developers may have personalized requirements, i.e., custom configuration. For example, developers try to specify a new response template with HTTP status to a redirect web page [29]. However, they find "I can do it manually with AWS lambda user interface but I need to do it with serverless framework version v1." It also reflects the challenges in writing the configuration file compared to the convenient user interface provided by cloud providers.
**Finding 7**: The challenges on Low-Code Development account for the second-largest percentage (i.e., 19.6%) of the total challenges. Provider/Function Configuration is the top category, accounting for 56.5% of the challenges in Low-Code Development.
Discussion and implication: Low-code development is a feature of developing serverless-based applications, effectively simplifying the integration of cloud services and management of functions. However, the related challenges even account for 19.6%, which is the second-largest category in proportion. Answerers mainly solve these problems by providing code snippets of specific configurations or modifying existing errors. It shows that developers lack a comprehensive configuration specification to guide them, and they are in urgent need of support tools. For cloud providers, they can provide more instructions and examples, especially the event and permission settings, to satisfy various configuration requirements. For framework developers, they can abstract the underlying differences of different serverless platforms, and provide a unified standard so that developers do not need to spend much time on browsing tedious documentations. For researchers, they can summarize the common issues of low-code developments, and extend existing code analysis tools and validation tools to help developers better find the bugs and mistakes of configurations.
6.5 Application Implementation (E)
Developers focus on the application logic without management underlying infrastructure in serverless computing. Any application code written by developers can be executed on serverless platforms. In our taxonomy, the challenges asked by developers most frequently are application implementation accounting for 35.4% of the total challenges. There are 3 inner categories (i.e., E.2, E.4 and E.6) and 11 leaf categories. Detailed categories are explained as follows.
**Functionality Implementation (E.1)** This category refers to challenges in the implementation of specific functionalities. We find that there are two types in this category, including both serverless-unrelated and serverless-related functionality implementations. For example, a developer makes a mistake in reading a CSV file [30], and it is a serverless-unrelated functionality implementation problem.
Another example is a serverless-related functionality implementation like “updating AWS S3 object metadata through boto3” [31].
**Package Integration (E.2)** This category represents challenges encountered in using third-party libraries in functions. Specifically, when developers prepare to use the method of a certain library, they must import its package beforehand but may encounter import-related challenges (E.2.1). They are mainly in the import of external libraries [32], which is generally solved through modifying the package path. After importing required packages, especially when using database services, developers need to establish a connection in advance [33], and challenges on configuring and connecting such services (E.2.2) occur. Besides, developers may be incorrect to use methods of third-party libraries (E.2.3).
**Asynchronous Processing (E.3)** This category covers challenges in dealing with asynchronous activities in a function. Due to the event-driven nature of serverless computing, functions written in JavaScript often apply asynchronous callbacks with `async`, `await`, and `promise`. However, many developers fail to correctly use these features to construct their functions [34].
**Data Processing (E.4)** This category covers questions about data processing. Converting raw data into the required format (E.4.1) is an important factor so that functions can successfully resolve data from triggered events [35]. Meanwhile, formatting the result (E.4.2) is critical so that users can obtain the correct response [36]. There are also some incorrect data processing problems caused by syntax errors (E.4.3) [37].
**Debugging and Testing (E.5)** This category represents challenges on debugging and testing of functions. Most questions are about debugging and they are often described in the format of “how to debug” [38].
**Function Invocation (E.6)** Developers can incorporate multiple functions in a single serverless-based application, and these functions can be invoked internally. This category represents challenges in invoking functions with different invocation methods and parameters. Most functions are configured to be triggered by Amazon API Gateway, so most challenges are related to supporting various HTTP methods (E.6.1), e.g., “POST” and “GET” [39]. Other challenges are to transmit data parameters to functions (E.6.2), e.g., JSON-format payload [40] or binary data [41].
**Finding 8:** Most (i.e. 35.4%) of the challenges occur in the *Application Implementation* stage, covering a wide spectrum of 11 leaf categories. *Package Integration* and *Functionality Implementation* are the top two categories, accounting for 30.8% and 21.4% of challenges in this stage, respectively.
**Discussion and implication:** Our results show that package integration is the most common problem in the application implementation stage. Especially, developers have to pay more attention to keeping the connection of database service in order to conform to the timeout limit of functions. Such problems may even not throw any exceptions [42], which are difficult to detect and debug for developers. For cloud providers, they can further improve their log/monitoring services (e.g., Amazon CloudWatch) to provide detailed logs and descriptions of error information, which can help developers better locate their bad code. For researchers, they can extend the existing analysis and diagnosis technologies with consideration of characteristics of serverless-based applications. Meanwhile, the unified programming model also needs to be studied to simplify developers’ development issues on multiple different serverless platforms.
We also find that another big bottleneck is functionality implementation. In this category, the first two authors manually check these posts and find that serverless-unrelated and serverless-related functionality implementations account for 33.3% and 66.7%, respectively. It illustrates that the serverless computing paradigm increases the programming difficulty of developers, although reducing most operational tasks. On the one hand, cloud providers can further simplify the programming model for serverless-based applications. On the other hand, cloud providers can also provide mature development and debugging tools to assist developers’ development. The challenge of debugging and testing tools is also found in the category (E.5) of our taxonomy. Traditional tools are not fully suitable for serverless-based applications, and new approaches are needed. Additionally, developers should avoid common pitfalls obtained from asynchronous processing and data processing, e.g., use of asynchronous statements, data parsing of the event, and format setting of the response, etc.
### 6.6 Application Deployment (F)
After implementing serverless-based applications, developers can deploy their applications to serverless platforms. Developers can package their functions and dependent libraries into a single bundle, and upload them to serverless platforms. Therefore, this category is deployment-related problems, accounting for 4.4% of the total challenges. Detailed leaf categories are explained as follows.
**Procedure (F.1)** This category describes questions about the procedure of a specific deployment, such as whether it is possible to deploy the same package to different cloud providers [43].
**Packaging (F.2)** This category represents challenges in packaging all code and dependent libraries of a serverless-based application. Developers often fail to package all related files in the correct format [44], and may also encounter the problem of exceeding the package size limit.
**Deployment Tool Usage (F.3)** This category refers to challenges in correctly using commands of deployment tools. For instance, the command “sls resources deploy” used by developers is incorrect [45], and instead the command “sls deploy” should be used.
**Finding 9:** Application Deployment is the development stage where developers ask the least questions. It accounts for 4.4% of the total challenges, and contains Procedure, Packaging, and Deployment Tool Usage categories.
**Discussion and implication:** We further analyze Procedure and Deployment Tool Usage categories and find that developers have diverse deployment requirements, e.g., deploying with a specific version, deploying with an environment variable, or deploying the same package to multiple cloud providers, etc. For cloud providers, they can think about how to facilitate various deployment requirements. For example, cloud providers provide a custom deployment template to fill in the necessary and optional information (e.g., version and environment variable), and then apply the deployment tool
to complete the deployment tasks with this template. In addition, for the size limit of the deployment package, researchers can work on more analysis techniques to identify and remove unused code or files to reduce the package size of serverless-based applications.
6.7 Non-functional Properties (G)
Developers may consider some non-functional properties in the development of serverless-based applications. 10.4% of the total challenges are about non-functional properties. Specific categories are introduced as follows.
Network (G.1) A function might integrate with external services (internal or publically hosted Web services, cloud services, databases, etc.) via the network. Thus, challenges related to networking occur, and they are mainly in Virtual Private Cloud (VPC) configuration. Some services can only be accessed by a function under the same VPC. For instance, Lambda functions connect to the Amazon RDS (i.e., a relational database) instances through the public Internet, but it fails due to a wrong VPC configuration [7].
Monitoring (G.2) This category represents questions about monitoring for serverless-based applications, e.g., whether all functions are completed normally [46].
Version Control (G.3) This category is mainly involved with the version management of serverless-based applications. Developers may be looking forward to an update or rollback version for applications [47]. Thus, serverless-based applications require version management like traditional applications using Git.
Cost (G.4) This category covers challenges about the billing model of serverless computing. Although serverless computing charges in a pay-as-you-go manner, there are still some concerns for developers. It is more difficult to predict the cost of a function, such as calculating the cost of the main function for a nested application when multiple functions are orchestrated in the main function [48].
Concurrency (G.5) This category represents questions about dealing with concurrent requests. They are often limited by the inherent concurrency strategy of different serverless platforms, such as concurrency number [49] and execution time [50].
Performance (G.6) This category represents questions about application performance. First, for execution latency (G.6.1), developers try to present a certain strategy to improve the execution efficiency of functions. For example, developers can speed up the date loading and save the network bandwidth by compressing data [51]. Second, for resource utilization (G.6.2), developers find competition between resources, such as I/O and CPU [52]. Third, for cold startup (G.6.3), when an invocation of a function occurs for the first time, this invocation is experiencing a cold startup and creating a function container. This container remains active and available for subsequent invocations for at least a few minutes before it is terminated. Developers often invoke a function periodically to reduce cold startup, i.e., “keeping warm” [53]. Finally, for throughput (G.6.4), developers look for ways to improve throughput, e.g., the read capacity of a database [54].
Security (G.7) Serverless computing hides infrastructure management from developers, but such opacity may increase concerns on security. They are mainly in the endpoint protection of functions [55] and data protection between functions [56]. Answerers mainly solve such questions by applying authentication and encryption on the endpoint and communication.
Finding 10: 10.4% of the total challenges are in Non-Functional Properties covering 10 leaf categories. Networking and Performance (53.0% in total) are the top two categories in Non-Functional Properties.
Discussion and implication: Our results show that two biggest challenges are networking and performance in non-functional properties. Specifically, networking-related challenges are VPC settings. Developers can strengthen the networking knowledge, especially the VPC configuration process. For performance-related challenges, developers expect to improve performance from different perspectives, i.e., execution latency, resource utilization, cold startup, and throughput. Particularly, the performance of serverless platforms is a broad topic in academia. For example, some measurement work [96, 107, 110] has evaluated the performance of different serverless platforms from the execution latency of functions, resource utilization, throughput, etc. Moreover, some studies [77, 99, 103] have minimized cold startup to improve execution efficiency through system optimization or sandboxing design. By comparison, we find that academia and industry have similar focuses in terms of performance. In this situation, researchers can consider improving performance from the perspective of the developer practice, e.g., using data compression to reduce network overhead [51]. In addition, we find that developers ask fewer questions about Performance (2.4%) than Application Implication (35.4%). This observation coincides with the observation of other work [76], i.e., developers ask more about the correctness of their programs than performance.
Under the serverless computing paradigm, the version control and billing model still face new challenges, e.g., the version update and rollback of a project (or development environment or configuration), and cost prediction for function retry. Thus, to promote the use of serverless computing, researchers can design version control tools that conform to this new programming paradigm, and cloud providers try to provide a more user-friendly billing model to reduce the cost of non-real function execution.
7 THREATS TO VALIDITY
In this section, we discuss threats to the validity of our study.
Selection bias of data source. Similar to previous research [76, 78, 80, 95, 100, 109, 111], our work uses SO as the only data source to study the challenges that developers encounter, which may overlook useful insights from other data sources. Thus, we plan to expand our analysis to other data sources in future work, further verifying our findings. Nevertheless, because SO data contains posts from both novices and experts [112], we believe that our findings and implications are still valid.
Construction of tag set. We use a set of tags to extract SO questions related to serverless computing. However, since the chosen thresholds for significance and relevance metrics may omit some tags related to serverless computing, we cannot guarantee the tag set is complete. To mitigate this threat, we adopt the lowest thresholds used in previous work [80, 95] to include as many relevant
tags as possible. Furthermore, we refine the tag set through further manual inspection to ensure the precision.
**Subjectivity of researchers.** In this study, we adopt manual analysis to construct the taxonomy of challenges. The manual analysis may pose threats to the validity of our taxonomy. In order to minimize this threat, the first two authors and an experienced arbitrator discuss and reach an agreement for conflicts. Meanwhile, we calculate the inter-rater agreement as 0.836, which is relatively high and indicates the reliability of our labeling procedure.
**Saturation of taxonomy.** When classifying the remaining 30% of questions, we discover five new categories that are added to the final taxonomy. It may raise the uncertainty about the level of completeness of our taxonomy. However, the number of newly-added categories in this study is smaller than that in previous work [84], and these categories contain few questions (no more than five). Thus, our taxonomy is relatively complete. Meanwhile, the taxonomy is carefully checked by the third arbitrator with seven years of cloud computing experience.
8 RELATED WORK
In this section, we summarize related work of serverless computing as well as empirical studies on challenges that developers encounter in the widely used techniques.
**Studies on serverless computing.** Serverless computing is a new trending paradigm of cloud computing, and lots of related studies have been proposed. First, some work [96, 103, 107, 110] has evaluated different serverless platforms from various aspects. For example, Wang et al. [107] conducted a measurement study to characterize the architectures, performance, and resource efficiency for commercial serverless platforms. Mohanty et al. [96] compared the features and performance of open-source implementations of serverless computing. Second, some work [88, 94] has analyzed the characteristics of serverless-based applications to guide the design of approaches related to serverless computing. Furthermore, some literature reviews have been conducted to understand the gap e.g., Web development, concurrency, mobile, which motivates us to identify the specific challenges behind them. We have manually inspected 619 sampled questions related to serverless computing and constructed a comprehensive taxonomy, including 11 inner categories and 36 leaf categories, representing challenges that developers encounter in developing serverless-based applications. In addition, our study also provide a series of practical findings and actionable implications for developers, researchers, and cloud providers, intending to highlight good practices and interesting research avenues in adopting the serverless computing paradigm.
9 CONCLUSION
Through analyzing SO questions related to serverless computing, we have found that the topic of serverless computing is gaining increasing attention among software engineers. Furthermore, we have demonstrated that questions related to serverless computing are more difficult to answer than other challenging topics in SE, e.g., Web development, concurrency, mobile, which motivates us to identify the specific challenges behind them. We have manually inspected 619 sampled questions related to serverless computing and constructed a comprehensive taxonomy, including 11 inner categories and 36 leaf categories, representing challenges that developers encounter in developing serverless-based applications. Some literature reviews have been conducted to understand the gap e.g., Web development, concurrency, mobile, which motivates us to identify the specific challenges behind them. We have manually inspected 619 sampled questions related to serverless computing and constructed a comprehensive taxonomy, including 11 inner categories and 36 leaf categories, representing challenges that developers encounter in developing serverless-based applications.
ACKNOWLEDGMENTS
This work was supported by the R&D Projects in Key Areas of Guangdong Province under the grant number 2020B010164002, the National Natural Science Foundation of China under the grant number 61725201, the Beijing Outstanding Young Scientist Program under the grant number BJWZYHJ0120191000104, and the PKU-Baidu Fund Project under the grant number 2020BD007.
REFERENCES
An Empirical Study on Challenges of Application Development in Serverless Computing
ESEC/FSE '21, August 23–28, 2021, Athens, Greece
|
{"Source-Url": "https://yilinglou.github.io/papers/SERVE_FSE21.pdf", "len_cl100k_base": 12302, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 44838, "total-output-tokens": 16797, "length": "2e13", "weborganizer": {"__label__adult": 0.0003390312194824219, "__label__art_design": 0.0003180503845214844, "__label__crime_law": 0.00022983551025390625, "__label__education_jobs": 0.0014123916625976562, "__label__entertainment": 7.081031799316406e-05, "__label__fashion_beauty": 0.00016570091247558594, "__label__finance_business": 0.0003972053527832031, "__label__food_dining": 0.0002522468566894531, "__label__games": 0.0005965232849121094, "__label__hardware": 0.0008730888366699219, "__label__health": 0.0003662109375, "__label__history": 0.00028252601623535156, "__label__home_hobbies": 9.369850158691406e-05, "__label__industrial": 0.00023853778839111328, "__label__literature": 0.00028967857360839844, "__label__politics": 0.0001952648162841797, "__label__religion": 0.00033545494079589844, "__label__science_tech": 0.01389312744140625, "__label__social_life": 9.965896606445312e-05, "__label__software": 0.00862884521484375, "__label__software_dev": 0.97021484375, "__label__sports_fitness": 0.0002067089080810547, "__label__transportation": 0.00039505958557128906, "__label__travel": 0.00018274784088134768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72598, 0.03825]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72598, 0.48022]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72598, 0.89389]], "google_gemma-3-12b-it_contains_pii": [[0, 3994, false], [3994, 11085, null], [11085, 16681, null], [16681, 23736, null], [23736, 28792, null], [28792, 32175, null], [32175, 38902, null], [38902, 45691, null], [45691, 52433, null], [52433, 59059, null], [59059, 65804, null], [65804, 65804, null], [65804, 72598, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3994, true], [3994, 11085, null], [11085, 16681, null], [16681, 23736, null], [23736, 28792, null], [28792, 32175, null], [32175, 38902, null], [38902, 45691, null], [45691, 52433, null], [52433, 59059, null], [59059, 65804, null], [65804, 65804, null], [65804, 72598, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72598, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72598, null]], "pdf_page_numbers": [[0, 3994, 1], [3994, 11085, 2], [11085, 16681, 3], [16681, 23736, 4], [23736, 28792, 5], [28792, 32175, 6], [32175, 38902, 7], [38902, 45691, 8], [45691, 52433, 9], [52433, 59059, 10], [59059, 65804, 11], [65804, 65804, 12], [65804, 72598, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72598, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
f4643dc8294d51c10fbabf44007ddfe471662150
|
Applying Machine Learning to Software Fault Prediction
Bartłomiej Wójcicki*, Robert Dąbrowski*
*Institute of Informatics, University of Warsaw
bartwojcicki@gmail.com, r.dabrowski@mimuw.edu.pl
Abstract
Introduction: Software engineering continuously suffers from inadequate software testing. The automated prediction of possibly faulty fragments of source code allows developers to focus development efforts on fault-prone fragments first. Fault prediction has been a topic of many studies concentrating on C/C++ and Java programs, with little focus on such programming languages as Python.
Objectives: In this study the authors want to verify whether the type of approach used in former fault prediction studies can be applied to Python. More precisely, the primary objective is conducting preliminary research using simple methods that would support (or contradict) the expectation that predicting faults in Python programs is also feasible. The secondary objective is establishing grounds for more thorough future research and publications, provided promising results are obtained during the preliminary research.
Methods: It has been demonstrated [1] that using machine learning techniques, it is possible to predict faults for C/C++ and Java projects with recall 0.71 and false positive rate 0.25. A similar approach was applied in order to find out if promising results can be obtained for Python projects. The working hypothesis is that choosing Python as a programming language does not significantly alter those results. A preliminary study is conducted and a basic machine learning technique is applied to a few sample Python projects. If these efforts succeed, it will indicate that the selected approach is worth pursuing as it is possible to obtain for Python results similar to the ones obtained for C/C++ and Java. However, if these efforts fail, it will indicate that the selected approach was not appropriate for the selected group of Python projects.
Results: The research demonstrates experimental evidence that fault-prediction methods similar to those developed for C/C++ and Java programs can be successfully applied to Python programs, achieving recall up to 0.64 with false positive rate 0.23 (mean recall 0.53 with false positive rate 0.24). This indicates that more thorough research in this area is worth conducting.
Conclusion: Having obtained promising results using this simple approach, the authors conclude that the research on predicting faults in Python programs using machine learning techniques is worth conducting, natural ways to enhance the future research being: using more sophisticated machine learning techniques, using additional Python-specific features and extended data sets.
Keywords: classifier, fault prediction, machine learning, metric, Naïve Bayes, Python, quality, software intelligence
1. Introduction
Software engineering is concerned with the development and maintenance of software systems. Properly engineered systems are reliable and they satisfy user requirements while at the same time their development and maintenance is affordable.
In the past half-century computer scientists and software engineers have come up with numerous ideas for how to improve the discipline of software engineering. Structural programming [2]
restricted the imperative control flow to hierarchical structures instead of ad-hoc jumps. Computer programs written in this style were more readable, easier to understand and reason about. Another improvement was the introduction of an object-oriented paradigm [3] as a formal programming concept.
In the early days software engineers perceived significant similarities between software and civil engineering processes. The waterfall model [4], which resembles engineering practices, was widely adopted as such regardless of its original description actually suggesting a more agile approach.
It has soon turned out that building software differs from building skyscrapers and bridges, and the idea of extreme programming emerged [5], its key points being: keeping the code simple, reviewing it frequently and early and frequent testing. Among numerous techniques, a test-driven development was promoted which eventually resulted in the increased quality of produced software and the stability of the development process [6]. Contemporary development teams started to lean towards short iterations (sprints) rather than fragile upfront designs, and short feedback loops, thus allowing customers’ opinions to provide timely influence on software development. This meant creating even more complex software systems.
The growing complexity of software resulted in the need to describe it at different levels of abstraction, and, in addition to this, the notion of software architecture has developed. The emergence of patterns and frameworks had a similar influence on the architecture as design patterns and idioms had on programming. Software started to be developed by assembling reusable software components which interact using well-defined interfaces, while component-oriented frameworks and models provided tools and languages making them suitable for formal architecture design.
However, a discrepancy between the architecture level of abstraction and the programming level of abstraction prevailed. While the programming phase remained focused on generating a code within a preselected (typically object-oriented) programming language, the architecture phase took place in the disconnected component world. The discrepancies typically deepened as the software kept gaining features without being properly refactored, development teams kept changing over time working under time pressure with incomplete documentation and requirements that were subject to frequent changes. Multiple development technologies, programming languages and coding standards made this situation even more severe. The unification of modelling languages failed to become a silver bullet.
The discrepancy accelerated research on software architecture and the automation of software engineering. This includes the vision for the automated engineering of software based on architecture warehouse and software intelligence [7] ideas. The architecture warehouse denotes a repository of the whole software system and software process artefacts. Such a repository uniformly captures and regards as architectural all information which was previously stored separately in design documents, version-control systems or simply in the minds of software developers. Software intelligence denotes a set of tools for the automated analysis, optimization and visualization of the warehouse content [8, 9].
An example of this approach is combining information on source code artefacts, such as functions, with the information on software process artefacts, such as version control comments indicating the developers’ intents behind changes in given functions. Such an integration of source code artefacts and software process artefacts allows to aim for more sophisticated automated learning and reasoning in the area of software engineering, for example obtaining an ability to automatically predict where faults are likely to occur in the source code during the software process.
The automated prediction of possibly faulty fragments of the source code, which allows developers to focus development efforts on the bug prone modules first, is the topic of this research. This is an appealing idea since, according to a U.S. National Institute of Standards and Technology’s study [10], inadequate software testing infrastructure costs the U.S. economy an esti-
Estimated $60 billion annually. One of the factors that could yield savings is identifying faults at earlier development stages.
For this reason, fault prediction was the subject of many previous studies. As yet, software researchers have concluded that defect predictors based on machine learning methods are practical [11] and useful [12]. Such studies were usually focused on C/C++ and Java projects [13] omitting other programming languages, such as Python.
This study demonstrates experimentally that techniques used in the former fault prediction studies can be successfully applied to the software developed in Python. The paper is organized as follows: in section 2 the related works are recalled; in section 3 the theoretic foundations and implementation details of the approach being subject of this study are highlighted; the main results are presented in section 4, with conclusions to follow in section 5. The implementation of the method used in this study for predictor evaluation is outlined in the Appendix, it can be used to reproduce the results of the experiments. The last section contains bibliography.
2. Related work
Software engineering is a sub-field of applied computer science that covers the principles and practice of architecting, developing and maintaining software. Fault prediction is a software engineering problem. Artificial intelligence studies software systems that are capable of intelligent reasoning. Machine learning is a part of artificial intelligence dedicated to one of its central problems - automated learning. In this research machine learning methods are applied to a fault prediction problem.
For a given Python software project, the architectural information warehoused in the project repository is used to build tools capable of automated reasoning about possible faults in a given source code. More specifically: (1) a tool able to predict which parts of the source code are fault-prone is developed; and (2) its operation is demonstrated on five open-source projects.
Prior works in this field [1] demonstrated that it is possible to predict faults for C/C++ and Java projects with a recall rate of 71% and a false positive rate of 25%. The tool demonstrated in this paper demonstrates that it is possible to predict faults in Python achieving recall rates up to 64% with a false positive rate of 23% for some projects; for all tested projects the achieved mean recall was 53% with a false positive rate of 24%.
Fault prediction spans multiple aspects of software engineering. On the one hand, it is a software verification problem. In 1989 Boehm [14] defined the goal of verification as an answer to the question Are we building the product right? Contrary to formal verification methods (e.g. model checking), fault predictors cannot be used to prove that a program is correct; they can, however, indicate the parts of the software that are suspected of containing defects.
On the other hand, fault prediction is related to software quality management. In 2003 Khoshgoftaar et al. [15] observed that it can be particularly helpful in prioritizing quality assurance efforts. They studied high-assurance and mission-critical software systems heavily dependent on the reliability of software applications. They evaluated the predictive performance of six commonly used fault prediction techniques. Their case studies consisted of software metrics collected over large telecommunication system releases. During their tests it was observed that prediction models based on software metrics could actually predict the number of faults in software modules; additionally, they compared the performance of the assessed prediction models.
Static code attributes have been used for the identification of potentially problematic parts of a source code for a long time. In 1990 Porter et al. [16] addressed the issue of the early identification of high-risk components in the software life cycle. They proposed an approach that derived the models of problematic components based on their measurable attributes and the attributes of their development processes. The models allowed to forecast which components were likely to share the same high-risk properties, such as like being error-prone or having a high development cost.
Table 1. Prior results of fault predictors using NASA data sets [17]
<table>
<thead>
<tr>
<th>Data set</th>
<th>Language</th>
<th>Recall</th>
<th>False positive rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>PC1</td>
<td>C</td>
<td>0.24</td>
<td>0.25</td>
</tr>
<tr>
<td>JM1</td>
<td>C</td>
<td>0.25</td>
<td>0.18</td>
</tr>
<tr>
<td>CM1</td>
<td>C</td>
<td>0.35</td>
<td>0.10</td>
</tr>
<tr>
<td>KC2</td>
<td>C++</td>
<td>0.45</td>
<td>0.15</td>
</tr>
<tr>
<td>KC1</td>
<td>C++</td>
<td>0.50</td>
<td>0.15</td>
</tr>
</tbody>
</table>
In total: 0.36 0.17
Table 2. Prior results of fault predictors using NASA data sets [1] (logarithmic filter applied)
<table>
<thead>
<tr>
<th>Data set</th>
<th>Language</th>
<th>Recall</th>
<th>False positive rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>PC1</td>
<td>C</td>
<td>0.48</td>
<td>0.17</td>
</tr>
<tr>
<td>MW1</td>
<td>C</td>
<td>0.52</td>
<td>0.15</td>
</tr>
<tr>
<td>KC3</td>
<td>Java</td>
<td>0.69</td>
<td>0.28</td>
</tr>
<tr>
<td>CM1</td>
<td>C</td>
<td>0.71</td>
<td>0.27</td>
</tr>
<tr>
<td>PC2</td>
<td>C</td>
<td>0.72</td>
<td>0.14</td>
</tr>
<tr>
<td>KC4</td>
<td>Java</td>
<td>0.79</td>
<td>0.32</td>
</tr>
<tr>
<td>PC3</td>
<td>C</td>
<td>0.80</td>
<td>0.35</td>
</tr>
<tr>
<td>PC4</td>
<td>C</td>
<td>0.98</td>
<td>0.29</td>
</tr>
</tbody>
</table>
In total: 0.71 0.25
In 2002, the NASA Metrics Data Program Data sets were published [18]. Each data set contained complexity metrics defined by Halstead and McCabe, the lines of code metrics and defect rates for the modules of a different subsystem of NASA projects. These data sets included projects in C, C++ and Java. Multiple studies that followed used these data sets and significant progress in this area was made.
In 2003 Menzies et al. examined decision trees and rule-based learners [19–21]. They researched a situation when it is impractical to rigorously assess all parts of complex systems and test engineers must use some kind of defect detectors to focus their limited resources. They defined the properties of good defect detectors and assessed different methods of their generation. They based their assessments on static code measures and found that (1) such defect detectors yield results that are stable across many applications, and (2) the detectors are inexpensive to use and can be tuned to the specifics of current business situations. They considered practical situations in which software costs are assessed and additionally assumed that better assessment allowed to earn exponentially more money. They pointed out that given finite budgets, assessment resources are typically skewed towards areas that are believed to be mission critical; hence, the portions of the system that may actually contain defects may be missed. They indicated that by using proper metrics and machine learning algorithms, quality indicators can be found early in the software development process.
In 2004 Menzies et al. [17] assessed other predictors of software defects and demonstrated that these predictors are outperformed by Naïve Bayes classifiers, reporting a mean recall of 0.36 with a false positive rate of 0.17 (see Table 1). More precisely they demonstrated that when learning defect detectors from static code measures, Naïve Bayes learners are better than entropy-based decision-tree learners, and that accuracy is not a useful way to assess these detectors. They also argued that such learners need no more than 200–300 examples to learn adequate detectors, especially when the data has been heavily stratified; i.e. divided into sub-sub-sub systems.
In 2007 Menzies et al. [1] proposed applying a logarithmic filter to features. The value of using static code attributes to learn defect predictors was widely debated. Prior work explored issues such as the merits of McCabes versus Halstead versus the lines of code counts for generating defect predictors. They showed that such debates are irrelevant since how the attributes are used to build predictors is much more important than which particular attributes are actually used. They demonstrated that adding a logarithmic filter resulted in improving recall to 0.71, keeping a false positive rate reasonably low at 0.25 (see Table 2).
In 2012 Hall et al. [13] identified and analysed 208 defect prediction studies published from January 2000 to December 2010. By a systematic review, they drew the following conclusions: (1) there are multiple types of features that can be used for defect prediction, including static code metrics, change metrics and previous fault
metrics; (2) there are no clear best bug-proneness indicators; (3) models reporting a categorical predicted variable (e.g. fault prone or not fault prone) are more prevalent than models reporting a continuous predicted variable; (4) various statistical and machine learning methods can be employed to build fault predictors; (5) industrial data can be reliably used, especially data publicly available in the NASA Metrics Data Program data sets; (6) fault predictors are usually developed for C/C++ and Java projects.
In 2016 Lanza et al. [22] criticized the evaluation methods of defect prediction approaches; they claimed that in order to achieve substantial progress in the field of defect prediction (also other types of predictions), researchers should put predictors out into the real world and have them assessed by developers who work on a live code base, as defect prediction only makes sense if it is used in vivo.
The main purpose of this research is to extend the range of analysed programming languages to include Python. In the remaining part of the paper it is experimentally demonstrated that it is possible to predict defects for Python projects using static code features with an approach similar to (though not directly replicating) the one taken by Menzies et al. [1] for C/C++ and Java.
3. Problem definition
For the remaining part of this paper let fault denote any flaw in the source code that can cause the software to fail to perform its required function. Let repository denote the storage location from which the source code may be retrieved with version control capabilities that allow to analyse revisions denoting the precisely specified incarnations of the source code at a given point in time. For a given revision $K$ let $K \sim 1$ denote its parent revision, $K \sim 2$ denote its grandparent revision, etc. Let software metric denote the measure of a degree to which a unit of software possesses some property. Static metrics can be collected for software without executing it, in contrast to the dynamic ones. Let supervised learning denote a type of machine learning task where an algorithm learns from a set of training examples with assigned expected outputs [23].
The authors follow with the definition central to the problem researched in this paper.
Definition 3.1. Let a classification problem denote an instance of a machine learning problem, where the expected output is categorical, that is where: a classifier is the algorithm that implements the classification; a training set is a set of instances supplied for the classifier to learn from; a testing set is a set of instances used for assessing classifier performance; an instance is a single object from which the classifier will learn or on which it will be used, usually represented by a feature vector with features being individual measurable properties of the phenomenon being observed, and a class being the predicted variable, that is the output of the classifier for the given instance.
In short: in classification problems classifiers assign classes to instances based on their features.
Fault prediction is a process of predicting where faults are likely to occur in the source code. In this case machine learning algorithms operate on instances being units of code (e.g. functions, classes, packages). Instances are represented by their features being the properties of the source code that indicate the source code unit’s fault-proneness (e.g. number of lines of code, number of previous bugs, number of comments). The features are sometimes additionally preprocessed; an example of a feature preprocessor, called a logarithmic filter, substitutes the values of features with their logarithms. For the instances in the training set the predicted variable must be provided; e.g. the instances can be reviewed by experts and marked as fault-prone or not fault-prone. After the fault predictor learns from the training set of code units, it can be used to predict the fault-proneness of the new units of the code. The process is conceptually depicted in Figure 1.
A confusion matrix is a matrix containing the counts of instances grouped by the actual and predicted class. For the classification problem it is a $2 \times 2$ matrix (as depicted in Table 3). The confusion matrix and derived metrics can be used to evaluate classifier performance, where the typical indicators are as follows:
to have predicted variable provided, for example they can be reviewed by experts and marked as 'fault-prone' or 'not fault-prone'. A fault predictor learns from the training set and, after that, it can be used to predict defect-proneness of new code units.
1.4. Performance metrics
In this study, my goal was to develop a fault predictor capable of identifying a large part of faults in a given project. For this reason, I measure recall, which is a fraction of fault-prone instances that are labeled as such by the fault predictor. Labour intensive, manual code inspections can find \( \approx 60 \) percent of defects \[38\]. I aimed to reach similar level of recall.
Recall alone is not enough to properly assess performance of a fault predictor. A trivial fault predictor that labels all functions as fault-prone achieves 100% recall. It is therefore a good practice to report false positive rate among recall. For fault prediction problem, false positive rate is a fraction of defect-free code units that are incorrectly labeled as fault-prone.
Definition 3.2. Let recall denote a fraction of actual positive class instances that are correctly assigned to positive class:
\[
\text{recall} = \frac{tp}{tp + fn}
\]
Let precision denote a fraction of predicted positive class instances that actually are in the positive class:
\[
\text{precision} = \frac{tp}{tp + fp}
\]
Let a false positive rate denote a fraction of actual negative class instances that are incorrectly assigned to the positive class:
\[
\text{false positive rate} = \frac{fp}{fp + tn}
\]
Let accuracy denote a fraction of instances assigned to correct classes:
\[
\text{accuracy} = \frac{tp + tn}{tp + fp + tn + fn}
\]
The remaining part of this section contains two subsections. In 3.1 the classification problem analysed in this study is stated in terms typical to machine learning, that is instances: what kinds of objects are classified; classes: into what classes are they are divided; features: what features are used to describe them; classifier: which learning method is used. Section 3.2 focuses on the practical aspects of fault prediction and describes the operational phases of the implementation: identification of instances, feature extraction, generation of a training set, training and predicting.
3.1. Classification problem definition
3.1.1. Instances
The defect predictor described in this study operates at the function level, which is a de facto standard in this field \[13\]. As the first rule of functions is that they should be small \[24\], it
was assumed that it should be relatively easy for developers to find and fix a bug in a function reported as fault-prone by a function-level fault predictor. Hence, in this research functions being instances of problem definition were selected.
3.1.2. Classes
For simplicity of reasoning, in this research the severity of bugs is not predicted. Hence, problem definition instances are labelled as either fault-prone or not fault-prone.
3.1.3. Features
To establish defect predictors the code complexity measures as defined by McCabe [25] and Halstead [26] were used.
The following Halstead’s complexity measures were applied in this study as code metrics for estimating programming effort. They estimate complexity using operator and operand counts and are widely used in fault prediction studies [1].
Definition 3.3. Let \( n_1 \) denote the count of distinct operators, \( n_2 \) denote the count of distinct operands, \( N_1 \) denote the total count of operators, \( N_2 \) denote the total count of operands. Then Halstead metrics are defined as follows: program vocabulary \( n = n_1 + n_2 \); program length \( N = N_1 + N_2 \); calculated program length \( \hat{N} = n_1 \log_2 n_1 + n_2 \log_2 n_2 \); volume \( V = N \times \log_2 n \); difficulty \( D = n_1/2 \times N_2/n_2 \); effort \( E = D \times V \); time required to program \( T = E/18 \) seconds; number of delivered bugs \( B = V/3000 \).
In this research all the metrics defined above, including the counters of operators and operands, are used as features; in particular preliminary research indicated that limiting the set of features leads to results with lower recall.
In the study also the McCabe’s cyclomatic complexity measure, being quantitative measure of the number of linearly independent paths through a program’s source code, was applied. In terms of the software’s architecture graph, cyclomatic complexity is defined as follows.
Definition 3.4. Let \( G \) be the flow graph being a subgraph of the software architecture graph, where \( e \) denotes the number of edges in \( G \) and \( n \) denotes the number of nodes in \( G \). Then cyclomatic complexity \( CC \) is defined as \( CC(G) = e - n + 2 \).
It is worth noting that some researchers oppose using cyclomatic complexity for fault prediction. Fenton and Pfleeger argue that it is highly correlated with the lines of code, thus it carries little information [27]. However, other researchers used McCabe’s complexity to build successful fault predictors [1]. Also, industry keeps recognizing cyclomatic complexity measure as useful and uses it extensively, as it is straightforward and can be communicated across the different levels of development stakeholders [28]. In this research the latter opinions are followed.
3.1.4. Classifier
In this study, the authors opted for using a Naïve Bayes classifier. Naïve Bayes classifiers are a family of supervised learning algorithms based on applying Bayes’ theorem with naive independence assumption between the features. In preliminary experiments, this classifier achieved significantly higher recall than other classifiers that were preliminary considered. Also, as mentioned in section 2, it achieved best results in previous fault prediction studies [1].
It should be noted that for a class variable \( y \) and features \( x_1, \ldots, x_n \), Bayes’ theorem states the following relationship:
\[
P(y|x_1, \ldots, x_n) = \frac{P(y)P(x_1, \ldots, x_n|y)}{P(x_1, \ldots, x_n)}.
\]
This relationship can be simplified using the naïve independence assumption:
\[
P(y|x_1, \ldots, x_n) = \frac{P(y) \prod_{i=1}^{n} P(x_i|y)}{P(x_1, \ldots, x_n)}.
\]
Since \( P(x_1, \ldots, x_n) \) does not depend on \( y \), then the following classification rule can be used:
\[
\hat{y} = \arg \max_y P(y) \prod_{i=1}^{n} P(x_i|y),
\]
where \( P(y) \) and \( P(x_i|y) \) can be estimated using the training set. There are multiple variants of
the Naïve Bayes classifier; in this paper a Gaussian Naïve Bayes classifier is used which assumes that the likelihood of features is Gaussian.
3.2. Classification problem
3.2.1. Identification of instances
A fault predicting tool must be able to encode a project as a set of examples. The identification of instances is the first step of this process. This tool implements it as follows: (1) it retrieves a list of files in a project from a repository (Git); (2) it limits results to a source code (Python) files; (3) for each file it builds an Abstract Syntax Tree (AST) and walks the tree to find the nodes representing source code units (functions).
3.2.2. Feature extraction
A fault predictor expects instances to be represented by the vectors of features. This tool extracts those features in the following way. Halstead metrics are derived from the counts of operators and operands. To calculate them for a given instance, this tool performs the following steps: (1) it extracts a line range for a function from AST; (2) it uses a lexical scanner to tokenize function’s source; (3) for each token it decides whether the token is an operator or an operand, or neither. First of all the token type is used to decide if it is an operator or operand, see Table 4. If the token type is not enough to distinguish between an operator and an operand; then if tokenize.NAME indicates tokens are Python keywords, they are considered operators; otherwise they are considered operands. McCabe’s complexity for functions is calculated directly from AST. Table 5 presents effects of Python statements on cyclomatic complexity score.
3.2.3. Training set generation
Creating a fault predicting tool applicable to many projects can be achieved either by training a universal model, or by training predictors individually for each project [29]. This research adopts the latter approach: for each project it generates a training set using data extracted from the given project repository. Instances in the training set have to be assigned to classes; in this case software functions have to be labelled as either fault-prone or not fault-prone. In previous studies, such labels were typically assigned by human experts, which is a tedious and expensive process. In order to avoid this step, this tool relies on the following general definition of fault-proneness:
Definition 3.5. For a given revision, function is fault-prone if it was fixed in one of K next commits, where the choice of K should depend on the frequency of commits.
The definition of fault proneness can be extended due to the fact that relying on a project architecture warehouse enables mining information in commit logs. For identification of commits as bug-fixing in this research a simple heuristic, frequently used in previous studies, was followed [30,31].
Definition 3.6. Commit is bug-fixing if its log contains any of the following words: bug, fix, issue.
Obviously such a method of generating training data is based on the assumption that bug fixing commits are properly marked and contain only fixes, which is consistent with the best practices for Git [32]. It is worth noting that since this might not be the general case for all projects, the tool in its current format is not recommended for predicting faults in projects that do not follow these practices.
3.2.4. Training and predicting
Training a classifier and making predictions for new instances are the key parts of a fault predictor. For these phases, the tool relies on GaussianNB from the Scikit-learn (scikit-learn.org) implementation of the Naïve Bayes classifier.
4. Main result
The tool’s performance was experimentally assessed on five arbitrarily selected open-source
Applying Machine Learning to Software Fault Prediction
Table 4. Operator and operand types
\[
\text{OPERATOR\_TYPES} = [\text{tokenize.OP, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT}]
\]
\[
\text{OPERAND\_TYPES} = [\text{tokenize.STRING, tokenize.NUMBER}]
\]
Table 5. Contribution of Python constructs to cyclomatic complexity
<table>
<thead>
<tr>
<th>Construct</th>
<th>Effect</th>
<th>Reasoning</th>
</tr>
</thead>
<tbody>
<tr>
<td>if</td>
<td>+1</td>
<td>An if statement is a single decision</td>
</tr>
<tr>
<td>elif</td>
<td>+1</td>
<td>The elif statement adds another decision</td>
</tr>
<tr>
<td>else</td>
<td>0</td>
<td>Does not cause a new decision - the decision is at the if</td>
</tr>
<tr>
<td>for</td>
<td>+1</td>
<td>There is a decision at the start of the loop</td>
</tr>
<tr>
<td>while</td>
<td>+1</td>
<td>There is a decision at the while statement</td>
</tr>
<tr>
<td>except</td>
<td>+1</td>
<td>Each except branch adds a new conditional path of execution</td>
</tr>
<tr>
<td>finally</td>
<td>0</td>
<td>The finally block is unconditionally executed</td>
</tr>
<tr>
<td>with</td>
<td>+1</td>
<td>The with statement roughly corresponds to a try/except block</td>
</tr>
<tr>
<td>assert</td>
<td>+1</td>
<td>The assert statement internally roughly equals a conditional statement</td>
</tr>
<tr>
<td>comprehension</td>
<td>+1</td>
<td>A list/set/dict comprehension of generator expression is equivalent to a for loop</td>
</tr>
<tr>
<td>lambda</td>
<td>+1</td>
<td>A lambda function is a regular function</td>
</tr>
<tr>
<td>boolean</td>
<td>+1</td>
<td>Every boolean operator (and, or) adds a decision point</td>
</tr>
</tbody>
</table>
Table 6. Projects used for evaluation
<table>
<thead>
<tr>
<th>Project</th>
<th>Location at github.com</th>
</tr>
</thead>
<tbody>
<tr>
<td>Flask</td>
<td>/mitsuhiko/flask</td>
</tr>
<tr>
<td>Odoo</td>
<td>/odoo/odoo</td>
</tr>
<tr>
<td>GitPython</td>
<td>/gitpython-developers/GitPython</td>
</tr>
<tr>
<td>Ansible</td>
<td>/ansible/ansible</td>
</tr>
<tr>
<td>Grab</td>
<td>/lorien/grab</td>
</tr>
</tbody>
</table>
Table 7. Summary of projects used for evaluation: projects’ revisions (Rv) with corresponding number of commits (Co), branches (Br), releases (Rl) and contributors (Cn)
<table>
<thead>
<tr>
<th>Project</th>
<th>Rv</th>
<th>Cm</th>
<th>Br</th>
<th>Rl</th>
<th>Cn</th>
</tr>
</thead>
<tbody>
<tr>
<td>Flask</td>
<td>7f38674</td>
<td>2319</td>
<td>16</td>
<td>16</td>
<td>277</td>
</tr>
<tr>
<td>Odoo</td>
<td>898cae5</td>
<td>94106</td>
<td>12</td>
<td>79</td>
<td>379</td>
</tr>
<tr>
<td>GitPython</td>
<td>78d9ca</td>
<td>1258</td>
<td>7</td>
<td>20</td>
<td>67</td>
</tr>
<tr>
<td>Ansible</td>
<td>718812d</td>
<td>15935</td>
<td>34</td>
<td>76</td>
<td>1154</td>
</tr>
<tr>
<td>Grab</td>
<td>e6477fa</td>
<td>1569</td>
<td>2</td>
<td>0</td>
<td>32</td>
</tr>
</tbody>
</table>
projects of different characteristics: Flask – a web development micro-framework; Odoo – a collection of business apps; GitPython – a library to interact with Git repositories; Ansible – an IT automation system; Grab – a web scraping framework. Analyzed software varies in scope and complexity: from a library with narrow scope, through frameworks, to a powerful IT automation platform and a fully-featured ERP system. All projects are publicly available on GitHub (see Table 6) and are under active development.
Data sets for evaluation were generated from projects using method described in section 3, namely: features were calculated for revision HEAD ~ 100, where HEAD is a revision specified in Table 7; functions were labeled as fault-prone if they were modified in bug-fixing commit between revisions HEAD ~100 and HEAD; data set was truncated to files modified in any commit between revisions HEAD ~100 and HEAD. Table 8 presents total count and incidence of fault-prone functions for each data set.
As defined in section 3, recall and false positive rates were used to assess the performance of fault predictors. In terms of these metrics, a good fault predictor should achieve: high recall – a fault predictor should identify as many faults in the project as possible; if two predictors obtain the same false positive rate, the one with higher recall is preferred, as it will yield more fault-prone functions; low false positive rate – code units identified as bug prone require developer action;
the predictor with fewer false alarms requires less human effort, as it returns less functions that are actually not fault-prone.
It is worth noting that Zhang and Zhang [33] argue that a good prediction model should actually achieve both high recall and high precision. However, Menzies et al. [34] advise against using precision for assessing fault predictors, as it is less stable across different data sets than the false positive rate. This study follows this advice.
For this research a stratified 10-fold cross validation was used as a base method for evaluating predicting performance. $K$-fold cross validation divides instances from the training set into $K$ equal sized buckets, and each bucket is then used as a test set for a classifier trained on the remaining $K-1$ buckets. This method ensures that the classifier is not evaluated on instances it used for learning and that all instances are used for validation.
As bug prone functions were rare in the training sets, folds were stratified, i.e. each fold contained roughly the same proportions of samples for each label.
This procedure was additionally repeated 10 times, each time randomizing the order of examples. This step was added to check whether predicting performance depends on the order of the training set. A similar process was used by other researchers (e.g. [1,35]).
Main result 1. The fault predictor presented in this research achieved recall up to 0.64 with false positive rate 0.23 (mean recall 0.53 with false positive rate 0.24, see Table 9 for details).
It is worth noting that: the highest recall was achieved for project Odoo: 0.640; the lowest recall was achieved for project Grab: 0.416; the lowest false positive rate was achieved for project Grab: 0.175; the highest false positive rate was achieved for project Flask: 0.336. For all data sets recall was significantly higher than the false positive rate. The results were stable over consecutive runs; the standard deviation did not exceed 0.03, neither for recall nor for the false positive rate.
Main result 2. This research additionally supports the significance of applying the logarithmic filter, since the fault predictor implemented for this research without using this filter achieved significantly lower mean recall 0.328 with false positive rate 0.108 (see Table 10 for details).
5. Conclusions
In this study, machine learning methods were applied to a software engineering problem of fault prediction. Fault predictors can be useful for directing quality assurance efforts. Prior studies showed that static code features can be used for building practical fault predictors for C/C++ and Java projects. This research demonstrates
### Table 8. Data sets used for evaluation
<table>
<thead>
<tr>
<th>Project</th>
<th>Functions</th>
<th>Fault-prone % fault-prone</th>
</tr>
</thead>
<tbody>
<tr>
<td>Flask</td>
<td>786</td>
<td>30</td>
</tr>
<tr>
<td>Odoo</td>
<td>1192</td>
<td>50</td>
</tr>
<tr>
<td>GitPython</td>
<td>548</td>
<td>63</td>
</tr>
<tr>
<td>Ansible</td>
<td>752</td>
<td>69</td>
</tr>
<tr>
<td>Grab</td>
<td>417</td>
<td>31</td>
</tr>
</tbody>
</table>
### Table 9. Results for the best predictor
<table>
<thead>
<tr>
<th>Project</th>
<th>Recall mean</th>
<th>SD</th>
<th>False positive rate mean</th>
<th>SD</th>
</tr>
</thead>
<tbody>
<tr>
<td>Flask</td>
<td>0.617</td>
<td>0.022</td>
<td>0.336</td>
<td>0.005</td>
</tr>
<tr>
<td>Odoo</td>
<td>0.640 < 0.001</td>
<td>0.234</td>
<td>0.003</td>
<td>0.003</td>
</tr>
<tr>
<td>GitPython</td>
<td>0.467</td>
<td>0.019</td>
<td>0.226</td>
<td>0.003</td>
</tr>
<tr>
<td>Ansible</td>
<td>0.522 < 0.001</td>
<td>0.191</td>
<td>0.002</td>
<td>0.004</td>
</tr>
<tr>
<td>Grab</td>
<td>0.416 0.010</td>
<td>0.175</td>
<td>0.004</td>
<td>0.004</td>
</tr>
</tbody>
</table>
In total: 0.531 < 0.03 0.240 < 0.03
It should be emphasised that similar significance was indicated in the case of the detectors for C/C++ and Java projects in [1].
that these techniques also work for Python, a popular programming language that was omitted in previous research. The tool resulting from this research is a function-level fault prediction tool for Python projects. Its performance was experimentally assessed on five open-source projects. On selected projects the tool achieved recall up to 0.64 with false positive rate 0.23, mean recall 0.53 with false positive rate 0.24. Leading fault predictors trained on NASA data sets achieved higher mean recall 0.71 with similar false positive rate 0.25 [1]. Labour intensive, manual code inspections can find about 60% of defects [36]. This research is close to reaching a similar level of recall. The performance of this tool can be perceived as satisfactory, certainly proving the hypothesis that predicting faults for Python programs has a similar potential to that of C/C++ and Java programs, and that more thorough future research in this area is worth conducting.
5.1. Threats to validity
**Internal** There are no significant threats to internal validity. The goal was to take an approach inspired by the experiments conducted by Menzies et al. [1] The experimental results for Python demonstrated to be consistent with the ones reported for C/C++ and Java, claiming that: static code features are useful for the identification of faults, fault predictors using the Naïve Bayes classifier perform well, however, using a logarithmic filter is encouraged, as it improves predicting performance. Using other methods of extracting features used for machine learning (i.e. Python features which are absent in C/C++ or Java), could potentially lead to a better performance of the tool.
**External** There are threats to external validity. The results obtained in this research are not valid for generalization from the context in which this experiment was conducted to a wider context. More precisely, the range of five arbitrarily selected software projects provides experimental evidence that this direction of research is worth pursuing; however, by itself it does not provide enough evidence for general conclusions and more thorough future research is required. Also the tool performance was assessed only in terms of recall and false positive rates, it has not been actually verified in practice. It is thus possible that the tool current predicting ability might prove not good enough for practical purposes and its further development will be required. Therefore, the conclusion of the universal practical applicability of such an approach cannot be drawn yet.
**Construct** There are no significant threats to construct validity. In this approach the authors were not interested in deciding whether it is a well selected machine learning technique, project attributes used for learning or the completeness of fault proneness definition for the training-set that were mainly contributing to the tool performance. The important conclusion was that the results obtained do not exclude but support the hypothesis, that automated fault prediction in Python allows to obtain accuracy comparable to the results obtained for other languages and to human-performed fault prediction, hence they encourage more research in this area. Thus, the results provided in this paper serve as an example and the rough estimation of predicting performance expected nowadays from fault predictors using static code features. There are few additional construct conditions worth mentioning. As discussed in section 3, the tool training set generation method relies on project change logs being part of the project architecture warehouse. If bug-fixing commits are not properly labelled, or contain not only fixes, then the generated data sets might be skewed. Clearly, the performance of the tool can be further improved, as it is not yet as good as the performance of fault predictors for C/C++ and Java; the current result is a good start for this improvement. Comparing the performance of classifiers using different data sets is not recommended, as predictors performing well on one set of data might fail on another.
**Conclusion** There are no significant threats to conclusion validity. Fault recall (detection rate) alone is not enough to properly assess the performance of a fault predictor (i.e. a trivial fault predictor that labels all functions as fault-prone achieves total recall), hence the focus on both re-
call (detection) and false positives (false alarms). Obviously the false positive rate of a fault predictor should be lower than its recall, as a predictor randomly labelling $p$ of functions as fault-prone on average achieves a recall and false positive rate of $p$. This has been achieved in this study, similarly to [1]. From the practical perspective, in this research the goal recognizing automatically as many relevant (erroneous) functions as possible, which later should be revised manually by programmers; that is the authors were interested in achieving high recall and trading precision for recall if needed. From the perspective of this research goals, evaluating classifiers by measures other than those used in [1] (i.e. using other elements in the confusion matrix) was not directly relevant for the conclusions presented in this paper.
5.2. Future research
Additional features As mentioned in section 3, static code metrics are only a subset of features that can be used for training fault predictors. In particular, methods utilizing previous defect data, such as, [37] can also be useful for focusing code inspection efforts [38,39]. Change data, such as code churn or fine-grained code changes were also reported to be significant bug indicators [40–42]. Adding support for these features might augment their fault predicting capabilities. Moreover, further static code features, such as object oriented metrics defined by Chidamber and Kemerer [43] can be used for bug prediction [32,44]. With more attributes, adding a feature selection step to the tool might also be beneficial. Feature selection can also improve training times, simplify the model and reduce overfitting.
Additional algorithms The tool uses a Naïve Bayes classifier for predicting software defects. In preliminary experiments different learning algorithms were assessed, but they performed significantly worse. It is possible that with more features supplied and fine-tuned parameters these algorithms could eventually outperform the Naïve Bayes classifier. Prediction efficiency could also be improved by including some strategies for eliminating class imbalance [45] in the data sets. Researchers also keep proposing more sophisticated methods for identifying bug-fixing commits than the simple heuristic used in this research, in particular high-recall automatic algorithms for recovering links between bugs and commits have been developed. Integrating algorithms, such as [46] into a training set generation process could improve the quality of the data and, presumably, tool predicting performance.
Additional projects In preliminary experiments, a very limited number of Python projects were used for training and testing. Extending the set of Python projects contributing to the training and testing sets is needed to generalize the conclusions. The selection of additional projects should be conducted in a systematic manner. A live code could be used for predictor evaluation [22], which means introducing predictors into the development toolsets used by software developers in live software projects. The next research steps should involve a more in-depth discussion about the findings on the Python projects, in particular identification why in some projects the proposed techniques have a better performance than in other projects.
References
Applying Machine Learning to Software Fault Prediction
Appendix
The implementation of the method used in this study for predictor evaluation is outlined below, it can be used to reproduce results of the experiments.
```python
# imports available on github.com
import git
import numpy as np
from sklearn import cross_validation
from sklearn import metrics
from sklearn import naive_bayes
from sklearn import utils
from scary import dataset
from scary import evaluation
def run():
projects = [
"path/to/flask",
"path/to/odoo",
"path/to/GitPython",
"path/to/ansible",
"path/to/grab",
]
classifier = naive_bayes.GaussianNB()
EvaluationRunner(projects, classifier).evaluate()
class EvaluationRunner:
def __init__(self, projects, classifier, from_revision="HEAD~100", to_revision="HEAD", shuffle_times=10, folds=10):
self.projects = projects
self.classifier = classifier
self.from_revision = from_revision
self.to_revision = to_revision
self.shuffle_times = shuffle_times
self.folds = folds
def evaluate(self):
total_score_manager = self.total_score_manager()
for project in self.projects:
project_score_manager = self.project_score_manager()
training_set = self.build_training_set(project)
for data, target in self.shuffled_training_sets(training_set):
predictions = self.cross_predict(data, target)
confusion_matrix = self.confusion_matrix(predictions, target)
total_score_manager.update(confusion_matrix)
project_score_manager.update(confusion_matrix)
self.report_score(project, project_score_manager)
self.report_score("TOTAL", total_score_manager)
def project_score_manager(self):
return ScoreManager.project_score_manager()
def total_score_manager(self):
return ScoreManager.total_score_manager()
```
def build_training_set(self, project):
repository = git.Repo(project)
return dataset.TrainingSetBuilder.build_training_set(repository,
self.from_revision, self.to_revision)
def shuffled_training_sets(self, training_set):
for _ in range (self.shuffle_times):
yield util.shuffle(training_set.features, training_set.classes)
def cross_predict(self, data, target):
return cross_validation.cross_val_predict(self.classifier, data, target,
cv=self.folds)
def confusion_matrix(self, predictions, target):
confusion_matrix = metrics.confusion_matrix(target, predictions)
return evaluation.ConfusionMatrix(confusion_matrix)
def report_score(self, description, score_manager):
print (description)
score_manager.report()
class ScoreManager:
def __init__ (self, counters):
self.counters = counters
def update (self, confusion_matrix):
for counter in self.counters:
counter.update(confusion_matrix)
def report(self):
for counter in self.counters:
print (counter.description, counter.score)
@classmethod
def project_score_manager(cls):
counters = [MeanScoreCounter(RecallCounter),
MeanScoreCounter(FalsePositiveRateCounter),]
return cls(counters)
@classmethod
def total_score_manager(cls):
counters = [RecallCounter(),
FalsePositiveRateCounter(),]
return cls(counters)
class BaseScoreCounter:
def update (self, confusion_matrix):
raise NotImplementedError
@property
def score (self):
raise NotImplementedError
def project_score_manager(cls):
counters = [MeanScoreCounter(RecallCounter),
MeanScoreCounter(FalsePositiveRateCounter),]
return cls(counters)
def total_score_manager(cls):
counters = [RecallCounter(),
FalsePositiveRateCounter(),]
return cls(counters)
Applying Machine Learning to Software Fault Prediction
```python
@property
def description(self):
raise NotImplementedError
class MeanScoreCounter(BaseScoreCounter):
def __init__(self, partial_counter_class):
self.partial_counter_class = partial_counter_class
self.partial_scores = []
def update(self, confusion_matrix):
partial_score = self.partial_score(confusion_matrix)
self.partial_scores.append(partial_score)
def partial_score(self, confusion_matrix):
partial_counter = self.partial_counter_class()
partial_counter.update(confusion_matrix)
return partial_counter.score
@property
def score(self):
return np.mean(self.partial_scores), np.std(self.partial_scores)
@property
def description(self):
return "mean/uni{}".format(self.partial_counter_class().description)
class RecallCounter(BaseScoreCounter):
def __init__(self):
self.true_positives = 0
self.false_negatives = 0
def update(self, confusion_matrix):
self.true_positives += confusion_matrix.true_positives
self.false_negatives += confusion_matrix.false_negatives
@property
def score(self):
return self.true_positives / (self.true_positives + self.false_negatives)
@property
def description(self):
return "recall"
class FalsePositiveRateCounter(BaseScoreCounter):
def __init__(self):
self.false_positives = 0
self.true_negatives = 0
def update(self, confusion_matrix):
self.false_positives += confusion_matrix.false_positives
self.true_negatives += confusion_matrix.true_negatives
@property
def score(self):
```
return self.false_positives/(self.false_positives+self.true_negatives)
@property
def description(self):
return 'false_positive_rate'
if __name__ == '__main__':
run ()
|
{"Source-Url": "http://www.e-informatyka.pl/attach/e-Informatica_-_Volume_12/eInformatica2018Art8.pdf", "len_cl100k_base": 11449, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 53559, "total-output-tokens": 14496, "length": "2e13", "weborganizer": {"__label__adult": 0.0003969669342041016, "__label__art_design": 0.00028634071350097656, "__label__crime_law": 0.00031256675720214844, "__label__education_jobs": 0.0008082389831542969, "__label__entertainment": 4.780292510986328e-05, "__label__fashion_beauty": 0.0001590251922607422, "__label__finance_business": 0.00013363361358642578, "__label__food_dining": 0.00031638145446777344, "__label__games": 0.00054168701171875, "__label__hardware": 0.0006422996520996094, "__label__health": 0.00043582916259765625, "__label__history": 0.00016450881958007812, "__label__home_hobbies": 8.535385131835938e-05, "__label__industrial": 0.0002930164337158203, "__label__literature": 0.0002269744873046875, "__label__politics": 0.0002002716064453125, "__label__religion": 0.0004057884216308594, "__label__science_tech": 0.006275177001953125, "__label__social_life": 8.970499038696289e-05, "__label__software": 0.00363922119140625, "__label__software_dev": 0.98388671875, "__label__sports_fitness": 0.0002961158752441406, "__label__transportation": 0.0003848075866699219, "__label__travel": 0.0001742839813232422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59242, 0.03035]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59242, 0.68791]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59242, 0.89034]], "google_gemma-3-12b-it_contains_pii": [[0, 3295, false], [3295, 7626, null], [7626, 11906, null], [11906, 16277, null], [16277, 20689, null], [20689, 23244, null], [23244, 27187, null], [27187, 30906, null], [30906, 34564, null], [34564, 38344, null], [38344, 42754, null], [42754, 47020, null], [47020, 49324, null], [49324, 53625, null], [53625, 55550, null], [55550, 57499, null], [57499, 59066, null], [59066, 59242, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3295, true], [3295, 7626, null], [7626, 11906, null], [11906, 16277, null], [16277, 20689, null], [20689, 23244, null], [23244, 27187, null], [27187, 30906, null], [30906, 34564, null], [34564, 38344, null], [38344, 42754, null], [42754, 47020, null], [47020, 49324, null], [49324, 53625, null], [53625, 55550, null], [55550, 57499, null], [57499, 59066, null], [59066, 59242, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59242, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59242, null]], "pdf_page_numbers": [[0, 3295, 1], [3295, 7626, 2], [7626, 11906, 3], [11906, 16277, 4], [16277, 20689, 5], [20689, 23244, 6], [23244, 27187, 7], [27187, 30906, 8], [30906, 34564, 9], [34564, 38344, 10], [38344, 42754, 11], [42754, 47020, 12], [47020, 49324, 13], [49324, 53625, 14], [53625, 55550, 15], [55550, 57499, 16], [57499, 59066, 17], [59066, 59242, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59242, 0.14824]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
aaa944f6609cac3b8ab601287b0e05307fc6ced9
|
Automatically Assessing Code Understandability: How Far Are We?
Simone Scalabrino*, Gabriele Bavota†, Christopher Vendome‡,
Mario Linares-Vásquez§, Denys Poshyvanyk† and Rocco Oliveto*
* University of Molise, Italy — †Università della Svizzera italiana (USI), Switzerland
‡The College of William and Mary, USA — §Universidad de los Andes, Colombia
Abstract—Program understanding plays a pivotal role in software maintenance and evolution: a deep understanding of code is the stepping stone for most software-related activities, such as bug fixing or testing. Being able to measure the understandability of a piece of code might help in estimating the effort required for a maintenance activity, in comparing the quality of alternative implementations, or even in predicting bugs. Unfortunately, there are no existing metrics specifically designed to assess the understandability of a given code snippet.
In this paper, we perform a first step in this direction, by studying the extent to which several types of metrics computed on code, documentation, and developers correlate with code understandability. To perform such an investigation we ran a study with 46 participants who were asked to understand eight code snippets each. We collected a total of 324 evaluations aiming at assessing the perceived understandability, the actual level of understanding, and the time needed to understand a code snippet.
Our results demonstrate that none of the (existing and new) metrics we considered is able to capture code understandability, not even the ones assumed to assess quality attributes strongly related to such factors as code readability and complexity.
Index Terms—Software metrics, Code understandability, Empirical study, Negative result
I. INTRODUCTION
Code understanding is an important foundation to any code-related activity. Developing new features, fixing bugs, or refactoring code requires a deep understanding of the involved code components and of their relationships. Unsurprisingly, recent studies showed that developers spend most of their time (~70%) understanding code [1].
While the importance of code understandability is undisputed for maintenance-related activities [2], [3], [4], [5], [6], [7], there is still a lack of metrics to objectively assess the understandability of a given piece of code. Indeed, our knowledge of factors affecting (positively or negatively) code understandability is basically tied to common beliefs or is focused on the cognitive process adopted when understanding code [8], [9]. For example, we commonly assume that code complexity has a direct impact on developers’ ability to understand the code, but we do not have strong empirical evidence supporting such a belief yet.
Another aspect possibly related to the understandability of a piece of code is represented by its readability. In the last years, researchers have proposed several metrics and models for assessing code readability [10], [11], [12], [13], [14]. These metrics and models are generally evaluated by assessing their correlation with the readability perceived by developers. This typically means that the developers participating in the evaluation are just asked to read the code and assess its readability on a given scale (e.g., from 1—low to 5—high readability). However, the perceived readability is something different from the actual understandability of the code; a developer could find a piece of code readable, but still difficult to understand, for example, due to unknown APIs used.
Let us consider the code fragment listed below:
```java
AsyncHttpClient client = new AsyncHttpClient();
String cookies = CookieManager.getInstance().getCookie(url);
client.addHeader(SM.COOKIE, cookies);
Log.e(TAG, cookies);
```
All readability metrics/models existing in the literature [10], [11], [12], [13], [14] would consider this snippet of code as highly readable, since it is very short, it has a low complexity, and uses meaningful and intuitive identifiers. Nevertheless, this snippet of code is not necessarily easy to understand for any given developer, because the used APIs could be unknown to her and even poorly documented. In other words, even if a developer can understand that `getCookie(url)` returns a cookie, she may not understand all the consequences of this call if she does not know the specifications behind that API.
While we have possible proxies for code understandability, such as code complexity and readability, we (i) do not know whether these proxies actually correlate with the effort required to understand a piece of code, and (ii) do not have a metric able to provide an estimation for code understandability. Previous attempts to define a code understandability model [4], [15], [6] have not been empirically evaluated, consider understandability as a factor in a quality model [2], [16], or measure understandability at the level of a whole system [17].
Having a metric to estimate the effort required to understand a piece of code would have a strong impact on several software engineering tasks. For example, such a metric would be useful to (i) improve the estimation of the time needed to fix a bug (the lower the understandability, the higher the time to fix the bug); (ii) create search-based refactoring recommender systems using code understandability as a fitness function; or (iii) assess the quality of code changes during code reviews.
In this paper, we make the first step towards the definition of a metric able to capture the understandability of a given piece of code by investigating to what extent a number of different (existing and new) metrics correlate with code understandability.
We consider three types of metrics:
1) **Code-related metrics.** We consider 105 metrics characterizing the code to be understood: classic code metrics such as LOC and cyclomatic complexity, as well as metrics used to assess the readability of a code component, such as text coherence [14] and the code indentation [10];
2) **Documentation-related metrics.** The availability of documentation can clearly impact the understandability of a given piece of code. For this reason, we consider 11 documentation-related metrics (e.g., the availability of external documentation for the given code). None of them are introduced in this paper.
3) **Developer-related metrics.** We consider five metrics related to the developer’s experience. While developer-related metrics could not be used to define an objective measure for code understandability, they are still useful in our study to assess to what extent the developer experience and background play a role during comprehension.
We conducted a study involving 46 participants to assess the correlation of the aforementioned 121 (105 code-related + 11 documentation-related + 5 developer-related) metrics with the understandability of code snippets. Participants were required to understand eight code snippets each, for a total of 324 data points. We adopted the following experimental design to consider both the perceived and the actual code understandability. We asked participants to carefully read and to fully understand each snippet. Participants could, at any moment, select the option “I understood the snippet” or “I cannot understand the snippet”. This provided us with a first classification of snippets that are perceived by the participants as either “understandable” or “not understandable”. Also, since we monitored the time spent before selecting one of the two options, we can also measure the understandability effort (i.e., the time required to understand a code snippet). Finally, when the participants clicked on “I understood the snippet”, we verified their actual level of understanding by asking questions about the code snippet. The collected dataset, as opposed to the ones used for evaluating code readability metrics (see [10], [14]), provides indications not only about the perceived understandability, but also about the actual understandability.
Our extensive statistical analysis provided us with what can be defined as a **negative empirical result**: none of the considered metrics exhibit a significant correlation with the understandability of code snippets. This holds for both the perceived and the actual understandability. This result was quite surprising for us, especially considering that several metrics (e.g., code complexity and readability) are supposed to influence the understandability of code.
### II. Background & Related Work
In this section, we describe metrics and models that have been proposed to measure code readability. All these metrics have been included in our study. Afterwards, we briefly describe related work presenting metrics for measuring understandability (at system level) as a single quality attribute and as part of a quality model.
#### A. Code Readability
Identifiers and comments play a crucial role in program comprehension, since developers express domain knowledge through the names that they assign to the code entities at different levels (i.e., packages, classes, methods, variables) [18], [19], [20], [21], [22]. Thus, source code lexicon impacts the psychological complexity of a program [14], [23]. Another aspect that also contributes to the readability (and potentially understandability) of source code are structural aspects such as indentation, code entities length [10], [11], and visual/spatial aspects such as syntax highlighting, code formatting, and visual areas covered by code entities [12].
All the aforementioned aspects have been used as features in binary classifiers able to predict the readability of code snippets [10], [11], [12], [13], [14]. In the model by Buse and Weimer [10], source code structural aspects (e.g., number of branches, loops, operators, blank lines, comments) represent the underlying features in the classifier. The model was trained a-priori on 100 small snippets; the snippets were tagged manually as readable or non-readable by 120 human annotators. The reported results provide evidence that readability can be estimated automatically.
Posnett et al. [11] proposed a model based on a reduced set of the features introduced by Buse and Weimer. An empirical evaluation conducted on the same dataset used by Buse and Weimer [10] indicated that the model by Posnett et al. is more accurate than the one by Buse and Weimer.
Dorn introduced a readability model, which relies on a larger set of features grouped in four categories: visual, spatial, alignment, and linguistic [12]. This larger set of features highlights the fact that structural aspects are not the only ones that should be considered for code readability; aspects representing and modeling how the code is read on the screen, such as syntax highlighting, variable naming standards, and operators alignment, should be also considered. Dorn trained and validated the model on a new dataset, including programs in Java, Python and CUDA, for a total of 360 snippets. Such a model achieved a higher accuracy as compared to the one by Buse and Weimer.
Scalabrino et al. [14] proposed and evaluated a set of features based entirely on source code lexicon analysis (e.g., consistency between source code and comments, specificity of the identifiers, textual coherence, comments readability). The model was evaluated on the two datasets previously introduced by Buse and Weimer [10] and Dorn [12] and on a new dataset, composed by 200 Java snippets, manually evaluated by nine developers. The results indicated that combining the features (i.e., structural+textual) improves the accuracy of code readability models.
#### B. Software/Code Understandability
While readable code might directly impact program comprehension, code readability metrics are not sufficient to measure to what extent the code allows developers to understand its purpose, relationships between code entities, and the latent semantics at the low-level (e.g., statements, beacons, motifs).
and high-level structures (e.g., packages, classes). Program understanding is a non-trivial mental process that requires building high-level abstractions from code statements or visualizations/models [9], [4]. There have been several metrics designed to evaluate software understandability by focusing on complexity as well as source-level metrics.
Lin et al. [4] proposed a model for assessing understandability by building an understandability matrix from fuzzy maximum membership estimation for population of fog index, comment ratio, the number of components, CFS, Halstead Complexity, and DMSP. The authors then used PCA and factor analysis to get the weights for the column vectors, which can be multiplied by the matrix to get the Synthesis Vector of Understandability. Finally, the understandability is calculated by using the fuzzy integral. The authors did not empirically evaluate the proposed metric.
Misra and Akman [24] performed a comparative study between existing cognitive complexity measures and their proposed measure: cognitive weight complexity measure (CWCM), which assigns weights to software components by analyzing their control structures. The authors performed a theoretical validation of these metrics based on the properties proposed by Weyuker [25]. They found that only one metric, Cognitive Information Complexity Measure (CICM), satisfied all nine properties, while the others satisfied seven of the nine.
Thongmak et al. [3] considered aspect-oriented software dependence graphs to assess understandability of aspect-oriented software, while Srinivasulu et al. [6] used rough sets and rough entropy (to filter outliers) when considering the following metrics: fog index, comment ration, the number of components, CFS, Halstead Complexity, and DMSC. These metrics are computed at system level for nine projects, and subsequently the rough entropy outlier factor was calculated for the metrics to identify the outliers, which correspond to either highly understandable or not understandable software based on the metric values.
Capiluppi et al. [17] proposed a measure of understandability that can be evaluated in an automated manner. The proposed measure considers: (i) the percentage of micro-modules (i.e., the numbers of files) that are within the macro-modules (i.e., the directories), and (ii) the relative size of the micro-modules. The authors calculated the proposed measure on the history of 19 open source projects, finding that understandability typically increased during the life-cycle of the systems. Yet, no evaluation is provided for such a measure.
Understandability has also been a factor in quality models to assess software maintainability. Aggarwal et al. [2] investigated the maintainability of software and proposed a fuzzy model, which is composed of three parts: (i) readability of code, (ii) documentation quality, and (iii) understandability of the software. To quantify understandability, the authors utilize a prior work that defines language of software as the symbols used, excluding reserved words. The authors constructed rules based on the ranges of the three factors to determine maintainability.
Similarly, Chen et al. [7] investigated the COCOMO II Software Understandability factors by conducting a study with six graduate students asked to accomplish 44 maintenance tasks, and found that higher quality structure, higher quality organization, and more self-descriptive code were all correlated with less effort spent on the tasks, which leads to high maintainability.
Bansiya and Davis [26] proposed a model where metrics are related to several quality attributes, including understandability. In terms of understandability, the model considers encapsulation and cohesion to have positive influences, while abstraction, coupling, polymorphism, complexity, and design size have a negative influence. The authors validated the model by analyzing several versions of two applications and found that understandability decreases as a system evolves with many new features. Additionally, 13 evaluators analyzed 14 versions of a project and the authors found a correlation between the evaluators’ overall assessment of quality and the models assessment for 11 out of 13 evaluators.
It is worth noting that we do not consider the above discussed understandability metrics [4], [24], [3], [6], [17], [16], [26] in our study since they are defined at system-level (i.e., they provide an overall indication of the system understandability), while we are interested in studying whether it is possible to measure the understandability of a given code snippet, as already done in the literature for code readability. Instead, we included in our study the metrics used by Kasto and Whalley [27] to study the understandability of code snippets in an educational context. Specifically, Kasto and Whalley analyzed the performance of 93 students in their final examination for the Java programming course and they correlated their results with five metrics.
Several studies have explored software understandability and program comprehension with either students or practitioners. Shima et al. considered the understandability of a software system by assessing the probability that a system can be correctly reconstructed from its components [28]. The authors asked eight students to reconstruct a system and the results suggest that faults tend to occur in hard to understand files or very simple files. Roehm et al. performed an observational study with 28 developers to identify the steps developers perform when understanding software and the artifacts they investigate [5]. The authors found that developers are more inclined towards relying upon source code as well as discussing with colleagues over utilizing the documentation. The authors also identified some behaviors that improve comprehension, such as consistent naming conventions or meaningful names.
Understandability has been mostly analyzed from the perspective of (i) the quality attribute at the software level, i.e., understandability as the “The capability of the software product to enable the user to understand whether the software is suitable, and how it can be used for particular tasks and conditions of use” [29]; (ii) the theories, challenges, and models for program understanding at cognitive levels [9], [8]. However, as of today, we still lack models for assessing code understandability at snippet-level, similarly to code readability.
The only work we found that relates to a code understandability model is based on complexity and size source code level metrics [4], [15].
III. CANDIDATE PREDICTORS FOR CODE UNDERSTANDABILITY
Understandability is a multifaceted property of source code and, as well as readability, is subjective in nature. In readability, the subjectivity is represented by personal taste and habits, while in understandability it lies in the previous knowledge of a developer and in her mental models [8]. Consider a method of an Android activity in a mobile app; its understandability might be high for an Android developer, while it could be low for a Java developer with no experience in Android. In this section, we briefly discuss the 121 metrics considered in our study aimed at assessing their ability to capture the understandability of a given piece of code. Table I shows the complete list of metrics: rows contain the basic metrics and columns indicate how the metrics are aggregated (e.g., the Identifiers length for a given code snippet is computed, as suggested by previous work [10], as the average and as the maximum length of the identifiers used in the snippet). We report in boldface the new metrics introduced in this study. In the following subsections, we discuss the considered metrics grouped by their type.
### A. Code-related metrics
Most of the metrics considered in our study assess source code properties. We include the five metrics used by Kasto and Whalley [27]: cyclomatic complexity [30], which estimates the number of linear independent paths of the snippet average number of nested blocks, which measures the average code-block nesting in the snippet, number of parameters, number of statements and number of operands, i.e., number of identifiers.
We also include in this category all the code-related readability metrics defined in the literature [10], [11], [12], [14]. These include the ones by Buse and Weimer [10], assessing properties for a single line of code (e.g., number of identifiers or line length) and then aggregated (with the maximum and/or the average) to work at the level of “code snippet”.
Lines of code (LOC), token entropy and Halstead’s volume are used by Posnett et al. [11] in the context of readability prediction. Dorn [12] presents a variation to the basic metrics introduced by Buse and Weimer [10], measuring the bandwidth of the Discrete Fourier Transform (DFT) of the metrics, the absolute and the relative area of characters belonging to different token categories (e.g., identifiers, keywords or comments), the alignment of characters through different lines, and the number of identifiers containing words belonging to an English dictionary. Note that the area-related metrics defined by Dorn are computed both in an absolute way (e.g., total area of comments) and in a relative way (e.g., area of comments divided by area of strings). These variants are not reported in Table I due to space constraints, but are considered in our study and listed in our replication package [31].
Scalabrino et al. [14] define Narrow Meaning Identifiers (NMI), Number of Meanings (NM), Identifiers Terms In Dictionary (ITID) and Textual Coherence (TC) to capture the readability of a code snippet. Such metrics are computed line-by-line (ITID), identifier-by-identifier (NMI and NM) or block-by-block (TC); the authors aggregate the measures using minimum, average and maximum, in order to have a single measure for the snippet. We also use code readability, as defined by Scalabrino et al. [14], as a separate metric, combining together the previously listed metrics. We followed the steps described by Scalabrino et al. to define the readability model by using a logistic classifier that we train on the 420 Java snippets available in the literature [10], [12], [14].
We also introduce a new code-related metric, the Invoked Methods Signature Quality (IMSQ), which measures the quality of the signature of the internal methods invoked by a given code snippet s (i.e., methods belonging to the same system of s) in terms of readability and representativeness. We define the Method Signature Quality (MSQ) of an invoked method m as:
\[ MSQ(m) = \frac{1}{|{IS(m)}|} \sum_{id \in {IS(m)}} IQ(id) \]
where \( IS(m) \) is the set of identifiers used in the m’s signature (i.e., method name and parameters) and \( IQ(id) \) is defined as:
\[ IQ(id) = \begin{cases} \frac{1}{2}(Rd(id) + Rp(id)), & \text{id is a method name} \\ Rd(id), & \text{id is a parameter name} \end{cases} \]
<table>
<thead>
<tr>
<th>Metric</th>
<th>Non-aggreg.</th>
<th>Min</th>
<th>Avg</th>
<th>Max</th>
<th>DFT</th>
<th>Visual</th>
<th>Area</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cyclomatic comp</td>
<td>[27]</td>
<td>[27]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Restricted blocks</td>
<td>[27]</td>
<td>[27]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Parameters</td>
<td>[27]</td>
<td>[27]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Statements</td>
<td>[27]</td>
<td>[27]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Assignments</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Blank lines</td>
<td>[10]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Characters</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Keywords</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Comments</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Comparisons</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Conditionals</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Identifiers</td>
<td>[27]</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Keywords</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Identifiers length</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Comments</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Expressions</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Expressions length</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Spaces</td>
<td>[10]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Indentation length</td>
<td>[10]</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Identifiers length</td>
<td>[10]</td>
<td>[10]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Line length</td>
<td>[10]</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Aligned blocks</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Indentation length</td>
<td>[10]</td>
<td>[10]</td>
<td>[12]</td>
<td>[12]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Entropy</td>
<td>[11]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>LOC</td>
<td>[11]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>NMI</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>NM</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>ITID</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>TC</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Readability</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>IMSQ</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>CR</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>CIC</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>CIM</td>
<td>[14]</td>
<td>[14]</td>
<td>[14]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>MBQ</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>AEDQ</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>CEAP</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>PE</td>
<td>[new]</td>
<td>[new]</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>PE-eff</td>
<td>[new]</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
**TABLE I**
CANDIDATE PREDICTORS FOR CODE UNDERSTANDABILITY.
IQ(id) captures the quality of an identifier in terms of its readability (Rd) and its representativeness (Rp). The idea behind the readability is that an identifier should be composed of a (possibly small) set of meaningful words. To measure Rd for an identifier (id), we (i) split id into the words composing it, (ii) expand each word to bring it in its original form (e.g., ptr → pointer), (iii) create a new identifier id_exp composed by the expanded words separated by a “_”, and (iv) measure the Levenshtein distance between id and id_exp. The Levenshtein distance between two strings a and b measures the minimum number of single-character changes needed to transform a into b. The conjecture behind IQ(id) is that the higher the Levenshtein distance between id and id_exp, the higher the mental effort required for the developer to understand the meaning of the identifier by mentally splitting and expanding it during program comprehension. Note also that we separate the expanded terms in id_exp by using “_” in order to penalize, by increasing the Levenshtein distance, identifiers composed by several words. For example, the identifier printOnStdOut is first split into print, on, std, out; then, each word is expanded, which has no effect on the first two words, but expands std into standard and out into output. Therefore, printOnStdOut is transformed in print_on_standard_output.
To have Rd(id) defined in [0, 1], we normalize the Levenshtein distance (L) between id and id_exp as follows:
\[ Rd(id) = 1 - \frac{L(id, id_{exp})}{\max(|id|, |id_{exp}|)} \]
where \( \max(|id|, |id_{exp}|) \) represents the longest identifier among the two. When the distance equals zero, the readability of the identifier equals one, indicating no need for expansion/splitting (i.e., id is composed by a single expanded word).
Note that in the implementation of Rd(id), we used a semi-automatic approach to split/expand identifiers. We first used a naive automatic splitting technique, based on camel case and underscores; then, we automatically checked the presence of each resulting word in an English dictionary. If the word was not found, we manually expanded/further split the specific word. For example, for the word “cmdline” there would not be automatic split. Since the word “cmdline” does not exist in the dictionary, we manually convert it to “command” and “line”. We save all the manual substitutions in order to minimize the human effort. In the literature, there are many automatic approaches for identifier splitting/expansion, but we preferred to implement a simpler and more effective strategy at this stage, since the number of identifiers to split/expand was limited and our goal was to assess the correlation of the defined metrics with the understandability effort. Thus, we wanted to be sure to avoid introducing imprecision while computing the metrics.
When dealing with the identifier used to name a method, we also verify whether it is representative of what the method does (Rp). We compute the textual overlap between the terms used in the identifier and in the method body. We tokenize the method body to define its dictionary. Then, we count the number of times each word from the identifier (expanded or not) is contained in the dictionary extracted from the method body. We consider only names and verbs from the identifiers, ignoring other parts of speech such as conjunctions, since they do not carry semantic information. Following the printOnStdOut example, we check whether the method body contains the words print, standard, std, output, and out. We measure the representativeness as the ratio between the number of words from the identifier (i.e., method name) contained in the method body, and the total number of words in the identifier. If all the words from the identifier are used in m’s body, we assume that the method name is representative of m and thus, should ease the understanding of methods invoking m. If, instead, words are not found in the method body, this could hinder the understandability of the methods invoking m.
In our study, we consider the minimum, the average, and the maximum values of the MSQ metric for a given code snippet (e.g., the average MSQ of all methods invoked in the code snippet).
B. Documentation-related metrics
Scalabrin et al. [14] introduced three metrics to capture the quality of the internal documentation of a snippet: Comments Readability (CR) measures the readability of the comments in a snippet using the Flesch reading-ease test [32]; Comments and Identifiers Consistency (CIC) measures the consistency between comments and code; and CIC_sync, a variant of CIC, which takes synonyms into account.
We also introduce two new metrics aimed at capturing the quality of both the internal (MIDQ) and external (AEDQ) documentation available for code components used in a given snippet. The Methods Internal Documentation Quality (MIDQ) for a snippet s acts as a proxy for the internal documentation (i.e., Javadoc) available for the internal methods (the ones belonging to the same project as s) invoked in s. Given m an internal invoked method, we compute MIDQ(m) using a variation of the approach proposed by Schreck et al. [33]:
\[ MIDQ(m) = \frac{1}{2} (DIR(m) + readability_D(m)) \]
where DIR(m) is the Documented Items Ratio computed as the number of documented items in m divided by the number of documentable items in m. We consider as documentable items for m (i) its parameters, (ii) the exceptions it throws, and (iii) its return value. Such items are considered as documented if there is an explicit reference to them in the Javadoc through the tags @param, @throws and @returns. readability_D(m) represents, instead, the readability of the Javadoc comments assessed using the Flesch reading-ease test [32]. The higher MIDQ the higher the internal documentation quality for m. We consider the minimum, the average, and the maximum values of the MSQ metric for a given code snippet.
Concerning the API External Documentation Quality (AEDQ), it tries to capture the amount of information about APIs used in the given snippet s that can be acquired from external sources of documentation, such as Q&A websites.
The conjecture is that if external documentation is available, it is more likely that developers are able to understand the usage of an API in a code snippet \( s \). We compute the availability of external documentation for each external class \( c \) used in \( s \) via the \( AEDQ(c) \) metric. First, we identify all Stack Overflow discussions related to \( c \) by running the following query:
“title:’how to’ \(<\ c\ >\ hasaccepted:yes\ [java]’”
In other words, we select all Stack Overflow discussions that (i) contain “how to” and the class name in the title, (ii) have an accepted answer, and (iii) concern Java (since our study has been performed on Java snippets). Then, we sum the votes assigned by the Stack Overflow users to the question in each retrieved discussion, in order to have a quantitative information about the interest of the developers’ community in such a class. We assume that higher interest in a given API class implies a higher availability of external sources of information (e.g., discussions, code examples, etc.). We consider in our study the minimum, the average, and the maximum values of the \( AEDQ \) metric for the external classes used in \( s \).
C. Developer-related metrics
Since understandability is a very subjective feature of code, we introduced three developer-related metrics. We measure the programming experience of the developer who is required to understand a snippet \( (PE_{gen} \text{ and } PE_{spec}) \) and the popularity of the API used in the snippet \( (EAP) \).
The common wisdom is that the higher the programming experience of developers, the higher their capability of understanding code. \( PE_{gen} \) measures the programming experience (in years) of a developer in general (i.e., in any programming language). \( PE_{spec} \) assesses instead the programming experience (in years) of a developer in the programming language in which a given snippet \( s \) is implemented. The higher \( PE_{spec} \), the higher the developer’s knowledge about the libraries available for such a programming language.
With External API Popularity \( (EAP) \), we aim at capturing the popularity of the external APIs used in a given snippet. The assumption is that the lower the popularity, the lower the probability that a typical developer knows the API. If the developer is not aware of the APIs used in a snippet, it is likely that she has to look for its documentation or to inspect its source code, thus spending more effort in code understanding.
We rely on an external base of Java classes \( E \) to estimate the popularity of an external class. We chose as \( E \) a 10% random sample of classes from Java/Android projects hosted on GitHub in 2016, totaling \( \sim 2M \) classes from \( \sim 57K \) Java projects. We used Google BigQuery to extract all the imports of all the classes belonging to such projects using a regular expression. Then, we counted the number of times each class imported in \( E \) occurred in the \texttt{import} statements. Note that in Java it is possible to import entire packages \( (e.g., \texttt{import java.util.*}) \). In this case, it is difficult to identify the actual classes imported from the package. For this reason, we applied the following strategy. Let us assume that a class, \( Foo \), is imported only once with the statement \texttt{import bar.Foo}, but it is part of a quite popular package, \( bar \), that is imported 100 times in \( E \) through the statement \texttt{import bar.*}. The class \( Foo2 \), belonging to the same package, is imported 99 times with the statement \texttt{import bar.Foo2}. In this case, we increase the number of occurrences of classes belonging to imported package in a proportional way. In the presented example, we add 1 to the number of \( Foo \)’s imports, and 99 to the number of \( Foo2 \) imports. We found that imports of entire packages represent only 2.6% of all the imports and, therefore, their impact is very low. \( EAP(c) \) is defined as the number of \( c \) imports normalized over the number of imports of \( c_{max} \), where \( c_{max} \) is the most imported class we found in \( E \) (i.e., \texttt{java.util.List}).
IV. Empirical Study Design
The goal of our study is to assess the extent to which the considered 121 metrics correlate with code understandability. The perspective is of researchers interested in analyzing whether code-related, documentation-related, and developer-related metrics can be used to assess the understandability level of a given piece of code. This study aims at answering the following major research question:
What is the correlation between the 121 considered metrics and the understandability level of a given developer for a specific code snippet?
Given the wide and heterogeneous set of considered metrics, answering this research question would allow us and, more in general, the research community to understand how far we are from defining a set of metrics capable of automatically and objectively assessing code understandability.
A. Data collection
The context of the study consists of 50 Java/Android methods extracted from ten popular systems listed in Table II (five methods from each system). We first extracted all the methods having \( 50 \pm 20 \) ELOCs (i.e., Effective Lines Of Code, excluding blank and comment lines) from the systems. The choice of the methods’ size (i.e., \( 50 \pm 20 \) ELOCs) was driven by the decision of excluding methods that are too trivial or too complex to understand.
<table>
<thead>
<tr>
<th>System</th>
<th>Java KLOC</th>
<th>Category</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>ANTIR</td>
<td>178</td>
<td>Desktop</td>
<td>Lexer-parser</td>
</tr>
<tr>
<td>Car-report</td>
<td>45</td>
<td>Mobile</td>
<td>Car costs monitoring</td>
</tr>
<tr>
<td>Hibernate</td>
<td>948</td>
<td>Framework</td>
<td>ORM framework</td>
</tr>
<tr>
<td>Jenkins</td>
<td>231</td>
<td>Web</td>
<td>Continuous integration</td>
</tr>
<tr>
<td>K9 mail</td>
<td>121</td>
<td>Mobile</td>
<td>Mail client</td>
</tr>
<tr>
<td>MyExpenses</td>
<td>101</td>
<td>Mobile</td>
<td>Budget monitoring</td>
</tr>
<tr>
<td>OpenCMS</td>
<td>1059</td>
<td>Web</td>
<td>Content Management System</td>
</tr>
<tr>
<td>Phoenix</td>
<td>352</td>
<td>Framework</td>
<td>Relational database engine</td>
</tr>
<tr>
<td>Spring</td>
<td>197</td>
<td>Framework</td>
<td>Generic application framework</td>
</tr>
<tr>
<td>Weka</td>
<td>657</td>
<td>Desktop</td>
<td>Machine-learning toolkit</td>
</tr>
</tbody>
</table>
TABLE II
SYSTEMS USED IN OUR STUDY
Afterwards, we computed all the metrics described in Section III for the selected methods\(^1\). Then, we used a greedy algorithm for center selection [34] to select the 50 most representative methods based on the defined metrics. Given a set of candidate methods \( M \) and a set of already selected centers \( C \), such algorithm chooses, in each iteration,
\[
\arg \max_{m \in M} \text{dist}(C, m),
\]
i.e., the candidate method which is the farthest possible (in terms of considered metrics) from the already selected centers. The first center is randomly selected. In order to select exactly five snippets from each system, we used the set of candidate methods from a specific system as \( M \) until the five methods for such a system were selected; then, we changed \( M \) with the set of candidate methods from another system, and so on, until \( |C| = 50 \). Note that (i) we did not empty the \( C \) set when changing the candidate methods (i.e., when moving from one system to another) to always keep track of the methods selected up to that moment, thus avoiding the risk of adding to \( C \) methods similar to the ones already in \( C \); (ii) we did not run the algorithm on the union of all candidate methods to ensure the selection of five methods per system (thus increasing the heterogeneity of the final sample).
After having selected the 50 methods and computed the values of the metrics of interest for each of these 50 methods, we needed to define a ground-truth reporting the understandability of each method. To this aim, we invited 46 Java developers and CS students to participate in a survey where they were required to understand the selected methods. The survey was implemented in a Web application and featured the following steps. First, we collected demographic data about participants: (i) years of experience in programming and about participants: (i) years of experience in programming and more specifically in Java, and (ii) current position (e.g., CS student, developer etc.). This information was used in part to compute the developer-related metrics. After this preliminary step, each participant was required to understand a subset of eight methods randomly selected from the 50 methods. The Web application was designed to automatically balance the number of evaluations for each of the 50 methods (i.e., the number of participants understanding each method was roughly the same). In total, we collected 324 evaluations across the 50 methods (~6.5 evaluations per method on average), since not all participants completed the survey.
The eight methods were presented individually (i.e., each method in a different page) to participants, and the Web application allowed navigation of the method and access to the methods/classes invoked/used by it. Also, participants were allowed to browse the Web to collect information about types, APIs, data structures, etc. used in the method. This was done to simulate the typical understanding process performed by developers. We asked participants to carefully read and fully understand each method. Participants could, at any moment, click on the button “I understood the method” or the button “I cannot understand the method”. In both cases, the Web application stored the time spent, in seconds, by the developer for the method’s understanding before clicking on one of the two buttons. If the participant clicked on “I understood the method”, the method was hidden and she was required to answer three verification questions about the method she just inspected. The provided answers were stored for future analysis. An example of verification question is: “What does the invoked method \( X \) do?”. To answer such a question, the participant should have understood also all the consequences of invoking a specific external method.
### B. Analysis Method
In the context of our study, we measure the understandability level of a given piece of code from different perspectives and correlate it with 121 considered metrics. We defined the following four different independent variables.
**Perceived Binary Understandability (PBU).** This binary metric gets value 0 if the participant clicked on the “I cannot understand the method” button, otherwise (i.e., the participant clicked on “I understood the method”) it gets value 1. This metric simply aims at discriminating between understandable vs. non-understandable methods as perceived by participants.
**Time Needed for Perceived Understandability (TNPU).** Measured as time, in seconds, spent by the participant while inspecting the method before clicking on “I understood the method”. This metric cannot be computed when the participant clicked on “I cannot understand the method”.
**Actual Understandability (AU).** It gets value 0 if the participant clicked on the “I cannot understand the method” button. Otherwise, it is computed as the percentage of correct answers the participant provided to the three verification questions. The metric is defined in the range [0, 1], where 1 indicates high understandability.
**Timed Actual Understandability (TAU).** It gets value 0 if the participant clicked on the “I cannot understand the method” button. Otherwise, it is computed as:
\[
TAU = AU \left(1 - \frac{TNPU_{no}}{\max TNPU_{no}}\right)
\]
where \( AU \) is the percentage of correct answers, \( TNPU \) is the time needed to understand the method and \( TNPU_{no} \) is a modified \( TNPU \) where outliers (detected using the Tukey’s test [35], with \( k = 3 \)) are substituted with the maximum value of TPNU, which is not an outlier. The higher \( AU \), the higher \( TAU \), while the higher \( TNPU \), the lower \( TAU \). Also, \( TAU \) is defined in [0, 1]. We considered the relative time \( \frac{TNPU_{no}}{\max TNPU_{no}} \) instead of the absolute time so that \( TAU \) gives the same importance to both the correctness achieved (\( AU \)) and the time needed (\( TNPU \)). We removed outliers from \( TNPU \) because the maximum value of such a variable is 1,649 seconds, much greater than the third quartile (171 seconds). Using such a value as the maximum would have flattened down all the relative times.
We computed these four variables for each of the 324 evaluations performed by participants (i.e., for each method each participant tried to understand). Before calculating the correlation between each of the 121 metrics described in
---
\(^1\)Excluding the “Developer programming experience” and the “Developer Java experience”.
Section III and PBU, TNPU, AU, and TAU, we excluded 2 of the 121 considered metrics (i.e., NMI\(_{\min}\) and ITID\(_{\min}\)), because the value of such metrics was 0 for all the snippets taken into account. Then, we verified which metrics strongly correlate among the 121. This was done to exclude from our analysis redundant metrics capturing the same information in different ways. We compute the Kendall rank correlation coefficient (i.e., Kendall’s \(\tau\)) [36] to determine whether there are pairs exhibiting a strong correlation. We adopted the Kendall’s \(\tau\), since it does not assume the data to be normally distributed nor the existence of a straight linear relationship between the analyzed pairs of metrics. Cohen [37] provided a set of guidelines for the interpretation of the correlation coefficient. It is assumed that there is no correlation when \(0 \leq |\tau| < 0.1\), small correlation when \(0.1 \leq |\tau| < 0.3\), medium correlation when \(0.3 \leq |\tau| < 0.7\), and strong correlation when \(0.7 \leq |\tau| \leq 1\).
For each pair of metrics exhibiting a strong correlation (i.e., with a Kendall’s \(|\tau| \geq 0.7\)), we excluded the ones which presented the highest number of missing values\(^2\) or, if equals, one at random. This allowed us to reduce the number of investigated metrics from 121 to 74. Note that such a removal of metrics was only done for presentation purposes, considering the high number of metrics taken into account in our study. Finally, we computed the Kendall correlation between each of the remaining 74 metrics and PBU, TNPU, AU, and TAU, to verify whether some of them are able to capture the (actual and perceived) understandability of code.
C. Replication Package
All the data used in our study is publicly available [31]. We provide the research community with our dataset reporting the (perceived and actual) understandability achieved by the 46 participants, hoping that the availability of such a dataset will help in fostering research on the definition of a metric to automatically assess code understandability.
V. EMPIRICAL STUDY RESULTS
Fig. 1 provides information about the participants involved in our study. Most of them (\(\sim 70\%\)) are bachelor’s students—mixed in terms of years of programming experience. The sample of participants also included six master’s students, three Ph.D. students, and five professional developers.
Fig. 2 reports a heat-map showing the Kendall’s \(\tau\) between each metric and each understandability variable. We only show in Fig. 2 correlations having \(|\tau| > 0.1\). As it is evident by looking at Fig. 2, very few metrics have a correlation with understandability variables higher than \(|\tau| > 0.1\). Specifically nine metrics have a weak correlation with PBU, 10 with TNPU, 8 with AU and 16 with TAU. 50 out of the 74 metrics taken into account show no correlation at all. In the following, we discuss the observed correlations by understandability metric. However, it must always be kept in mind that these are all weak correlations and, as such, do not allow for making any strong claims about the ability of these correlated metrics to act as proxies for code understandability.
A. Perceived Binary Understandability (PBU)
The metric which has the highest correlation with PBU is “Max line length” (\(\tau \approx -0.17\)), one of the metrics introduced by Buse and Weimer [10] for readability prediction. Note that Buse and Weimer also found that such a metric is the most important one for readability prediction [10]. Therefore, this is a further confirmation of the fact that, generally, developers tend to perceive code with long lines as less pleasant. We also found that there is a low correlation between PE\(_{\text{spec}}\) and PBU: developers with more experience in the specific programming language tend to have a slightly higher confidence and they tend to perceive snippets of code as understandable more frequently than developers with less experience. There is also a low correlation between PBU and AIDQ\(_{\text{min}}\): if the internal APIs are well documented, developers tend to answer that they understood the snippet slightly more frequently.
B. Time Needed for Perceived Understandability (TNPU)
The time needed to answer “I understood the snippet” is (weakly) correlated with the programming experience, both PE\(_{\text{gen}}\) (\(\tau \approx 0.16\)), and PE\(_{\text{spec}}\) (\(\tau \approx 0.15\)). Surprisingly, the correlation is positive: the higher the experience, the higher the time needed to complete the comprehension step (and click the button “I understood the snippet”). This result seems to suggest that experienced developers tend to take more time to understand the snippets, while less experienced developers tend to complete the comprehension process more quickly. However, it is worth remembering that TNPU assesses the time needed for the perceived understandability, and not the actual one (TAU).
C. Actual Understandability (AU)
The metric that has the highest correlation with AU is the average Textual Coherence of the snippet (\(\tau \approx -0.16\)). The fact that the correlation is negative is surprising, because we expected a higher Textual Coherence to imply a higher understandability. Other examples of metrics correlated with AU are Number of parameters and DFT of conditionals (\(\tau \approx -0.15\)), indicating that higher complexity reduces understandability.
D. Timed Actual Understandability (TAU)
The metric with the highest correlation with TAU is DFT of conditionals ($\tau \approx -0.18$). Again, high complexity reduces the understandability. It should be noticed that for TAU, i.e., actual understandability, we do not observe any correlation with the programming experience.
E. Discussion
Given the large and diverse set of metrics considered in our study, we expected to observe some form of correlation allowing us to start designing an understandability metric/model. However, what we obtained is a clear and bold negative result: none of the investigated metrics show a significant correlation with the snippets’ understandability.
An important implication of this finding is that readability and complexity metrics are not correlated with understandability, which is a result deserving additional empirical investigations. For instance, the snippet in Fig. 3 from Weka was understood by all the participants who evaluated such a snippet during the study (i.e., mean PBU = 1). Note also that the mean $TAU = 0.72$, i.e., the participants answered correctly two out of three the verification questions, on average. However, the snippet is considered as unreadable (0.14) when using the readability model proposed by Scalabrino et al. [14].
Another metric that has no correlation with understandability is LOC. Even if in our study we considered snippets with a small variation of LOCs (maximum 40), it would have
However, the research community has been able to identify any metric under understandability as simple too subjective to be captured by metrics. For this reason, we believe that more research targeting the automatic assessment of code understandability still represents an important and valuable research direction.
In the few cases where we observed a correlation, its magnitude is very small. The most important (and surprising) conclusions of our study are that (i) there is no correlation between understandability and readability, and (ii) metrics generally used for effort estimation and commonly associated with understandability, such as cyclomatic complexity, actually have low or no correlation with understandability.
Our study lays the foundations for future research on new metrics actually able to capture facets of code understandability. For this reason, we publicly release our dataset to enable the research community to investigate this direction further.
**VII. CONCLUSION AND FUTURE WORK**
We presented an empirical study investigating the correlation between code understandability and 121 metrics related to the code itself, to the documentation available for it, and to the developer understanding it. We asked 46 developers to understand 50 Java snippets, and we gathered a total of 324 evaluations. We assessed the perceived and actual participants’ understanding for each snippet they inspected and the time they needed for the comprehension process. Our results demonstrate that, in most of the cases, there is no correlation between the considered metrics and code understandability. In the few cases where we observed a correlation, its magnitude is very small. The most important (and surprising) conclusions of our study are that (i) there is no correlation between understandability and readability, and (ii) metrics generally used for effort estimation and commonly associated with understandability, such as cyclomatic complexity, actually have low or no correlation with understandability.
Acknowledgments. Bavota was supported in part by the SNF project JITRA, No. 172479.
**Fig. 3. Example of understandable snippet with low readability**
been reasonable to expect at least a small correlation with understandability.
Almost all of the metrics that we introduced in this study to capture aspects of code reasonably related to understandability do not correlate with any of the considered proxies. The only exception is AIDQ_{min} (API Internal Documentation Quality). Indeed, such a metric has a low correlation with both PBU and TAU. This result does not completely exclude the fact that external documentation, quality of identifiers and popularity of external APIs could play a role in the automatic assessment of code understandability, but it underlines that designing metrics able to capture such an aspect is far from trivial and represents a big challenge for the research community.
Finally, we should not exclude the possibility that code understandability is simply too subjective to be captured by any metric. However, the research community has been able to successfully define proxies for other highly subjective code properties in the past, such as code readability. For this reason, we believe that more research targeting the automatic assessment of code understandability still represents an important and valuable research direction.
**VI. THREATS TO VALIDITY**
**Threats to construct validity** concerning the relation between theory and observation, are mainly due to the measurements we performed, both in terms of the 121 metrics that we studied as well as when defining the four independent variables for the understandability level. Concerning the 121 metrics, we tested our implementation and, when needed (e.g., for the IMSQ metric during the identifiers splitting/expansion), relied on manual intervention to ensure the correctness of the computed metrics. As for the independent variables, we tried to capture both the perceived and the actual code understandability. However, different results might be achieved by exploiting different variables.
**Threats to internal validity** concern the generalizability of our findings. Our study has been performed on a large, but limited, set of metrics and by involving 46 participants comprehending a subset of 50 methods extracted from 10 Java systems. Clearly, our findings hold for the considered population of participants and for Java code. Larger studies possibly involving more participants and code snippets written in other languages should be performed to corroborate or contradict our results.
**Fig. 3. Example of understandable snippet with low readability**
```java
private void addButtons() {
JButton okBut = new JButton("OK");
JButton cancelBut = new JButton("Cancel");
JPanel butHolder = new JPanel();
butHolder.setLayout(new GridLayout(1, 2));
butHolder.add(okBut);
butHolder.add(cancelBut);
add(butHolder, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if (m_modifyListener != null) {
m_modifyListener.setModifiedStatus(
ClassifierPerformanceEvaluatorCustomizer.this, true);
}
if (m_evaluationMetrics.size() > 0) {
StringBuilder b = new StringBuilder();
for (String s : m_evaluationMetrics) {
b.append(s).append(";");
}
String newList = b.substring(0, b.length() - 1);
m_cpe.setEvaluationMetricsToOutput(newList);
}
}
cancelBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
customizerClosing();
if (m_parent != null) {
m_parent.dispose();
}
}
});
```
|
{"Source-Url": "https://dibt.unimol.it/staff/sscalabrino/home/files/2017/aseUnderstandabilityPaper.pdf", "len_cl100k_base": 13434, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 40927, "total-output-tokens": 13246, "length": "2e13", "weborganizer": {"__label__adult": 0.0004398822784423828, "__label__art_design": 0.0002892017364501953, "__label__crime_law": 0.0003066062927246094, "__label__education_jobs": 0.0010843276977539062, "__label__entertainment": 5.3048133850097656e-05, "__label__fashion_beauty": 0.00016021728515625, "__label__finance_business": 0.0001704692840576172, "__label__food_dining": 0.0003216266632080078, "__label__games": 0.00048065185546875, "__label__hardware": 0.0005364418029785156, "__label__health": 0.0003418922424316406, "__label__history": 0.00016200542449951172, "__label__home_hobbies": 8.14199447631836e-05, "__label__industrial": 0.00022494792938232425, "__label__literature": 0.0002601146697998047, "__label__politics": 0.000213623046875, "__label__religion": 0.0003707408905029297, "__label__science_tech": 0.0026836395263671875, "__label__social_life": 0.00011247396469116212, "__label__software": 0.0034580230712890625, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.00030684471130371094, "__label__transportation": 0.00038313865661621094, "__label__travel": 0.0001926422119140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56740, 0.02454]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56740, 0.41052]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56740, 0.92068]], "google_gemma-3-12b-it_contains_pii": [[0, 5677, false], [5677, 11984, null], [11984, 18468, null], [18468, 24847, null], [24847, 31063, null], [31063, 37550, null], [37550, 44068, null], [44068, 49537, null], [49537, 51007, null], [51007, 56740, null], [56740, 56740, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5677, true], [5677, 11984, null], [11984, 18468, null], [18468, 24847, null], [24847, 31063, null], [31063, 37550, null], [37550, 44068, null], [44068, 49537, null], [49537, 51007, null], [51007, 56740, null], [56740, 56740, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56740, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56740, null]], "pdf_page_numbers": [[0, 5677, 1], [5677, 11984, 2], [11984, 18468, 3], [18468, 24847, 4], [24847, 31063, 5], [31063, 37550, 6], [37550, 44068, 7], [44068, 49537, 8], [49537, 51007, 9], [51007, 56740, 10], [56740, 56740, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56740, 0.22979]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
e19005dc8406963a3820647e2143d7e57c3b5e5a
|
This specification describe how to handle events with XMPP.
Legal
Copyright
This XMPP Extension Protocol is copyright © 1999 – 2024 by the XMPP Standards Foundation (XSF).
Permissions
Permission is hereby granted, free of charge, to any person obtaining a copy of this specification (the "Specification"), to make use of the Specification without restriction, including without limitation the rights to implement the Specification in a software program, deploy the Specification in a network service, and copy, modify, merge, publish, translate, distribute, sublicense, or sell copies of the Specification, and to permit persons to whom the Specification is furnished to do so, subject to the condition that the foregoing copyright notice and this permission notice shall be included in all copies or substantial portions of the Specification. Unless separate permission is granted, modified works that are redistributed shall not contain misleading information regarding the authors, title, number, or publisher of the Specification, and shall not claim endorsement of the modified works by the authors, any organization or project to which the authors belong, or the XMPP Standards Foundation.
Warranty
## NOTE WELL: This Specification is provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. ##
Liability
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall the XMPP Standards Foundation or any author of this Specification be liable for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising from, out of, or in connection with the Specification or the implementation, deployment, or other use of the Specification (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if the XMPP Standards Foundation or such author has been advised of the possibility of such damages.
Conformance
This XMPP Extension Protocol has been contributed in full conformance with the XSF’s Intellectual Property Rights Policy (a copy of which can be found at <https://xmpp.org/about/xsf/ipr-policy> or obtained by writing to XMPP Standards Foundation, P.O. Box 787, Parker, CO 80134 USA).
## Contents
1 Introduction .................................................. 1
2 Requirements ................................................... 1
3 Glossary .......................................................... 2
4 Use Cases .......................................................... 2
4.1 Creating a Simple Event .................................. 2
4.1.1 explanation .............................................. 2
4.2 Organizing an Event ...................................... 3
4.2.1 explanation .............................................. 5
5 Events Nodes .................................................... 6
6 Events Data ....................................................... 6
6.1 Head Picture ............................................... 7
6.2 Description ................................................ 7
6.3 Categories .................................................. 7
6.4 Location ..................................................... 8
6.4.1 Online Location ....................................... 8
6.5 RSVP .......................................................... 10
6.5.1 RSVP Summarizing .................................. 12
6.5.2 Private RSVP .......................................... 13
6.6 Linked Pubsub Nodes ..................................... 14
6.6.1 invitees ............................................... 14
6.6.2 comments .............................................. 15
6.6.3 blog .................................................... 15
6.6.4 schedule ............................................... 15
6.7 Attachments ................................................ 15
6.8 Extra Data .................................................. 15
6.9 External Event ............................................. 16
7 Business Rules .................................................. 17
8 Discovering Support ........................................... 17
9 Security Considerations ........................................ 18
10 IANA Considerations ........................................... 18
11 XMPP Registrar Considerations ................................ 18
12 XML Schema .................................................... 19
1 Introduction
Nowadays, it is common to handle all kind of events through desktop computer or phone: it is useful to have them at hand, to easily share them and to have all kind of reminders. XMPP is a good fit to handle events: it’s a communication protocol, and as such it would be useful for it to have tools to handle and share events.
The only existing attempt at this point is iCal Envelope (XEP-0097)\(^1\) which describe a way to wrap iCal\(^2\) data. However, this XEP never got traction, is not taking advantage of XMPP features, doesn’t handle thing such as invitees and RSVP, and it not easily extensible.
This XEP proposes an alternative which leverage existing tools such as Publish-Subscribe (XEP-0060)\(^3\).
2 Requirements
The design goals of this XEP are:
- use pubsub and its access model to be able to have events either private or public, and to take advantage of the subscription mechanism
- being able to specify simple events with minimum metadata (e.g. doctor appointment, coffee with a friend)
- provide optional tools such as RSVP or invitees list for events organization
- it should be possible to optionally ask any kind of extra data in RSVP (e.g.: number of people attending, allergy information for dinner, etc.)
- group several events of same kind in a pubsub node (e.g. personal agenda, work agenda, events linked to an organization)
- flexible enough to specify all kind of extra metadata (e.g. description, classification tags, accessibility information) and media (e.g. main picture)
- being able to optionally link to other pubsub features such as Microblogging Over XMPP (XEP-0277)\(^4\) blog, or a way to share picture after the event is finished
- be extensible
---
\(^2\)iCalendar https://datatracker.ietf.org/doc/html/rfc5545
4 Use Cases
4.1 Creating a Simple Event
Juliet and her nurse decide to have a coffee together. Juliet knows the usual place where they're going, and thus doesn't need to add much information, she creates an event for her agenda on her XMPP client. The client creates an item on Juliet’s PEP node 'urn:xmpp:events:0' as follow:
Listing 1: Minimal Event
```xml
<iq type='set' from='juliet@capulet.lit/chamber' to='juliet@capulet.lit' id='event1'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<publish node='urn:xmpp:events:0'>
<item>
<event xmlns='urn:xmpp:events:0'>
<name>Coffee with the nurse</name>
<start>2022-09-05T12:00:00Z</start>
<end>2022-09-05T13:00:00Z</end>
</event>
</item>
</publish>
</pubsub>
</iq>
```
4.1.1 explanation
An event is published on a Publish-Subscribe (XEP-0060) item. Juliet publishes this event on her personal agenda, thus she uses the node 'urn:xmpp:events:0' (see events nodes). The payload of an event is an <event/> element qualified by the namespace 'urn:xmpp:events:0'. Each event MUST have one or several <name/> elements containing a human readable short text describing the element. If several <name/> elements are used, they MUST have distinct 'xml:lang' attributes, to specify the same name in different languages. Each <event/> element MUST have a <start/> and an <end/> child elements specifying the expected start time and end time of the event by using the format explained in XMPP Date and Time Profiles (XEP-0082).
---
This is all for the minimum required elements of an event, everything else is optional. Thus, the only required elements of an event payload are `<name/>`, `<start/>` and `<end/>`.
### 4.2 Organizing an Event
Juliet is organizing a ball, and to make things easier she uses her XMPP client to manage it. To make the event more appealing, she'll publish a nice image of the ball room as main picture of the event, and she’ll publish the list of invitees. She’ll also need RSVP to evaluate the number of people attending.
The event she’s publishing looks as follows:
**Listing 2: Organising an Event**
```xml
<iq
type='set'
from='juliet@capulet.lit/chamber'
to='pubsub.capulet.lit'
id='event2'>
<pubsub
xmlns='http://jabber.org/protocol/pubsub'>
<publish
node='urn:xmpp:events:0/balls'>
<item
id='2022_ball'>
<event
xmlns='urn:xmpp:events:0'>
<name xml:lang='en'>Capulet's_Ball</name>
<start>2022-12-15T20:00:00Z</start>
<end>2022-12-16T02:00:00Z</end>
<head>picture</head>
<file-sharing
xmlns='urn:xmpp:sfs:0'
disposition='inline'>
</file-sharing>
<file
xmlns='urn:xmpp:file:metadata:0'>
<name>ball_room.jpg</name>
<size>120354</size>
<dimensions>1920x1080</dimensions>
<hash>sha3-256</hash>
<url-data
xmlns='http://jabber.org/protocol/url-data'
target='https://download.capulet.lit/123abc-def-456-789/ball_room.jpg'>
</url-data>
</event>
</item>
</publish>
</pubsub>
</iq>
```
Come and enjoy the event of the year!
The Capulet family is organizing its great annual ball! Come and enjoy the event of the year.
Capulet's House
<country>Italy</country>
<lat>45.4181</lat>,
<lon>10.9637</lon>
<text>Code for entrance gate: 0123C</text>
</locality>
<geoloc xmlns='http://jabber.org/protocol/geoloc' xml:lang='en'>
<!--
\[urn:xmpp:events:rsvp:0
\[urn:xmpp:events:invitees:0/2022_ball
\[urn:xmpp:microblog:0:comments/2022_ball
\[blog
-->
4.2.1 explanation
Juliet wants to be sure that this event will be a success, thus she provides a lot of information. The first 3 elements <name/>, <start/> and <end/> are the mandatory one as specified in
simple event explanation, all other elements are optionals. The elements used are briefly explained below, and are more detailed in Events Data section. The <head-picture/> element indicate where to find the head picture, or in other terms the main image used to represent the event. This image is used by clients to nicely represent the event to end-user.
<description/> elements contain human readable text to explain what the event is about.
<category/> elements are used to classify the event. This is useful to quickly give an idea of what the event is about, and for events discovery.
<location/> specify where the event takes place. It may also be used for online events.
<rsvp/> contains the form that invitees will answer to indicate if they plan to attend the event. The 4 following elements <invitees/>, <comments/>, <blog/> and <schedule/> link to pubsub nodes respectively handling list of invitees, comments on the events, blog talking about the event, and event schedule. They are described in Linked Pubsub Nodes section.
<attachments/> elements provide any kind of files that can be useful to the event. It’s used here to provide the menu for the dinner.
Finally, the <extra/> element contains a data form for any useful extra information.
5 Events Nodes
Events are published to pubsub nodes. Each user may have a personal agenda on its Personal Eventing Protocol (XEP-0163) service, by using the 'urn:xmpp:events:0' node. This node should have an access model of "whitelist" by default, however it is up to the entity holding the PEP node to use an other access model (a JID linked to an organisation may want to make public all its events from the personal agenda by using an "open" access model).
Otherwise, a node may be published on any pubsub service. An events node SHOULD be prefixed with 'urn:xmpp:events:0/', which SHOULD be followed by an unique identifier.
A pubsub node can contain any kind of events, and it is up to the publisher to decide what to put inside. While a personal agenda will hold events related to the owning entity, an events node can be used to keep events related to a school or other organisation, to a room (e.g. to show when and by whom a room is booked), to a team, to professional appointments, etc.
6 Events Data
This section describe the various optional elements usable as children of an <event/> element. The 3 mandatory elements <name/>, <start/> and <end/> are specified in Simple Event Explanation.
6.1 Head Picture
The `<head-picture/>` element describes the image to use to represent the event to the end-user. It is recommended to include it for public events as it may help to give a rough idea of the event, and to represent nicely a summary of the event. Keep in mind that the picture may be resized or cropped to fit end-user display and client’s UI choices. The element MUST contain a child `<file-sharing/>` element as described [Stateless file sharing (XEP-0447)](https://xmpp.org/extensions/xep-0447.html). The image SHOULD be published in JPEG format due to its widespread support and the fact that mostly photos are expected to be used as head pictures. It is strongly recommended to include thumbnails if the head picture is large, as the event may be displayed on any screen size.
6.2 Description
The `<description/>` element is used to give a human-readable text explaining the event. It is the main presentation of the event, usually highlighted below the head picture. The description may be in plain text, in this case the `<description/>` MUST have a 'type' attribute with a value of "text". The element then contains the plain text description. XHTML may also be used to provide rich description. To do so, the "xhtml" value must be used for the 'type' attribute, and the first child element of the `<description/>` element MUST be a `<div/>` element qualified by the 'http://www.w3.org/1999/xhtml' namespace. Note that the content MUST be sanitized before being shown to end-user, please check Security Considerations for some advices. The "xml:lang" attribute SHOULD be present on each description element. Several `<description/>` elements MAY be present, as long as they have distinct "type"/"xml:lang" combination. It is not mandatory to provide a text or XHTML description, and providing only one of them is valid.
6.3 Categories
It is possible to give categories to the event with the `<category/>` element. This is specially useful for event discovery, and to give a rough idea of what the event is about. A `<category/>` MUST have a 'term' attribute with a human-readable word or short words combination describing the category, and SHOULD have a "xml:lang" attribute set. Whenever possible, the `<category/>` SHOULD have a "wd" attribute whose value is the Wikidata Entity ID. Wikidata is an open and collaborative database with over 100 million items. By specifying the Wikidata entity ID corresponding to the term, the category becomes machine-readable and can be easily translated, associated to similar terms, linked to corresponding
---
9to find the ID corresponding to the term, you can either search on Wikidata itself, or check it via Wikipedia. An item entity identifier is needed, thus it should start with a "Q". IDs can also be found via Wikipedia API or Wikidata API.
6.4 Location
It is often important to indicate the place where the event happens. This is done by using a `<location/>` element which is wrapping zero or one User Geolocation (XEP-0080) ¹⁰ `<geoloc/>` element and any number of `<online/>` elements (described below). `<online/>` element is used for virtual meeting using a computer. If is it the under the same `<location/>` element than a `<geoloc/>` element, the online meeting is done in parallel to the physical meeting.
There may be several `<location>` elements if the meeting happens in several places (either at the same time, or one after the other). If several locations are used, each `<location/>` element MUST have an 'id' attribute with an unique identifier. At least one of the `<location/>` SHOULD have an 'id' with a value of "main", indicating that it is the main meeting place (which can then be used to discover events by geographical coordinates). When the event is presented to end-user using HTML, the rendering software SHOULD set an 'id' attribute to the element showing the location with the value "location_<LOCATION_ID>" (e.g. for the "main" location, the 'id' attribute would have a value of "location_main"), this way location may then be linked in the XHTML description.
6.4.1 Online Location
If the meeting is virtual or if a virtual meeting happens in parallel for those who can’t go physically to the event, one or more `<online/>` elements can be used to give the instructions. The only mandatory `<online/>` child element is `<instructions/>` which contains a human readable text explaining how to join the online meeting. The `<instructions/>` element SHOULD have a 'xml:lang' attribute, and several `<instructions/>` elements MAY be present if they have distinct 'xml:lang' attributes.
Each `<online/>` MAY have an optional `<name/>` child with a human readable text, this is notably useful if several online locations are used at the same time for different purpose (e.g.: global announces, lost and found, etc.). The `<name/>` element SHOULD have a 'xml:lang' attribute.
If the online location is on an XMPP MUC, an `<x/>` element qualified by the 'jabber:x:conference' namespace as described in Direct MUC Invitations (XEP-0249) ¹¹ can be used.
It may be useful to indicate which software is used for the meeting. This is done with the `<software/>` element which MUST have a 'name' attribute with the software name, SHOULD have a 'wd' attribute with Wikidata entity ID when available (see Categories section for explanation on Wikidata) as it provides a lot of machine readable useful information such as where it can be found, on which platforms it is running, etc. The `<software/>` SHOULD also have an 'url' attribute with the URL to the official software website as value. The 'need_install'
attribute MAY be used with a value of either 'true' if the software needs to be installed or 'false' if it’s not necessary (i.e. if it’s accessible directly via a web resource).
The <url-data/> provide the main URL to be used to join the online meeting. It is specified in URL Address Information (XEP-0103)\(^\text{12}\)
---
**Listing 3: Online Location**
```xml
<iq
type='set'
from='juliet@capulet.lit/chamber'
to='pubsub.capulet.lit'
id='event3'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<publish node='urn:xmpp:events:0/ball_organisation'>
<item>
<event xmlns='urn:xmpp:events:0'>
<!-{...}->
<location>
<name xml:lang='en'>Ball organisation</name>
<software name='Jitsi_Meet' wd='Q87849488' url='https://meet.jit.si/' need_install='false' />
<instructions xml:lang='en'>Just click on the link to access the room. We'll be discussing about organisation of the Capulet ball.</instructions>
</location>
<!-{...}->
</item>
</publish>
</pubsub>
</iq>
```
---
6.5 RSVP
RSVP is a major tool when an event is organized: it helps to check if invitees have seen the event, and to evaluate the total number of people attending. The <rsvp> element MUST contain form as specified in Data Forms (XEP-0004) \(^{13}\) and Field Standardization for Data Forms (XEP-0068) \(^{14}\). The form must be specified as explained in Field Standardization for Data Forms (XEP-0068) \(^{15}\) with <field/> having a 'type' attribute with a value of "hidden", a 'var' with a value of "FORM_TYPE", and the field value MUST be "urn:xmpp:events:rsvp:0". The form is the one which has to be answered by invitees, it SHOULD contain a field with a 'type' attribute of value "list-single" and a 'var' attribute of value "attending" with 3 options of respective value "maybe", "yes" and "no". This is the main field and it’s the one which will be used to estimate the number of attendees. However, an event organizer MAY decide to modify the available options, for instance if the "maybe" option is not desired. This element SHOULD have a <required/> child element.
An optional field named "participants_number" MAY be used to indicate the number of attendees, including the person answering. This field has the default type of "text-single". If present, it will be used to summarize the expected number of persons participating to the event, otherwise one person per attending invitee will be assumed.
Any other field can be added to request extra information to invitees. For instance, it may be used to ask if attendees have allergies, or who is bringing what to a picnic. If a new field is added, Field Standardization for Data Forms (XEP-0068) \(^{16}\) MUST be followed, and the 'var' attribute MUST be namespace using Clark Notation \(^{17}\).
The answer is provided by attendees using Pubsub Attachments (XEP-0470) \(^{18}\): an <rsvp/> element qualified by the 'urn:xmpp:events:0' namespace is attached to the event item, containing the submitted data.
<rsvp/> element SHOULD have a 'xml:lang' attribute set to the language of the labels. Several <rsvp/> elements MAY be present, in which case they MUST have distinct 'xml:lang' attributes.
### Listing 4: RSVP Form
```xml
<iq type='set'
from='juliet@capulet.lit/chamber'
to='pubsub.capulet.lit'
id='event4'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
</pubsub>
</iq>
```
---
\(^{17}\)Clark Notation, a syntax to allow universal names written as a URI in curly brackets followed by the local name; developed by James Clark. <http://www.jclark.com/xml/xmlns.htm>.
Listing 5: Romeo Submit his RSVP Answer
```xml
<iq from='romeo@montague.lit/123' id='events_5' to='pubsub.capulet.lit' type='set'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<publish node='urn:xmpp:pubsub.capulet.lit?;node=urn%3Axml%3Aevents%3A%2Fpicnics;item=picnic_ab123'>
<item id='romeo@montague.lit'>
<attachments>
<rsvp xmlns='urn:xmpp:events:0'>
<x xmlns='jabber:x:data' type='submit'>
<field var='FORM_TYPE'>11
```
6 EVENTS DATA
```xml
<publish node='urn:xmpp:events:0/picnics'>
<item id='picnic_ab123'>
<event xmlns='urn:xmpp:events:0'>
<!-{}- ... -{}->
<rsvp>
<x xmlns='jabber:x:data' type='form'>
<field var='FORM_TYPE' type='hidden'>
<value>urn:xmpp:events:rsvp:0</value>
</field>
<field type='list-single' label='Attending' var='attending'>
<value>maybe</value>
<option label='maybe'>value=maybe</option>
<option label='yes'>value=yes</option>
<option label='no'>value=no</option>
<required/>
</field>
<field label='Number_of_persons_coming_(including_you)' var='participants_number'>
<value>1</value>
</field>
<field label='Do_you_have_any_allergy_or_food_restriction?' var='https://example.org/some_software/restrictions' type='text-multi' />
</x>
</rsvp>
<!-{}- ... -{}->
</event>
</item>
</publish>
</iq>
```
Listing 5: Romeo Submit his RSVP Answer
```xml
<iq from='romeo@montague.lit/123' id='events_5' to='pubsub.capulet.lit' type='set'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<publish node='xmpp:pubsub.capulet.lit?;node=urn%3Axml%3Aevents%3A%2Fpicnics;item=picnic_ab123'>
<item id='romeo@montague.lit'>
<attachments>
<rsvp xmlns='urn:xmpp:events:0'>
<x xmlns='jabber:x:data' type='submit'>
<field var='FORM_TYPE'>11
```
6.5.1 RSVP Summarizing
To summarize RSVP answers, as explained in Pubsub Attachments (XEP-0470)\(^{19}\), the number of attendees is counted with 2 values: “confirmed” which are attendees coming for sure, and “max” which is the maximum number of persons expected. For each <rsvp/> element attached, the count is done like this:
- the increment is equal to the value of the 'participants_number' field, or 1 if
1. the 'participants_number' field is not used or not present in submitted values
2. the value doesn’t cast to an int
3. the int value is lower than 1
- if the value of 'attending' field is not set or "no", then nothing is done
- if the value of 'attending' field is "yes", both "confirmed" and "max" are increased by the increment value
- if the value of 'attending' field is "maybe", only "max" is increased by the increment value
The summary is done in an <attendees/> element qualified by the 'urn:xmpp:events:0' namespace, with a 'confirmed' attribute whose value is the number of confirmed invitees, and a 'max' attribute with the maximum number of invitees expected. If 'max' is the same number as 'confirmed' (meaning that nobody has answered "maybe"), then it may be omitted.
---
6.5.2 Private RSVP
Due to the way Pubsub Attachments (XEP-0470) is working, the normal way to answer RSVP is visible to everybody which can see the event. This is normally not a problem as people which attend the event can see by themselves who is there or not, however some persons may not want to have their RSVP or JID exposed to other participants. In this case the RSVP MAY be sent through a <message/> stanza directed to the JID of the event publisher. The RSVP is then simply put as a child of the stanza, with an optional <body/>. If not <body/> is provided or if the body in empty, The <message/> SHOULD include a <store> hint as specified in Message Processing Hints (XEP-0334). Note that sending an RSVP with a <message/> may complicate the organisation: it’s then not counted automatically in the attachments summary, and if several persons are organizing the event, they may not all check easily the participation.
Listing 6: Juliet Check Current Summary of RSVP
```xml
<iq from='pubsub.capulet.lit' id='events_6' to='juliet@capulet.lit/chamber' type='result'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<items node='urn:xmpp:pubsub-attachments:summary:1'/>
<item id='picnic_ab123'>
<summary
xmlns='urn:xmpp:pubsub-attachments:summary:1'>
<!-{}-⋯-{}->
<attendees xmlns='urn:xmpp:events:0' confirmed='5' max='7' />
<!-{}-⋯-{}->
</summary>
</item>
</items>
</pubsub>
</iq>
```
Listing 7: Romeo Submit a Private RSVP Answer
```xml
<message from='romeo@montague.lit/123' to='juliet@capulet.lit'>
<rsvp xmlns='urn:xmpp:events:0'>
<x xmlns='jabber:x:data' type="submit">
<field var='FORM_TYPE'>
<value>urn:xmpp:events:rsvp:0</value>
</field>
</x>
</rsvp>
</message>
```
6.6 Linked Pubsub Nodes
Some useful external pubsub nodes can be linked to the event. Those nodes are linked through elements which always have a 'jid' attribute specifying the JID of the pubsub or Personal Eventing Protocol (XEP-0163) ²² service, and a 'node' attribute specifying the pubsub node used. The supported elements are described below.
6.6.1 invitees
<invitees/> element links to a node containing one item per invitee. This node access model MAY be different to the one of the event itself: it can for instance have a "whitelist" access model to restrict the list of invitees only to organisers. In other words, it’s not because an user has access to the event item that they have necessarily access to the list of invitees. Each item of the invitees node has a simple payload with an <invitee/> element qualified by the 'urn:xmpp:events:0' namespace and whose attributes are the mandatory 'jid' with the JID of the invitee, and an optional 'name' attribute with a human readable name.
Listing 8: Pubsub Service Returns the List of Invitees to Juliet
6.6.2 comments
The <comments/> element link to a Microblogging Over XMPP (XEP-0277) comments node holding comments to the event itself.
6.6.3 blog
The <blog/> element link to a Microblogging Over XMPP (XEP-0277) node with a blog about the event. It is useful to keep people updated about any news or preparation information.
6.6.4 schedule
The <schedule/> element link to an events node (i.e. a node using this specification) describing the programation which will happens during the main event. Put another way, it’s were information such as dinner time, talks, workshop, etc. can be added. Several events in the schedule MAY happen at the same time or overlapping time (for instance: various talks happening in parallel in a conference), in which case the locations SHOULD be specified (e.g. in which room each talk is taking place). Schedule MAY include events with RSVP (e.g. for a workshop needing inscription).
6.7 Attachments
The <attachments/> elements is used to attach all kinds of files which may be useful to the event (menu, map, badge template, and so forth). It contains one or more <file-sharing/> elements as specified by Stateless file sharing (XEP-0447).
6.8 Extra Data
The <extra/> element hold a data form containing any relevant extra data. The form must be specified by using a FORM_TYPE field with the value “urn:xmpp:events:extra:0” and a ‘type’ with the value ”hidden”. Below some fields are specified, a software MAY add additional field. Any new field MUST follow Field Standardization for Data Forms (XEP-0068) and be
---
namespaced using Clark Notation \(^{27}\). All field and the form itself are optional. The following fields may be used, if not specified otherwise their type is “text-single”:
- **website**: the value links to a website dedicated to the event
- **status**: indicate if the event will happen for sure or if it’s a tentative. The possible values are “confirmed” if the event will happen for sure, “tentative” if the event may happen dependant on some condition (e.g. number of participants, convenient date found), and “cancelled” if the event won’t happen. Note that “tentative” events may be moved to another time\(^{28}\).
- **languages**: indicate the main languages that will be used during the event. The field is of type “list-multi”, and each language value is an ISO 639 language code.
- **accessibility:wheelchair**: indicates if the event is accessible to wheelchairs. The possible values are “full” for an event totally accessible to wheelchair, “partial” when some zones may be difficult to access, and “no” when the zone is not adapted for wheelchairs.
### 6.9 External Event
An event may link to an other one. This is often useful when ones want to participate to an event and add it to their own personal agenda. To link an external event, an `<external/>` element is used which MUST have the 3 following attributes: 'jid' with the JID of the pubsub service of the linked event, 'node' with the name of the pubsub node and 'item' with the ID of the linked event item. Generally, only the 3 mandatory `<name/>`, `<start/>` and `<end/>` elements are specified in addition to the `<external/>` one, the reason being that all data of the events SHOULD be retrieved from the original event itself. The start and end time are still specified through to be sure that the event won’t be automatically moved to an unapproved time spot if the original event is modified.
**Listing 9: Romeo Link Capulet’s Ball in His Personal Agenda**
```xml
<iq type='set' from='romeo@montague.lit/123' to='romeo@montague.lit' id='event_link_123'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<publish node='urn:xmpp:events:0'>
<item>
<event xmlns='urn:xmpp:events:0'>
...
</event>
</item>
</publish>
</pubsub>
</iq>
```
\(^{27}\)Clark Notation, a syntax to allow universal names written as a URI in curly brackets followed by the local name; developed by James Clark. \(<\text{http://www.jclark.com/xml/xmlns.htm}>\).
\(^{28}\)technically any event can be moved to a different time, the "tentative" status just make it a stronger possibility
8 Discovering Support
If a client supports the Events protocol specified in this XEP, it must advertise it by including the "urn:xmpp:events:0" discovery feature in response to a Service Discovery (XEP-0030) information request:
Listing 10: Service Discovery information request
```xml
<iq type='get' from='juliet@example.org/balcony' to='romeo@example.org/orchard' id='disco1'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
```
Listing 11: Service Discovery information response
```xml
<iq type='result' from='romeo@example.org/orchard' to='juliet@example.org/balcony' id='disco1'>
<query xmlns='http://jabber.org/protocol/disco#info'>
...
<feature var='urn:xmpp:events:0'/>
...
</query>
</iq>
```
7 Business Rules
TODO
8 Discovering Support
If a client supports the Events protocol specified in this XEP, it must advertise it by including the "urn:xmpp:events:0" discovery feature in response to a Service Discovery (XEP-0030) information request:
Listing 10: Service Discovery information request
```xml
<iq type='get' from='juliet@example.org/balcony' to='romeo@example.org/orchard' id='disco1'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
```
Listing 11: Service Discovery information response
```xml
<iq type='result' from='romeo@example.org/orchard' to='juliet@example.org/balcony' id='disco1'>
<query xmlns='http://jabber.org/protocol/disco#info'>
...
<feature var='urn:xmpp:events:0'/>
...
</query>
</iq>
```
Similarly, if a PEP/Pubsub service implements the summarizing of RSVP as described in RSVP Summarizing, it MUST advertise that fact by including the “urn:xmpp:events:0” discovery feature in response to a Service Discovery (XEP-0030) information request:
Listing 12: Service Discovery information request
```xml
<iq type='get'
from='juliet@example.org/balcony'
to='pubsub.capulet.lit'
id='disco2'>
<query xmlns='http://jabber.org/protocol/disco#info'/>
</iq>
```
Listing 13: Service Discovery information response
```xml
<iq type='result'
from='pubsub.capulet.lit'
to='juliet@example.org/balcony'
id='disco2'>
<query xmlns='http://jabber.org/protocol/disco#info'>
...
<feature var='urn:xmpp:events:0'/>
...
</query>
</iq>
```
9 Security Considerations
TODO
10 IANA Considerations
TODO
11 XMPP Registrar Considerations
TODO
---
12 XML Schema
TODO
13 Acknowledgements
Thanks to JC Brand for spelling corrections.
|
{"Source-Url": "https://xmpp.org/extensions/xep-0471.pdf", "len_cl100k_base": 8503, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 68826, "total-output-tokens": 10823, "length": "2e13", "weborganizer": {"__label__adult": 0.0003001689910888672, "__label__art_design": 0.000492095947265625, "__label__crime_law": 0.00077056884765625, "__label__education_jobs": 0.0011167526245117188, "__label__entertainment": 0.00015723705291748047, "__label__fashion_beauty": 0.00011217594146728516, "__label__finance_business": 0.0011005401611328125, "__label__food_dining": 0.00024390220642089844, "__label__games": 0.0004363059997558594, "__label__hardware": 0.0007739067077636719, "__label__health": 0.0001806020736694336, "__label__history": 0.00022399425506591797, "__label__home_hobbies": 8.767843246459961e-05, "__label__industrial": 0.00022733211517333984, "__label__literature": 0.0003075599670410156, "__label__politics": 0.0003132820129394531, "__label__religion": 0.0002579689025878906, "__label__science_tech": 0.0102386474609375, "__label__social_life": 0.0002357959747314453, "__label__software": 0.11114501953125, "__label__software_dev": 0.87060546875, "__label__sports_fitness": 0.0001354217529296875, "__label__transportation": 0.00020635128021240232, "__label__travel": 0.00023734569549560547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37448, 0.03302]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37448, 0.19995]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37448, 0.76114]], "google_gemma-3-12b-it_contains_pii": [[0, 60, false], [60, 2595, null], [2595, 4866, null], [4866, 4866, null], [4866, 6884, null], [6884, 8596, null], [8596, 10537, null], [10537, 10996, null], [10996, 11202, null], [11202, 13763, null], [13763, 16705, null], [16705, 19655, null], [19655, 20965, null], [20965, 24012, null], [24012, 25996, null], [25996, 27296, null], [27296, 29149, null], [29149, 30302, null], [30302, 32209, null], [32209, 34807, null], [34807, 36383, null], [36383, 37362, null], [37362, 37448, null]], "google_gemma-3-12b-it_is_public_document": [[0, 60, true], [60, 2595, null], [2595, 4866, null], [4866, 4866, null], [4866, 6884, null], [6884, 8596, null], [8596, 10537, null], [10537, 10996, null], [10996, 11202, null], [11202, 13763, null], [13763, 16705, null], [16705, 19655, null], [19655, 20965, null], [20965, 24012, null], [24012, 25996, null], [25996, 27296, null], [27296, 29149, null], [29149, 30302, null], [30302, 32209, null], [32209, 34807, null], [34807, 36383, null], [36383, 37362, null], [37362, 37448, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37448, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37448, null]], "pdf_page_numbers": [[0, 60, 1], [60, 2595, 2], [2595, 4866, 3], [4866, 4866, 4], [4866, 6884, 5], [6884, 8596, 6], [8596, 10537, 7], [10537, 10996, 8], [10996, 11202, 9], [11202, 13763, 10], [13763, 16705, 11], [16705, 19655, 12], [19655, 20965, 13], [20965, 24012, 14], [24012, 25996, 15], [25996, 27296, 16], [27296, 29149, 17], [29149, 30302, 18], [30302, 32209, 19], [32209, 34807, 20], [34807, 36383, 21], [36383, 37362, 22], [37362, 37448, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37448, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
a8d4031e56d0be5cab45e95028164c3a2c95da0f
|
The \texttt{refcount} package
Heiko Oberdiek∗
\texttt{<heiko.oberdiek at googlemail.com>}
2016/05/16 v3.5
Abstract
References are not numbers, however they often store numerical data such as section or page numbers. \texttt{ref} or \texttt{pageref} cannot be used for counter assignments or calculations because they are not expandable, generate warnings, or can even be links. The package provides expandable macros to extract the data from references. Packages \texttt{hyperref}, \texttt{nameref}, \texttt{titleref}, and \texttt{babel} are supported.
Contents
1 Usage \hspace{1cm} 2
\hspace{0.5cm} 1.1 Setting counters \hspace{1cm} 2
\hspace{0.5cm} 1.2 Expandable commands \hspace{1cm} 2
\hspace{0.5cm} 1.3 Undefined references \hspace{1cm} 3
\hspace{0.5cm} \hspace{0.5cm} 1.3.1 Check for undefined references \hspace{1cm} 3
\hspace{0.5cm} 1.4 Notes \hspace{1cm} 3
2 Implementation \hspace{1cm} 3
\hspace{0.5cm} 2.1 Loading packages \hspace{1cm} 5
\hspace{0.5cm} 2.2 Defining commands \hspace{1cm} 5
\hspace{0.5cm} 2.3 \texttt{setrefcountdefault} \hspace{1cm} 7
\hspace{0.5cm} 2.4 \texttt{refused} \hspace{1cm} 7
\hspace{0.5cm} 2.5 Setting counters by reference data \hspace{1cm} 7
\hspace{0.5cm} \hspace{0.5cm} 2.5.1 Generic setting \hspace{1cm} 7
\hspace{0.5cm} \hspace{0.5cm} 2.5.2 User commands \hspace{1cm} 8
\hspace{0.5cm} 2.6 Extracting references \hspace{1cm} 8
\hspace{0.5cm} 2.7 Macros for checking undefined references \hspace{1cm} 10
3 Test \hspace{1cm} 11
\hspace{0.5cm} 3.1 Catcode checks for loading \hspace{1cm} 11
\hspace{0.5cm} 3.2 Macro tests \hspace{1cm} 12
\hspace{0.5cm} 3.3 Test with package \texttt{titleref} \hspace{1cm} 15
4 Installation \hspace{1cm} 17
\hspace{0.5cm} 4.1 Download \hspace{1cm} 17
\hspace{0.5cm} 4.2 Bundle installation \hspace{1cm} 17
\hspace{0.5cm} 4.3 Package installation \hspace{1cm} 17
\hspace{0.5cm} 4.4 Refresh file name databases \hspace{1cm} 18
\hspace{0.5cm} 4.5 Some details for the interested \hspace{1cm} 18
5 Catalogue \hspace{1cm} 18
∗Please report any issues at https://github.com/ho-tex/oberdiek/issues
1 Usage
1.1 Setting counters
The following commands are similar to \LaTeX’s `\setcounter` and `\addtocounter`, but they extract the number value from a reference:
```
\setcounterref, \addtocounterref
\setcounterpageref, \addtocounterpageref
```
They take two arguments:
```
\...counter...ref {⟨LaTeX counter⟩} {⟨reference⟩}
```
An undefined references produces the usual LaTeX warning and its value is assumed to be zero. Example:
```
\newcounter{ctrA}
\newcounter{ctrB}
\refstepcounter{ctrA}\label{ref:A}
\setcounterref{ctrB}{ref:A}
\addtocounterpageref{ctrB}{ref:A}
```
1.2 Expandable commands
These commands that can be used in expandible contexts (inside calculations, `\edef`, `\csname`, `\write`, ...):
```
\getrefnumber, \getpagerefnumber
```
They take one argument, the reference:
```
\get...refnumber {⟨reference⟩}
```
The default for undefined references can be changed with macro `\setrefcountdefault`, for example this package calls:
```
\setrefcountdefault{0}
```
Since version 2.0 of this package there is a new command:
```
\getrefbykeydefault {⟨reference⟩} {⟨key⟩} {⟨default⟩}
```
This generalized version allows the extraction of further properties of a reference than the two standard ones. Thus the following properties are supported, if they are available:
<table>
<thead>
<tr>
<th>Key</th>
<th>Description</th>
<th>Package</th>
</tr>
</thead>
<tbody>
<tr>
<td>⟨empty⟩</td>
<td>same as <code>\ref</code></td>
<td>\LaTeX</td>
</tr>
<tr>
<td>page</td>
<td>same as <code>\pageref</code></td>
<td>\LaTeX</td>
</tr>
<tr>
<td>title</td>
<td>section and caption titles</td>
<td>titleref</td>
</tr>
<tr>
<td>name</td>
<td>section and caption titles</td>
<td>nameref</td>
</tr>
<tr>
<td>anchor</td>
<td>anchor name</td>
<td>hyperref</td>
</tr>
<tr>
<td>url</td>
<td>url/file</td>
<td>hyperref/xr</td>
</tr>
</tbody>
</table>
Since version 3.2 the expandable macros described before in this section are expandable in exact two expansion steps.
### 1.3 Undefined references
Because warnings and assignments cannot be used in expandable contexts, undefined references do not produce a warning, their values are assumed to be zero.
Example:
```latex
\label{ref:here}\% somewhere
\refused{ref:here}\% see below
\ifodd\getpagerefnumber{ref:here}\%
reference is on an odd page
\else
reference is on an even page
\fi
```
In case of undefined references the user usually want’s to be informed. Also \LaTeX{} prints a warning at the end of the \LaTeX{} run. To notify \LaTeX{} and get a normal warning, just use
```latex
\refused{⟨reference⟩}
```
outside the expanding context. Example, see above.
#### 1.3.1 Check for undefined references
In version 3.2 macros were added, that test, whether references are defined.
```latex
\IfRefUndefinedExpandable {⟨refname⟩} {⟨then⟩} {⟨else⟩}
\IfRefUndefinedBabel {⟨refname⟩} {⟨then⟩} {⟨else⟩}
```
If the reference is not available and therefore undefined, then argument ⟨then⟩ is executed, otherwise argument ⟨else⟩ is called. Macro \IfRefUndefinedExpandable is expandable, but ⟨refname⟩ must not contain babel shorthand characters. Macro \IfRefUndefinedBabel supports shorthand characters of babel, but it is not expandable.
### 1.4 Notes
- The method of extracting the number in this package also works in cases, where the reference cannot be used directly, because a package such as hyperref has added extra stuff (hyper link), so that the reference cannot be used as number any more.
- If the reference does not contain a number, assignments to a counter will fail of course.
### 2 Implementation
```
\begin{verbatim}
1 \langle*package⟩
Reload check, especially if the package is not used with \LaTeX{}.
2 \begingroup\catcode61=10\relax\% 3 \catcode13=5 \% "M
4 \catcode13\endlinechar=10 \%
5 \catcode35=6 \%
6 \catcode35\catcode32=10 \%relax%
7 \catcode39=12 \%
8 \catcode44=12 \%
9 \catcode46=12 \%
\end{verbatim}
```
2.1 Loading packages
\begingroup\expandafter\expandafter\expandafter\endgroup
\expandafter\ifx\csname RequirePackage\endcsname\relax
\input ltxcmds.sty\relax
\input infwarerr.sty\relax
\else
\RequirePackage{ltxcmds}\[2011/11/09\]%
\RequirePackage{infwarerr}\[2010/04/08\]%
\fi
2.2 Defining commands
\rc@ifDefinable
\ifx@IfUndefined{@ifdefinable}{%
\def\rc@ifDefinable#1{%
\ifx#1\ltx@undefined
\expandafter\ltx@firstofone
\else
\ifx#1\relax
\expandafter\expandafter\expandafter\ltx@firstofone
\else
\@PackageError{refcount}{%
\else
\fi
\endinput}
Command \string#1 is already defined.\MessageBreak
It will not redefined by this package%
}\@ehc
\expandafter\expandafter\expandafter\ltx@gobble
\fi
\fi
\let\rc@IfDefinable\@ifdefinable
\rc@RobustDefOne
\rc@RobustDefZero
\ltx@IfUndefined{protected}{{%}
\ltx@IfUndefined{DeclareRobustCommand}{{%}
def\rc@RobustDefOne#1#2#3#4{%}
\rc@IfDefinable#3{% #1}\def#3##1{#4}%
}%}
%}
def\rc@RobustDefZero#1#2{%
\rc@IfDefinable#1{%
def#1{#2}%
}%
%}
def\rc@RobustDefOne#1#2#3#4{%
\rc@IfDefinable#3{%
\DeclareRobustCommand#2#3[1]{#4}%
}%
%}
def\rc@RobustDefZero#1#2{%
\rc@IfDefinable#1{%
\protected\def#1{#2}%
}%
%}
def\rc@RobustDefOne#1#2#3#4{%
\rc@IfDefinable#3{%
\protected\def#1##1{#4}%
}%
%}
def\rc@RobustDefZero#1#2{%
\rc@IfDefinable#1{%
\protected\def#1{#2}%
}%
%}
def\rc@RobustDefOne#1#2#3#4{%
\rc@IfDefinable#3{%
\protected\def#1##1{#4}%
}%
%}
def\rc@RobustDefZero#1#2{%
\rc@IfDefinable#1{%
\protected\def#1{#2}%
}%
%}
def\rc@newcommand
\ltx@IfUndefined{newcommand}{{%}
def\rc@newcommand*#1[#2]#3{% hash-ok
\rc@IfDefinable#1{%
\ifcase#2 %
def#1{#3}%
or
\def#1##1{#3}%
or
\def#1##1##2{#3}%
else
\rc@InternalError
\fi
%}
2.3 \setrefcountdefault
\setrefcountdefault
\rc@RobustDefOne!\long\setrefcountdefault{%}
\def\rc@default{#1}%
\setrefcountdefault{0}
2.4 \refused
\refused
\ltx@ifundefined{G@refundefinedtrue}{%}
\rc@RobustDefOne{}{*}\refused{%}
\begingroup
\csname @safe@activestrue\endcsname
\ltx@ifundefined{r@#1}{%}
\protect\G@refundefinedtrue
\rc@WarningUndefined{#1}%
\endgroup
\rc@WarningUndefined
\ltx@ifundefined{@latex@warning}{%}
\def\rc@WarningUndefined#1{%
\ltx@ifundefined{thepage}{%}
\def\thepage{\number\count0 }%
\@PackageWarning{refcount}{%}
Reference `#1' on page \thepage space undefined%
}%
}
\endgroup
\rc@WarningUndefined
2.5 Setting counters by reference data
2.5.1 Generic setting
\rc@set Generic command for \{set,addto\}counter{page, }ref:
2.5.2 User commands
\setcounter
\addtocounter
\setcounterpageref
\addtocounterpageref
2.6 Extracting references
\getrefnumber
2.7 Macros for checking undefined references
\IfRefUndefinedExpandable
\newcommand*{\IfRefUndefinedExpandable}[1]{\@ifundefined{r@#1}\@firstoftwo\@secondoftwo}
\IfRefUndefinedBabel
\RobustDefOne{}\IfRefUndefinedBabel{\begingroup\csname safe@actives@true\endcsname\expandafter\expandafter\expandafter\endgroup\expandafter\ifx\csname r@#1\endcsname\relax\@firstoftwo\else\@secondoftwo\fi}\else\expandafter\expandafter\expandafter\endgroup\expandafter\ifx\csname r@#1\endcsname\relax\@firstoftwo\else\@secondoftwo\fi\fi
3 Test
3.1 Catcode checks for loading
\catcode\{=1 %
\catcode\}=2 %
\catcode\#=6 %
\catcode\@=11 %
\expandafter\ifx\csname count@\endcsname\relax
\countdef\count@=255 %
\fi
\expandafter\ifx\csname @gobble\endcsname\relax
\long\def\@gobble#1{}%
\fi
\expandafter\ifx\csname @firstofone\endcsname\relax
\long\def\@firstofone#1{#1}%
\fi
\expandafter\ifx\csname loop\endcsname\relax
\else
\expandafter\@gobble
\fi
\def\loop#1\repeat{%
\def\body{#1}%
\iterate
}
\def\iterate{%
\body
\let
ext\iterate
\else
\let
ext\relax
\fi
\next
}
\let
repeat=\fi
\def\RangeCatcodeInvalid#1#2{%
\count@=#1\relax
\loop
\catcode\count@=15 %
\ifnum\count@<#2\relax
\advance\count@ 1 %
\repeat
}
\def\RangeCatcodeCheck#1#2#3{%
\def\RangeCatcodeInvalid#1#2{%
\count@=#1\relax
\loop
\catcode\count@=1 %
\ifnum\count@<255 %
\advance\count@ 1 %
\repeat
}
\def\RangeCatcodeCheck#1#2#3{%
3.2 Macro tests
\def\strip@prefix#1->{%
\def\@onelevel@sanitize#1{%
\edef#1{\expandafter\strip@prefix\meaning#1}%
}\fi
\else
\def\@onelevel@sanitize#1{%
\edef#1{\detokenize\expandafter{#1}}%
}%
}\fi
\def\msg#{\immediate\write16}
\def\empty{}
\def\space{ }
\def\r@foo{{\empty 1}{\empty 2}}
\long\def\test#1#2{\begingroup \setbox0=\hbox{%
\def\TestTask{#1} \@onelevel@sanitize\TestTask \msg{* \TestTask} \expandafter\expandafter\expandafter\def \expandafter\expandafter\expandafter\TestResult \expandafter\expandafter\expandafter{#1}{\def\TestExpected{#2}}%
\ifx\TestResult\TestExpected \msg{ \space ok.} \else \@onelevel@sanitize\TestResult \@onelevel@sanitize\TestExpected \msg{ \space Result: \space\space\TestResult} \msg{ \space Expected: \space\space\TestExpected} \errmessage{Test failed!} \fi \fi\ifdim\wd0=0pt % \else \showbox0 \fi \endgroup}
\test{\getrefnumber{foo}}{\empty 1}\test{\getpagerefnumber{foo}}{\empty 2}\test{\getrefbykeydefault{foo}{empty default}}{\empty 1}\test{\getrefbykeydefault{foo}{empty default}}{\empty 2}\test{\getrefbykeydefault{foo}{page}{empty default}}{\empty 1}\test{\getrefbykeydefault{foo}{name}{empty default}}{\empty 2}\test{\getrefbykeydefault{foo}{anchor}{empty default}}{\empty default}\test{\getrefbykeydefault{foo}{url}{empty default}}{\empty default}\test{\getrefbykeydefault{foo}{title}{empty default}}{\empty default}
\msg{} \def\r@foo{{}{}{}{}{}{}{}{}{}{}{}\def\Test#1#2\{\test{#1{foo}#2}{}\}} \def\TestGroup{\Test\getrefnumber\Test\getpagerefnumber}
\texttt{\_Test\getrefbykeydefault{\{\}}{\}}
\%
\texttt{\Test\getrefbykeydefault{\{page\}}{\}}
\%
\texttt{\Test\getrefbykeydefault{\{anchor\}}{\}}
\%
\texttt{\Test\getrefbykeydefault{\{name\}}{\}}
\%
\texttt{\Test\getrefbykeydefault{\{url\}}{\}}
\%
\}
\texttt{\TestGroup}
\texttt{\Test\getrefbykeydefault{\{title\}}{\}}
\%
\texttt{\msg{}}
\texttt{\def\r@foo{\par\par\par\par\par\par\par\par}}
\%
\texttt{\long\def\Test#1#2{}}
\%
\texttt{\test{#1{foo}#2}{\par}}
\%
\texttt{\TestGroup}
\texttt{\test{\getrefbykeydefault{\{title\}}{\}}{\}}
\%
\texttt{\msg{}}
\texttt{\long\def\Test#1#2{}}
\%
\texttt{\test{#1{foo}#2}{}}
\%
\texttt{\TestGroup}
\texttt{\msg{}}
\texttt{\def\r@foo{{ }{ }{ }{ }{ }}}
\%
\texttt{\long\def\TestDefault#1{}}
\%
\begin{group}
\texttt{\setrefcountdefault{#1}}
\%
\texttt{\test{\getrefnumber{foo}}{#1}}
\%
\texttt{\test{\getpagerefnumber{foo}}{#1}}
\%
\end{group}
\%
\texttt{\TestDefaultX{}}
\%
\texttt{\let\r@foo@undefined}
\%
\texttt{\TestDefaultX{}}
\%
\texttt{\let\r@foo@relax}
\%
\texttt{\TestDefaultX{}}
\%
\texttt{\def\r@foo{}}
\%
\texttt{\TestDefaultX{}}
\%
\texttt{\msg{}}
\texttt{\long\def\Test#1#2#3#4{}}
\%
\begin{group}
\texttt{\def\TestTask{\#1}}
\%
\texttt{\@onelevel@sanitize\TestTask}
\%
\texttt{\msg{\star{\TestTask}}}
\%
\texttt{\edef\TestResultA{\IfRefUndefinedExpandable{\#1}{\#2}{\#3}{}}}\%
\texttt{\IfRefUndefinedBabel{\#1}{}}\%
\texttt{\def\TestResultB{\#2}{}}\%
\texttt{\def\TestExpected{\#3}}\%
\texttt{\ifx\TestResultA\TestExpected}
\%
\texttt{\msg{\space ok.}}\%
\texttt{\end{group}
\texttt{\elsee}
\begin{group}
\texttt{\@onelevel@sanitize\TestResultA}
\%
\texttt{\@onelevel@sanitize\TestExpected}
\%
\texttt{\msg{\space Result: \TestResultA}}\%
\texttt{\msg{\space Expected: \TestExpected}}\%
\end{group}
\texttt{\input{test2}}
\section{Hello World}
\label{sec:hello}
\section{\hbox{xy}}
\label{sec:foo}
\begin{verbatim}
\makeatletter
\@ifundefined{r@sec:hello}{%
\typeout{==> Compile twice!}%
}{%
\def\test#1#2{%
\begingroup
\def\TestTask{#1}%
\@onelevel@sanitize\TestTask
\typeout{* \TestTask}%
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\TestResult
\expandafter\expandafter\expandafter{#1}%
\def\TestExpected{#2}%
\ifx\TestResult\TestExpected
\typeout{ \space ok.}%
\else
\@onelevel@sanitize\TestResult
\@onelevel@sanitize\TestExpected
\typeout{ \space Result: \space\space[\TestResult]}%
\typeout{ \space Expected: [\TestExpected]}%
\errmessage{Test failed!}%
\endgroup
\fi
\endgroup
}
\end{verbatim}
3.3 Test with package titleref
\NeedsTeXFormat{LaTeX2e}
\documentclass{article}
\usepackage{refcount}[2016/05/16]
\usepackage{nameref}
\usepackage{titleref}
\begin{document}
\section{Hello World}
\label{sec:hello}
\section{\hbox{xy}}
\label{sec:foo}
\makeatletter
\@ifundefined{r@sec:hello}{%
\typeout{==> Compile twice!}%
}{%
\def\test#1#2{%
\begingroup
\def\TestTask{#1}%
\@onelevel@sanitize\TestTask
\typeout{* \TestTask}%
\expandafter\expandafter\expandafter\def
\expandafter\expandafter\expandafter\TestResult
\expandafter\expandafter\expandafter{#1}%
\def\TestExpected{#2}%
\ifx\TestResult\TestExpected
\typeout{ \space ok.}%
\else
\@onelevel@sanitize\TestResult
\@onelevel@sanitize\TestExpected
\typeout{ \space Result: \space\space[\TestResult]}%
\typeout{ \space Expected: [\TestExpected]}%
\endgroup
\fi
\endgroup
}
\end{verbatim}
\end{document}
660 \errmessage{Test failed!}\%
661 \fi
662 \endgroup
663 \%
664 \test{\getrefbykeydefault{sec:hello}{title}{}}{Hello World}\%
665 \test{\getrefbykeydefault{sec:foo}{title}{}}{\hbox{xy}}\%
666 \begingroup
667 \def\hbox#1{[#1]}% hash-ok
668 \test{\getrefbykeydefault{sec:foo}{title}{}}{\hbox{xy}}%
669 \endgroup
670 \}
671 \makeatother
672 \end{document}
673 ⟨/test3⟩
674 ⟨*test5⟩
675 \NeedsTeXFormat{LaTeX2e}
676 \documentclass{book}
677 \usepackage{refcount}[2016/05/16]
678 \usepackage{zref-runs}
679 \newcounter{test}
680 \begin{document}
681 \ifnum\zruns>1 %
682 \makeatletter
683 \def\Test#1#2#3{%
684 \begingroup
685 \setcounter{test}{10}%
686 \sbox0{#1{test}{#2}%
687 \ifnum#3=\value{test}%
688 \else
689 \PackageError{test}{\string#1{#2} <> #3 (\the\value{test})}%
690 \fi
691 %
692 \ifdim\wd0=0pt %
693 \else
694 \PackageError{test}{Non-empty box}@ehc
695 \fi
696 \endgroup
697 }%
698 \makeatother
699 \Test\setcounterpageref{ch:two}{1}%
700 \Test\setcounterpageref{ch:three}{3}%
701 \Test\setcounterpageref{ch:four}{5}%
702 \Test\setcounterpageref{ch:five}{7}%
703 \Test\setcounterpageref{ch:six}{9}%
704 \Test\setcounterpageref{ch:seven}{13}%
705 \Test\addtocounterpageref{ch:two}{1}%
706 \Test\addtocounterpageref{ch:three}{1}%
707 \Test\addtocounterpageref{ch:four}{11}%
708 \Test\addtocounterpageref{ch:five}{17}%
709 \Test\addtocounterpageref{ch:six}{19}%
710 \Test\addtocounterpageref{ch:seven}{23}%
711 \Test\setcounterref{ch:two}{1}%
712 \Test\setcounterref{ch:three}{2}%
713 \Test\setcounterref{ch:four}{11}%
714 \Test\addtocounterref{ch:two}{11}%
715 \Test\addtocounterref{ch:three}{12}%
716 \Test\addtocounterref{ch:four}{21}%
717 \fi
718 \frontmatter
719 \chapter{Chapter one}\label{ch:one}
720 \cleardoublepage
4 Installation
4.1 Download
Package. This package is available on CTAN:\(^1\):
Bundle. All the packages of the bundle ‘oberdiek’ are also available in a TDS compliant ZIP archive. There the packages are already unpacked and the documentation files are generated. The files and directories obey the TDS standard.
- **CTAN:install/macros/latex/contrib/oberdiek.tds.zip**
*TDS* refers to the standard “A Directory Structure for *L*AT*EX* Files” (CTAN:tds/tds.pdf). Directories with *texmf* in their name are usually organized this way.
4.2 Bundle installation
Unpacking. Unpack the **oberdiek.tds.zip** in the TDS tree (also known as *texmf* tree) of your choice. Example (linux):
```
unzip oberdiek.tds.zip -d ~/texmf
```
Script installation. Check the directory TDS:scripts/oberdiek/ for scripts that need further installation steps. Package *attachfile2* comes with the Perl script *pdfatfi.pl* that should be installed in such a way that it can be called as *pdfatfi*. Example (linux):
```
chmod +x scripts/oberdiek/pdfatfi.pl
cp scripts/oberdiek/pdfatfi.pl /usr/local/bin/
```
4.3 Package installation
Unpacking. The **.dtx** file is a self-extracting docstrip archive. The files are extracted by running the **.dtx** through plain *L*AT*EX*:
```
tex refcount.dtx
```
\(^1\)http://ctan.org/pkg/refcount
TDS. Now the different files must be moved into the different directories in your installation TDS tree (also known as `texmf` tree):
- `refcount.sty` → `tex/latex/oberdiek/refcount.sty`
- `refcount.pdf` → `doc/latex/oberdiek/refcount.pdf`
- `test/refcount-test1.tex` → `doc/latex/oberdiek/test/refcount-test1.tex`
- `test/refcount-test2.tex` → `doc/latex/oberdiek/test/refcount-test2.tex`
- `test/refcount-test3.tex` → `doc/latex/oberdiek/test/refcount-test3.tex`
- `test/refcount-test4.tex` → `doc/latex/oberdiek/test/refcount-test4.tex`
- `test/refcount-test5.tex` → `doc/latex/oberdiek/test/refcount-test5.tex`
- `refcount.dtx` → `source/latex/oberdiek/refcount.dtx`
If you have a `docstrip.cfg` that configures and enables `docstrip`'s TDS installing feature, then some files can already be in the right place, see the documentation of `docstrip`.
4.4 Refresh file name databases
If your \TeX\ distribution (\TeX\, \LaTeX\, \ldots) relies on file name databases, you must refresh these. For example, \TeX\ users run `texhash` or `mktexlsr`.
4.5 Some details for the interested
Unpacking with \LaTeX. The `.dtx` chooses its action depending on the format:
- \plain\TeX: Run `docstrip` and extract the files.
- \LaTeX: Generate the documentation.
If you insist on using \LaTeX for `docstrip` (really, `docstrip` does not need \LaTeX), then inform the autodetect routine about your intention:
```
latex \let\install=y\input{refcount.dtx}
```
Do not forget to quote the argument according to the demands of your shell.
Generating the documentation. You can use both the `.dtx` or the `.drv` to generate the documentation. The process can be configured by the configuration file `ltxdoc.cfg`. For instance, put this line into this file, if you want to have A4 as paper format:
```
\PassOptionsToClass{a4paper}{article}
```
An example follows how to generate the documentation with `pdflatex`:
```
pdflatex refcount.dtx
makeindex -s gind.ist refcount.idx
pdflatex refcount.dtx
makeindex -s gind.ist refcount.idx
pdflatex refcount.dtx
```
5 Catalogue
The following XML file can be used as source for the \TeX Catalogue. The elements `caption` and `description` are imported from the original XML file from the Catalogue. The name of the XML file in the Catalogue is `refcount.xml`.
```
<?xml version='1.0' encoding='us-ascii'?>
<!DOCTYPE entry SYSTEM 'catalogue.dtd'>
<entry datestamp='$Date$' modifier='$Author$' id='refcount'>
<name>refcount</name>
</entry>
```
740 (`catalogue`)
741 <xml version='1.0' encoding='us-ascii'?>
742 <!DOCTYPE entry SYSTEM 'catalogue.dtd'>
743 <entry datestamp='$Date$' modifier='$Author$' id='refcount'>
744 <name>refcount</name>
```
Provides commands \texttt{\setcounterref} and \texttt{\addtocounterref} which use the section (or whatever) number from the reference as the value to put into the counter, as in:
\begin{verbatim}
...\label{sec:foo}
...
\setcounterref{foonum}{sec:foo}
\end{verbatim}
Commands \texttt{\setcounterpageref} and \texttt{\addtocounterpageref} do the corresponding thing with the page reference of the label.
No \texttt{.ins} file is distributed; process the \texttt{.dtx} with plain \TeX{} to create one.
The package is part of the \texttt{xref refid='oberdiek'}oberdiek\texttt{xref} bundle.
6 History
[1998/04/08 v1.0]
- First public release, written as answer in the newsgroup \texttt{comp.text.tex}:
“Re: Adding a \texttt{ref} to a counter?”\textsuperscript{2}
[2000/09/07 v2.0]
- Documentation added.
- LPPL 1.2
- Package rewritten, new commands added.
[2006/02/20 v3.0]
- Support for \texttt{hyperref} and \texttt{nameref} improved.
- Support for \texttt{titleref} and \texttt{babel}’s shorthands added.
- New: \texttt{\refused}, \texttt{\getrefbykeydefault}
\textsuperscript{2}Url: http://groups.google.com/group/comp.text.tex/msg/c3f2a135ef5ee528
[2008/08/11 v3.1]
- Code is not changed.
- URLs updated.
[2010/12/01 v3.2]
- \IfRefUndefinedExpandable and \IfRefUndefinedBabel added.
- \getrefnumber, \getpageregnumber, \getrefbykeydefault are expandable in exact two expansion steps.
- Non-expandable macros are made robust.
- Test files added.
[2011/06/22 v3.3]
- Bug fix: \rc@refused is undefined for \setcounterpageref and similar macros. (Bug found by Marc van Dongen.)
[2011/10/16 v3.4]
- Bug fix: \setcounterpageref and \addtocounterpageref fixed. (Bug found by Staz.)
- Macros \setaddtocounter{page}{ref} are made robust.
[2016/05/16 v3.5]
- Documentation updates.
7 Index
Numbers written in italic refer to the page where the corresponding entry is described; numbers underlined refer to the code line of the definition; plain numbers refer to the code lines where the entry is used.
Symbols
\# ............................................. 365
\% ............................................. 441
\@ ............................................. 366, 439, 471
\@PackageError 127
\@PackageWarning 222
\@sbc 130, 695
\@empty 318
\@firstofone 374, 377
\@gobble 371, 379
\@ifdefinable 136
\@ifundefined 639
\@latex@warning 228
\@nil . . 245, 270, 284, 311, 317, 318, 320, 324, 328, 332, 336, 340, 343, 344
\@onelevel@sanitize . . 477, 483, 498, 509, 510, 583, 596, 597, 607, 608, 645, 656, 657
\@undefined 58, 573, 618
\\ . . 440, 532, 536, 537, 538, 539, 540, 541, 542, 545, 548, 555
\{ ............................................. 363
\} ............................................. 364
A
\addtocounter 253, 259
\addtocounterpageref 258, 706, 707, 708, 709, 710, 711, 762
\addtocounterref 252, 715, 716, 717, 752
\advance . . 404, 412, 427
\aftergroup 29
\appendix 730
B
\begin . . 632, 680
\body 383, 387
C
\catcode . . 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 69, 70, 72, 73, 74, 78, 79, 80, 81, 82, 83, 84, 87, 88, 90, 91, 92, 93, 97, 99, 363, 364, 365, 366, 401, 410, 418, 422, 439, 440, 441, 471
|
{"Source-Url": "http://ctan.unsw.edu.au/macros/latex/contrib/oberdiek/refcount.pdf", "len_cl100k_base": 8530, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 66045, "total-output-tokens": 10387, "length": "2e13", "weborganizer": {"__label__adult": 0.0002321004867553711, "__label__art_design": 0.0006260871887207031, "__label__crime_law": 0.0002541542053222656, "__label__education_jobs": 0.0007877349853515625, "__label__entertainment": 0.0001251697540283203, "__label__fashion_beauty": 0.00010257959365844728, "__label__finance_business": 0.0002791881561279297, "__label__food_dining": 0.0001914501190185547, "__label__games": 0.0006966590881347656, "__label__hardware": 0.00034546852111816406, "__label__health": 0.00012254714965820312, "__label__history": 0.0002206563949584961, "__label__home_hobbies": 0.00011169910430908204, "__label__industrial": 0.0002008676528930664, "__label__literature": 0.00027441978454589844, "__label__politics": 0.0002027750015258789, "__label__religion": 0.00029587745666503906, "__label__science_tech": 0.005176544189453125, "__label__social_life": 0.00014388561248779297, "__label__software": 0.1387939453125, "__label__software_dev": 0.85009765625, "__label__sports_fitness": 0.000133514404296875, "__label__transportation": 0.00012624263763427734, "__label__travel": 0.00021636486053466797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23918, 0.06156]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23918, 0.26336]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23918, 0.53019]], "google_gemma-3-12b-it_contains_pii": [[0, 2078, false], [2078, 3947, null], [3947, 5996, null], [5996, 5996, null], [5996, 6546, null], [6546, 7659, null], [7659, 8415, null], [8415, 8544, null], [8544, 8544, null], [8544, 9063, null], [9063, 9922, null], [9922, 9938, null], [9938, 11454, null], [11454, 13208, null], [13208, 14825, null], [14825, 16559, null], [16559, 18019, null], [18019, 20703, null], [20703, 21865, null], [21865, 23918, null], [23918, 23918, null], [23918, 23918, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2078, true], [2078, 3947, null], [3947, 5996, null], [5996, 5996, null], [5996, 6546, null], [6546, 7659, null], [7659, 8415, null], [8415, 8544, null], [8544, 8544, null], [8544, 9063, null], [9063, 9922, null], [9922, 9938, null], [9938, 11454, null], [11454, 13208, null], [13208, 14825, null], [14825, 16559, null], [16559, 18019, null], [18019, 20703, null], [20703, 21865, null], [21865, 23918, null], [23918, 23918, null], [23918, 23918, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23918, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23918, null]], "pdf_page_numbers": [[0, 2078, 1], [2078, 3947, 2], [3947, 5996, 3], [5996, 5996, 4], [5996, 6546, 5], [6546, 7659, 6], [7659, 8415, 7], [8415, 8544, 8], [8544, 8544, 9], [8544, 9063, 10], [9063, 9922, 11], [9922, 9938, 12], [9938, 11454, 13], [11454, 13208, 14], [13208, 14825, 15], [14825, 16559, 16], [16559, 18019, 17], [18019, 20703, 18], [20703, 21865, 19], [21865, 23918, 20], [23918, 23918, 21], [23918, 23918, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23918, 0.01178]]}
|
olmocr_science_pdfs
|
2024-12-05
|
2024-12-05
|
eb7059beffc37f7ea4ba0d1e97204f0fff6522d5
|
A High Performance Memory Key-Value Database Based on Redis
Qian Liu*, Haolin Yuan
First Research Institute of the Ministry of Public Security of RPC, Beijing, China.
* Corresponding author. Email: liuqian1104@126.com
Manuscript submitted January 10, 2019; accepted February 20, 2019.
doi: 10.17706/jcp.14.3.170-183
Abstract: This paper proposes a high-performance memory key-value database Redis++. In the memory management mechanism, Redis++ can apply and release a fixed-size memory segment from the system. The data in each memory segment is stored consecutively, and the memory is reclaimed based on the profit evaluation value. Secondly, a cache-friendly hash index structure is designed and the structure uses two-level index which can solve the hash collision to complete per search which needs cache mapping only once if possible. In addition, using the SIMD instruction set to realize instruction-level parallelism, which speeds up the search efficiency of the secondary index. The experiments prove the effect of Redis++ on memory utilization, system latency, and throughput.
Key words: In-memory database, memory segment, profit evaluation model, two-level hash index.
1. Introduction
With the rapid development of computer hardware technology and the continuous reduction of memory cost, it becomes feasible for database management system to put its working data set into memory completely. Compared with the conventional disk database, the in-memory database has faster data-storage speed, higher throughput, and stronger concurrent access capability, which meets the fast response requirements of many applications. Memcached [1], MICA [2] and Redis [3] are among several representative products, but these products still have performance bottlenecks in memory fragmentation and cache miss.
In Linux system, all memory allocation must start at an address that is evenly divisible by 4, 8 or 16 (depending on the processor architecture) or is determined by the paging mechanism of the MMU (memory management unit). The memory manager can only obtain fixed-size memory pages when applying for memory from the system, so the extra space created by the difference between the size of the memory allocated and the actual size required by the applicant is called internal memory fragmentation. In addition, the frequent allocation and release of variable-length memory space can result in a large number of non-consecutive small memory segments interspersed among the allocated memory segments, produced the external memory fragmentation.
The latest version of Redis currently uses Jemalloc [4] as its memory management module by default. Jemalloc makes the size of allocated and released memory segments conform to certain rules and reduces the generation of external fragmentation by classifying the memory allocation request. However, this design is not optimized for the problem of internal fragmentation, and the common scenario of Redis is
caching. In order to process the writing and expiration of variable-length data, Redis needs to apply and release memory frequently to the system, which leads to increasing memory occupied by Redis and increasing fragmentation rate.
In order to test the actual memory usage performance of the memory allocator supported by Redis, related experiments were designed for verification. The test data set is designed as shown in Table 1.
### Table 1. The Memory Utilization Dataset
<table>
<thead>
<tr>
<th>Dataset</th>
<th>Before (Byte)</th>
<th>Delete</th>
<th>After (Byte)</th>
</tr>
</thead>
<tbody>
<tr>
<td>W₁</td>
<td>100</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<td>W₂</td>
<td>100</td>
<td>0%</td>
<td>130</td>
</tr>
<tr>
<td>W₃</td>
<td>100</td>
<td>50%</td>
<td>130</td>
</tr>
<tr>
<td>W₄</td>
<td>100</td>
<td>90%</td>
<td>130</td>
</tr>
<tr>
<td>W₅</td>
<td>100-200</td>
<td>N/A</td>
<td>N/A</td>
</tr>
<tr>
<td>W₆</td>
<td>100-200</td>
<td>0%</td>
<td>200-1000</td>
</tr>
<tr>
<td>W₇</td>
<td>100-200</td>
<td>50%</td>
<td>200-1000</td>
</tr>
<tr>
<td>W₈</td>
<td>100-200</td>
<td>90%</td>
<td>200-1000</td>
</tr>
</tbody>
</table>
In this experiment, Redis's maximum memory usage parameter is set to 10 GB, and the elimination policy is set to allkeys-random. That is, when the data stored by Redis exceeds 10 GB, existing data will be randomly eliminated to ensure that valid data does not occupy more than 10 GB of memory. Each test is divided into three steps. The first step is to generate a test data set that conforms to the distribution shown in the Before column in Table 1. Such as the test data set for $W₁$ is composed of key-value pairs with a fixed size of 100 bytes. The $W₅$ test data set consists of key-value pairs with a value range of 100 to 200 bytes. The total size of each test data set is 10 GB, and then the data sets are written to Redis. The second step is to delete the data in Redis as shown in the Delete column. The third step is basically the same as the first step, but the value size distribution of the data set is modified as shown in the After column.

The test results are shown in Fig. 1. Jemalloc, Tcmalloc [5], and Glibc all have memory fragmentation problems. Jemalloc performed best, followed by Tcmalloc, and Glibc had more serious fragmentation problem. Jemalloc is only slightly inferior to Tcmalloc under $W₄$ and $W₆$, so Redis chooses Jemalloc as its memory allocator by default. The memory fragmentation rate under $W₅$ and $W₆$ is significantly higher than other tests. It is because other tests firstly perform some delete operations while no deletions are performed in $W₂$ and $W₆$. From this experiment, we can see that there are some memory fragmentation problems in current allocators when dealing with variable-length data. Therefore, it is necessary to design a new memory management mechanism to improve the memory utilization of Redis.
In addition, the index structure is another key factor affecting the performance of the in-memory database. Because memory has better random read/write performance than disk, the index structure of the
in-memory database is designed to improve cache utilization rather than increasing disk I/O efficiency by converting random reads and writes to sequential reads and writes.
The Cache is located between CPU and DRAM. It is a memory with a small capacity but fast read/write speed. The Cache capacity is limited, so how to increase the Cache utilization is the key to improving the overall system performance. Redis currently uses the method of chain address to resolve hash collision. This method is simple to implement and easy to debug. However, with the increase of data in hash table, each query needs to traverse the entire linked list so that a large number of pointer random access seriously affect the cache hit rate. This paper uses the perf software to track the Cache-miss events during the running of Redis. The results are shown in Table 2.
Table 2. The Cache Miss Percentage of Redis
<table>
<thead>
<tr>
<th>Function</th>
<th>Cache Miss Percentage (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>siphash</td>
<td>22.5</td>
</tr>
<tr>
<td>dictFind</td>
<td>18.9</td>
</tr>
<tr>
<td>dictSdsHash</td>
<td>15.8</td>
</tr>
<tr>
<td>dictSdsKeyCompare</td>
<td>15.8</td>
</tr>
<tr>
<td>dictRehash</td>
<td>8.5</td>
</tr>
<tr>
<td>memcmp</td>
<td>6.0</td>
</tr>
<tr>
<td>other</td>
<td>12.5</td>
</tr>
</tbody>
</table>
From this experiment, we can see that the Cache-miss event triggered by the hash table related function call accounted for about 77% of the total. This indicates that the current hash table design of Redis does not make full use of Cache, and how to reduce cache-miss effectively will become the key point to improve the overall performance of the system. To that end, the primary contributions of this paper are as follows:
a) A segmented memory management mechanism was proposed. Under this mechanism, Redis++ will only apply to system for memory space and release it in units of 8 MB fixed segments. It can avoid the problems of external memory fragmentation caused by the system’s frequent allocating and recycling memory space of different sizes. At the same time, the use of the smart data structures and read-write strategies allows data to be stored consecutively in each memory segment, which avoids internal memory fragmentation. In addition, in order to improve memory utilization, an efficient memory reclaim strategy was proposed.
b) A cache-friendly hash table is designed as the index structure of Redis++ to solve the problem of low cache utilization. The index structure divides the 64-bit hash value into the first 48 bits and the last 16 bits. The first 48 bits are used as the first-level index to perform hash bucket mapping, the latter 16 bits are used as secondary indexes in the hash bucket to support the specific positioning of index items in the bucket. Compared to the traditional hash index, the proposed hash index only needs one cache mapping. It greatly reduces the probability of cache misses and improves cache utilization.
The rest of the paper is organized as follows: Section 2 introduces the related works. Section 3 describes the memory management mechanism of Redis++. Section 4 presents the two-level hash index of Redis++. Section 5 shows our experimental results. Finally, the paper is concluded in Section 6.
2. Related Work
2.1. Memory Management
Memcached [6] uses a similar Linux kernel’s slab algorithm for memory management. It divides the applied memory space into multiple 1 MB slab. Each slab block is divided into chunks of a fixed size, and slabs with the same size of chunks belong to the same class. The slab algorithm uses the growth factor to determine the growth rate of the chunk size between adjacent class. Memcached selects a class whose
chunk size is the closest to the current key-value data to store when inserting new data. This design can reduce the memory fragmentation and improve the memory utilization, but it cannot deal with the data skew.
Memc3 [7] uses the cuckoo hash algorithm to optimize the index structure of Memcached, and uses the idea of clock replacement algorithm to improve LRU (least recently used) strategy. The basic idea of the cuckoo hashing algorithm is simply to provide two index positions for each key value pair data through two hash functions. When a new data is inserted, it can select one of two index locations for storage. If both index positions are already occupied, it randomly selects one of the two locations for replacement. The replaced data is stored in its other index position. If the position is also occupied, the replacement operation will be triggered again until an empty position is found or the number of replacements reaches the set threshold. If it is the latter, then the reconstruction of the hash table will be triggered. The cuckoo hash algorithm can make the load factor of the hash table, that is, the hash bucket usage rate as high as possible. In addition, this method can reduce the waste of pointer space compared to using the open chain method to solve the hash conflict, because each value field in the open chain hash table will carry a pointer to point to the next node. However, this pointer is not needed in the cuckoo hash index, and each value field of the hash table stores only the key value data.
MongoDB [8] is a documented NoSQL database. It uses a memory-mapping mechanism to manage data. It maps disk files to memory, and accesses the data on the disk through pointer access. This speeds up data access because it avoids system calls of file operations and the overhead of data copying between kernel space and user space.
RAMCloud [9] utilizes a log structure memory management mechanism. It only applies and releases a fixed 8 MB memory space, called Segment, and indexes these segments through a hash table. These Segments only allow supplementary write operations. The update operation is transformed into writing new data additionally with a higher version number. The delete operation is transformed into writing additional tombstone data to indicate that the corresponding data has been cleared. Under this limitation, all modification operations are converted to consecutive write operations which can improve the Cache hit rate. And the application and release of the variable-length memory space are avoided so that the memory fragmentation rate is reduced. However, this approach leaves a large amount of invalid data in the segment when the update and delete operations are frequent.
2.2. Index Structure
The common index structures are tree index structure, bitmap index structure and hash index structure [10]. Bitmap indexing is the most memory-efficient indexing structure. This indexing structure allows each string to be equivalently replaced by a fixed-length binary expression to efficiently store key-value pairs through hash map. However, bitmap index usually has weaker support for update operations. Athanassoulis et al [11] proposed the Upbit which adds an additional update vector for each bit vector. All update operations will be performed on the update vector, and bit vector will be updated when it is read in the next time. Although Upbit alleviates the overhead of update operations to some extent, bitmap indexes are still somewhat inefficient when dealing with write-intensive request load compared to other index structures. The tree index structure is not only widely used in the traditional hard disk database, but also has many optimization solutions in the in-memory database. FAST [12], HAT-trie [13] and ART [14] designed the nodes of the tree in terms of the size of the cache mapping unit in order to improve the cache utilization. In addition, FAST and ART skillfully design data layout to use SIMD (single instruction multiple data) instruction set to implement instruction-level concurrency efficiency. Mao et al [15] designed a multi-layer tree structure with multiple B+ trees coupled and used data pre-fetching techniques to improve tree traversal efficiency. The advantage of the tree index structure is that it can support efficient range
search operations and can save space and provide prefix-matching lookups when storing string data with a common prefix. However, the search operation of the tree index structure needs node traversal of the tree, so the single point search efficiency is usually lower than the hash index.
3. Segmented Memory Management Mechanism
In order to solve the problem of memory fragmentation problems when Redis handles frequent insertion and deletion of variable-length data, we propose a segmented memory management mechanism. In this mechanism, Redis++ only applies and releases a fixed 8 MB memory space from the system. This avoids the external memory fragmentation problems caused by the frequent application and release of variable-length memory space. The data structure of proposed mechanism is shown in Fig. 2.
We refer to each 8 MB memory space as a Segment, and the smallest storage unit in each Segment is Object. Each Object contains 6 fields. InitialSize is an integer value, this field stores the initial size of the Object, which is the space occupied by the Object when it is inserted into the Segment. Because in each Segment, Object is stored consecutively, so in order to provide in-place update functionality, it needs to check whether the size of the updated Object exceeds its initial size when the content stored on Object is updated, so as to avoid overwriting part data of the next Object after the update. If the size of the updated Object exceeds the initial size, the original Object is deleted and the updated Object is inserted as new object at the place pointed by the Head pointer. The Head pointer always points to the end of the current Segment where it can be written. Index is a long integer value, which stores the index information of the object. The first 48 bits store the subscript of the hash bucket where the index information is located, and the last 16 bits store the tag value of the index information, which will be detailed in the next section. When an object is deleted, Redis++ does not actually delete the object and deallocate the space it occupies. Instead, it sets the Object’s Index to 0 to indicate that the Object has been expired. Expire is a time type that stores the object’s timeout elimination time. KeyLen is an integer value, which stores the Key string length of the Object, so that it can use a more efficient memcpy function instead of strcpy function to match the string. The Key and Value field stores the string of the Object’s Key and Value, respectively.

The Segment Index is an array that stores the meta information of the Segment. Each array element contains three fields. The first field Used is an integer value that stores the number of bytes that have been occupied in the Segment. The second field Num is an integer value that stores the number of valid objects in the Segment. The third field SP is a pointer that stores the address of the Segment. When the occupied memory space of the Segment is released, instead of deleting the corresponding element in the Segment Index, we put the SegmentID, the array index in the Segment Index into the free queue. When the memory space pointed by the Head pointer is not enough to write new data, the SegmentID is preferentially taken from the idle queue, and the new segment will be stored in the corresponding position of the Segment Index according to the SegmentID. When there is no free space in the Segment Index, the size of the array will be
In this memory management mechanism, all write operations are in append mode, so the cache can be better used to improve write performance. However, some delete and update operations will leave invalid data in the Segment. The accumulation of these invalid data will have a serious impact on memory utilization. Therefore, we need to design a memory collection strategy to solve this problem. The memory collection strategy makes use of the fundamental idea of RAMCloud [9], and the Segment with invalid data is cleaned and reclaimed on a regular basis. When selecting the segment to be reclaimed, the profit of the reclaiming Segment will be evaluated first, and the segment with the highest profit will be selected for reclaim. The calculation formula of reclaiming profit is as follows:
\[
\frac{\text{benefit}}{\text{cost}} = \frac{(1-u) \cdot \text{Lifetime}}{u} = 1 - \frac{1}{u} \sum_{i=1}^{N} (\text{Expire}_i - \text{Current}) / N
\]
(1)
In this formula, \(u\) is the usage rate of Segment, that is, the ratio of memory space occupied by valid data to the total memory space of the Segment, and Lifetime is the average survival time of Object in the Segment, that is, the average of the absolute value of the difference between Expire and the Current time. \(N\) is the number of valid Object in the Segment. We use Lifetime to measure the stability of data in a Segment. When cache elimination strategy is set to LRU, the value of Expire is the last time of the object was accessed plus the timeout time in the system configuration. When the cache elimination policy is set to TTL, the value of Expire is the timeout of Object. The larger the value of Lifetime means that the longer the data lives in the Segment and the better the stability, because the Segment with smaller Lifetime value will generate invalid data more quickly.
Redis++ will select the Segment with the highest profit to clean and reclaim, and move its valid data in the Segment to the place pointed by the Head pointer, and deallocate the memory space occupied by the Segment.
4. Two-Level Hash Index Design
We use the xxHash function in [16] as a hash function to build a hash table, which can map an arbitrary-length string to a 64-bit hash value. Xxhash is currently one of the fastest hash functions for hashing. Under the SMHasher test set [17], xxHash can achieve a full score of 10 points in hash quality and 13.8 GB per second calculation speed. At present, the widely used hash-function MurmurHash [18] is only 2.7 GB per second, although the score of hash quality is also 10 points.
In order to minimize the cache invalidation caused by traversing the linked list when performing search operation in the hash index, we design a new hash index structure shown in Fig. 3.

The size of each hash bucket in the hash index is fixed at 64 bytes, which is exactly the same size as the
cache mapping unit of x86 architecture. This ensures that each bucket is accessed only one cache mapping is required and there is no data access across the Cache line.
The size of a pointer in a 64-bit machine is 8 bytes. If a hash index has $2^{64}$ hash buckets, the total space occupied by the hash index will exceed $8 \times 2^{64}$ bytes. But a single general server is limited to 2 TB of memory at present, so the number of buckets in the hash index cannot exceed $2^{40}$. Since we cannot directly use a 64-bit hash value as a subscript of the hash bucket in the hash index, we need to perform modulo operation so that the hash value falls within the number of hash buckets, so the hash collision rate is determined by the number of hash buckets instead of by the value range of the hash value. Therefore, Redis++ uses the first 48 bits of the 64-bit hash value as the primary index to determine the bucket index of the object in the hash table, which corresponds with the index information of the Object, and use the last 16-bit as a secondary index to perform the second search in the hash bucket to locate specific index information.
Each hash bucket is divided into three parts: Head, Offset array, and expanded Bucket ID. First, in the Head, the Num field is an 8-bit bit vector. Its highest bit is always 0. The rest of the bits indicate the validity of data of the corresponding position of the Tag array and the Offset array in the header. The bit is set to 1 to indicate that the data stored in the corresponding position is valid, and the bit is set to 0 to indicate invalid. In the hash index, each index item is divided into two parts: Tag and Offset. Tag is the last 16 bits of the Object's Key hash value, and Offset is a 48-bit vector that stores the position information of the Object in the Segment. For example, there stores two index entries in a hash bucket. The data of these two index entries are stored in Tag[1], Offset[1], Tag[3], and Offset[3], respectively. Then the binary expression of the Num field of the hash bucket is 00000101. So we can get the number of valid index in the current hash bucket by counting the number of digits set to 1 in the Num field. When the new index entry is inserted, the storage position of the new index entry is obtained by obtaining the lowest position of the zero in the Num field. When the binary expression of the Num field is 00000101, the new index entry is stored in Tag[2] and Offset[2]. The Flag field in the Head is also an 8-bit bit vector. The highest bit is also 0. The remaining bits are used to indicate whether the index entries stored in the corresponding positions in the Tag array and Offset array are native. We will expand on the specific meaning of this field in the following sections of this section.
The Tag array in the Head is used to store the Tag section of each index entry. Each Tag element has a size of 16 bits. When an Object is located in a hash bucket through the first 48 bits of the Key hash value as a primary index, and we use the next 16 bits as secondary index Tag to locate the specific Offset index information in the hash bucket. For example, when the last 16 bits of the Key hash value are equal to Tag[3] in the hash bucket, the Offset information of the Object corresponding to the Key will be stored in Offset[3]. In order to avoid the latency overhead of traversing the Tag array for comparison, we uses the SIMD instruction set to speed up the lookup process. The total size of the Head field of each hash bucket is 128 bits, which is just in accordance with the SIMD operation specification, so that each 16-bit in the Head field and the last 16 bits of Key hash value can be compared in parallel by using eight registers in one instruction cycle. By using the SIMD instruction, the comparison operations are parallelized which improves the search efficiency.
The Offset array stores the specific information for each index entry. Each element in the Offset array is a 48-bit bit vector. The first 25 bits are used to store the SegmentID of the Segment where the data of the Object is located, and the last 23 bits are used to store the offset of the Object's position in the Segment relative to the first address of the Segment. The reason for this design is that each Segment has a fixed size of 8 MB, so we can just use the 23-bit bit vector to store the offset of each Object in the Segment relative to the first address.
Each hash bucket in the index can store up to 7 valid index entries. When more than 7 objects are mapped to the same hash bucket, we need to use the expanded bucket to store these index entries. The Next field in the hash bucket is a 48-bit bit vector used to store the expanded Bucket ID. We use the square detection method to obtain the expanded bucket. For example, if the current Bucket ID is $b_1$, we will select the hash bucket with the least number of positions in the Num field set to 1 as the expanded bucket of current bucket from the five buckets whose ID in $b_1+1^2$, $b_1+2^2$, $b_1+3^2$, $b_1+4^2$, $b_1+5^2$, and its Bucket ID is stored in the Next field. The index entries that we place in the corresponding hash bucket after the first-level index mapping are called native index entries, which differentiate between these index entries and the index entries that are stored to the hash bucket through the expanded bucket mechanism. We use the Flag field in the Head to indicate which index entries in the current hash bucket are native. For example, there are 3 index entries stored in a hash bucket, and the index entries stored in $Tag[1]$, $Offset[1]$, $Tag[3]$, and $Offset[3]$ are native and the index item stored in $Tag[2]$ and $Offset[2]$ is non-native, the binary expressions of its Num field and Flag field are respectively 00000111 and 00000101. When a hash bucket and its expanded bucket have been filled with 7 valid index entries and a new index entry needs to be stored in the hash bucket, a process similar to cuckoo hash will be triggered to make room for the new index entry. For example, if there are 7 valid index entries in the bucket, the value of the Flag field is 00110111. The new index entry will replace the native index entry in the bucket. For example, the index entries in the bucket that are stored in the $Tag[1]$ and $Offset[1]$, the replaced index item will be stored in its expansion bucket, which may trigger the replacement operation again. This replacement process will continue until there is free space to store the index entry that is replaced. When there is no native index entry in the expanded hash bucket or if the replacement operation has been executed more than the configured threshold value, a rehashing process is triggered to rebuild the hash table, and the hash table is expanded. The overall structure of the hash table is shown in Fig. 4.
During the running of Redis++, we will maintain two hash table structures. The DictHt structure consists of four elements. The Table pointer stores the address of the hash index. The Size stores the number of buckets for the hash index. The value of SizeMask is Size - 1, and we set the value of Size to the integer power of 2 so that the modulo operation at the first-level index searching can be transformed into the AND operation with SizeMask to improve the efficiency. Used stores hash buckets already used in the hash index. When it need to rehash, we will initialize the second hash table structure, and set the number of hash buckets of the hash index to the twice as much as the first hash index. Then the index entries in the first hash index are migrated to the second hash index. The Ht array in the Dict structure is used to store pointers which point two hash structures, and the RehashIdx field is used to store the running state of the rehash process. The initial value of RehashIdx is -1, indicating that no rehash process is currently performed. When the value is non-negative, it indicates that the hash index of the first hash index is currently migrated. During rehashing, the read operation of the hash index is performed on both indexes, and writing operation is performed only on the second hash index. After the rehashing is completed, Redis++ will reset RehashIdx to -1, and deallocate the memory occupied by the first hash table pointer, and then swap the two hash table
By designing the size of each hash bucket skillfully, it is exactly the same size as the cache mapping unit (64 bytes), to improve the cache utilization and speed up the hash index search efficiency.
5. Experiments
5.1. Experimental Settings
We analyze Redis++’s memory utilization, response latency and throughput. The experimental environment is shown in Table 3.
<table>
<thead>
<tr>
<th>Hardware</th>
<th>Settings</th>
</tr>
</thead>
<tbody>
<tr>
<td>CPU</td>
<td>Intel Xeon E5-2698 v3 2.30 Ghz (dual-16cores)</td>
</tr>
<tr>
<td>DRAM</td>
<td>DDR4-2133 128 GB</td>
</tr>
<tr>
<td>NIC</td>
<td>Intel 82599ES 10 Gigabit Ethernet Controller</td>
</tr>
</tbody>
</table>
Facebook performs a statistical analysis of the dataset handled by Memcached cluster in a production environment, indicating that almost all requests in its online environment contain no more than 100 bytes of Key, and more than 95% of its requests Value is less than 1024 bytes in length [19]. Therefore, we designed three test datasets with different data size distributions, as shown in Table 4. The Key and Value of the three test datasets are random strings, except that the 5% Value is between 1,024 and 10,240 bytes in length, and the remaining 95% of Value are less than 1,024 in length. We choose Redis 4.0.6 as baseline system.
<table>
<thead>
<tr>
<th>Scale</th>
<th>Key (Bytes)</th>
<th>95% Value (Bytes)</th>
<th>5% Value (Bytes)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiny</td>
<td>8</td>
<td>8-16</td>
<td>1024-10240</td>
</tr>
<tr>
<td>Small</td>
<td>16</td>
<td>16-128</td>
<td>1024-10240</td>
</tr>
<tr>
<td>Large</td>
<td>128</td>
<td>128-1024</td>
<td>1024-10240</td>
</tr>
</tbody>
</table>
5.2. Memory Utilization
We designed the four test datasets shown in Table 5 to show the memory utilization of Redis++.
<table>
<thead>
<tr>
<th>Dataset</th>
<th>Before (Byte)</th>
<th>Delete</th>
<th>After (Byte)</th>
</tr>
</thead>
<tbody>
<tr>
<td>W₁</td>
<td>100</td>
<td>0%</td>
<td>130</td>
</tr>
<tr>
<td>W₂</td>
<td>100</td>
<td>50%</td>
<td>130</td>
</tr>
<tr>
<td>W₃</td>
<td>100-200</td>
<td>0%</td>
<td>200-1000</td>
</tr>
<tr>
<td>W₄</td>
<td>100-200</td>
<td>50%</td>
<td>200-1000</td>
</tr>
</tbody>
</table>
We set the maximum memory usage limit of Redis and Redis++ to 10 GB, and set the memory elimination strategy to random elimination. When the memory of Redis and Redis++ reaches the upper limit and new data needs to be written, it will randomly evict data from existing data until there is enough space to store newly written data. At the same time, we activated the memory fragmentation cleaning function supported by Redis after version 4.0, and set the threshold for Redis and Redis++ on memory cleanup to start memory clean up when there is more than 10% of fragmentation in memory.
The experiment is divided into three steps. In the first step, random strings with a total size of 20 GB are generated as the test data set. All length of Key is fixed at 100 bytes, and the length of Value is shown in the Before column in Table 5. Then writing the Key-Value pairs of the test data set into the system in turn. The
The second step is to delete the currently stored data according to the proportion value shown in the *Delete* column in Table 5. The third step is basically the same as the first step, except that the length of the generated test data set is shown in the *After* column in Table 5.
The experimental results are shown in Fig. 5. We can see that Redis++ achieves high memory utilization through memory reclaim mechanism. Whether the memory recovery mechanism is efficient depends on the appropriateness of the design of the return formula in (1). The formula can be divided into two parts: utilization \((1-u)/u\) and stability \((\text{Lifetime})\). How to balance the weight of these two parts is important. If the weight of utilization is given too high, the memory reclaim will appear to be too greedy. And it is more likely to get the *Segment* with the local optimal reclaiming benefit for cleaning and reclaiming. Because the segment whose stability is poor will have its utilization reach the new lowest point faster, it is very likely to lose the opportunity to reach the globally optimal solution if only considering the current utilization of the *Segment*. If the weight of stability is given too high, it will lead to the higher-utilization *Segment* will also be cleaned up and reclaimed, resulting in reducing the efficiency of reclaiming.
In order to achieve a good balance between utilization and stability, we make several variations of the formula and perform some tests. We define the memory reclaim cost in memory management as:
\[
ReclaimCost = \sum_{i=1}^{N} u_i
\]
In (2), \(u_i\) is the memory usage of the *Segment* that is reclaimed, and \(N\) is the total number of the *Segment* that are reclaimed during the memory management. The smaller value of ReclaimCost indicates that the *Segment* selected for each cleaning and recycling more tend to be the globally optimal solution.
In this experiment we used two different modes of test loads. One is the random access mode. That is, the probability of occurrence of each *Key* is equal, and the test dataset is defined as the *Uniform* load. The other is the *Hot-Cold* load, that is, the occurrence number of 20% of *Keys* in the test dataset occurs 80% of the total, and the remaining 80% of *Keys* only occur 20% of the total. This test dataset is defined as the Zipf load [20]. We will perform memory reclaim that use three different reclaiming revenue formulations under these two access modes. We define the *Original* mechanism as (1), the *Greedy* mechanism is to set the stability of \(\text{Lifetime}\) in (1) to 1, and the *Modified* mechanism is to use \(\sqrt{\text{Lifetime}}\). The experimental results are shown in Fig. 6.
In Fig. 6, we can see that even though the *Greedy* mechanism performs the memory reclaim with the lowest cost under the *Uniform* load, it has the highest cost to perform memory reclaim under the *Hot-Cold* load because it only considers the segment memory utilization and falls into local optimum trap. Because *Original*'s stability in the calculation formula of recovery profit can easy interfere with the result of the final
calculation, resulting in the Original mechanism cannot handle the Uniform load well. Compared with the two mechanisms, the Modified mechanism performs best on the whole. This mechanism performs the memory reclaim with the minimum cost under Hot-Cold load, and the Hot-Cold access pattern is also more consistent with the real-world environment.

5.3. Response Delay
Request processing delay is an important indicator of system processing efficiency. In this paper, latency refers to the amount of time the client spends between sending a request to the server and receiving a reply from the server. We will test write delay and read delay for Redis++ and Redis. In this experiment, we only run a single Redis and Redis++ process, then run only one client and the client sends 1,000,000 requests to two processes respectively. We perform many tests and calculate the average delay.

The delay of read requests is shown in Fig. 7 (a). We can see that Redis++ has a delay of 22.47 microseconds when dealing with Tiny data sets, while Redis has a delay of 68.74 microseconds, and Redis++ is only a third of Redis. The delay of write requests is shown in Fig. 7 (b). We can see that when dealing with Tiny data sets, the delay of Redis++ and Redis is not significantly different from the read request delay. With the increase of the data size, the processing efficiency of the write request is significantly lower than that of the read request, but overall Redis++ request processing efficiency can be maintained steadily about three times times over Redis.
5.4. Throughput
System throughput is another important indicator to measure the efficiency of request processing of a database system. In this paper, throughput is defined as the total amount of requests processed by the system in a unit of time. We use YCSB (Yahoo! Cloud Serving Benchmark) [21] for testing. YCSB is an
open-source tool used by Yahoo to perform basic tests on NoSQL databases. In order to simulate the actual application scenario as much as possible, we will define two test loads and two access modes. A write-intensive load contains 50% of write requests and 50% of query requests, and read-intensive load contains 5% of write requests and 95% of query requests. The Unif access mode means that the Key of all requested are randomly generated with equal probability. In the Zipf access mode, the distribution of all requested Keys is in accordance with the Ziff distribution, that is, about 20% of the Keys will appear in about 80% of the requests. This is in line with the actual application scenario.
In this experiment, we will run a single Redis++ and Redis server process, with 50 client processes sending requests to the server program.
The experimental results of the write intensive load are shown in Fig. 8 (a). We can see that Redis++ can achieve throughput of 0.43 and 0.48 million requests per second in the Unif and Zipf access modes when processing Tiny datasets. And Redis can only achieve throughput of 0.12 million requests per second. Redis++’s throughput performance can reach about 4 times that of Redis. With the increase of data size, although Redis++’s throughput will be slightly dropped, it can still be maintained steadily at a relatively high level.
The experimental results of read intensive load are shown in Fig. 8 (b). When dealing with Tiny datasets, Redis++ can reach throughput of 0.48 and 0.57 million requests per second respectively in Unif and Zipf access modes respectively. And Redis is 0.14 and 0.15 million requests per second, respectively. Redis++’s throughput performance is still about 4 times that of Redis. The performance in the Zipf access mode is significantly higher than that in the Unif access mode, mainly because the cache hit rate is higher in the Zipf access mode, so the processing efficiency is higher.
From this experiment, we can see that under a variety of data sizes, the type of read/write intensive loads, and access modes, Redis++ can steadily achieve about 4 times the throughput performance of Redis.
6. Conclusion
In this paper, we select Redis that ranks the top one in market share as a benchmark, and analyzes its memory management bottlenecks. Then, we design and implement two optimization solutions and develop a high performance in-memory database Redis++ based on Redis. The experiments prove the performance improvement of Redis++ over Redis on memory utilization, processing latency and throughput. However, the optimization solutions are mainly related to the string structure, there still exists memory fragmentation and cache misses when using list, set, zset, hash, and other data structures. In the future, we will optimize the design of these data structures.
References
Qian Liu was born in Shandong province of China in 1984. She received the Ph.D degree in computer science and technology from Institute of Computing Technology Chinese Academy of Sciences in 2015. Her research interests include big data analysis, machine learning and named entity recognition.
|
{"Source-Url": "http://www.jcomputers.us/vol14/jcp1403-03.pdf", "len_cl100k_base": 9015, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 36589, "total-output-tokens": 10783, "length": "2e13", "weborganizer": {"__label__adult": 0.0004222393035888672, "__label__art_design": 0.000579833984375, "__label__crime_law": 0.0004820823669433594, "__label__education_jobs": 0.0007853507995605469, "__label__entertainment": 0.0001436471939086914, "__label__fashion_beauty": 0.00022995471954345703, "__label__finance_business": 0.0004837512969970703, "__label__food_dining": 0.0004029273986816406, "__label__games": 0.0007262229919433594, "__label__hardware": 0.01036834716796875, "__label__health": 0.0006680488586425781, "__label__history": 0.0004069805145263672, "__label__home_hobbies": 0.00015246868133544922, "__label__industrial": 0.0009279251098632812, "__label__literature": 0.00025463104248046875, "__label__politics": 0.0003490447998046875, "__label__religion": 0.0005908012390136719, "__label__science_tech": 0.4306640625, "__label__social_life": 9.006261825561523e-05, "__label__software": 0.018341064453125, "__label__software_dev": 0.53173828125, "__label__sports_fitness": 0.0002808570861816406, "__label__transportation": 0.0006890296936035156, "__label__travel": 0.00019741058349609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43957, 0.05738]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43957, 0.45173]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43957, 0.88459]], "google_gemma-3-12b-it_contains_pii": [[0, 2963, false], [2963, 6007, null], [6007, 9783, null], [9783, 14123, null], [14123, 17644, null], [17644, 20585, null], [20585, 25036, null], [25036, 28948, null], [28948, 31823, null], [31823, 34973, null], [34973, 36970, null], [36970, 39821, null], [39821, 43432, null], [43432, 43957, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2963, true], [2963, 6007, null], [6007, 9783, null], [9783, 14123, null], [14123, 17644, null], [17644, 20585, null], [20585, 25036, null], [25036, 28948, null], [28948, 31823, null], [31823, 34973, null], [34973, 36970, null], [36970, 39821, null], [39821, 43432, null], [43432, 43957, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43957, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43957, null]], "pdf_page_numbers": [[0, 2963, 1], [2963, 6007, 2], [6007, 9783, 3], [9783, 14123, 4], [14123, 17644, 5], [17644, 20585, 6], [20585, 25036, 7], [25036, 28948, 8], [28948, 31823, 9], [31823, 34973, 10], [34973, 36970, 11], [36970, 39821, 12], [39821, 43432, 13], [43432, 43957, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43957, 0.23179]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
327b0823cf848aff0ad8344bd3b0ee83b741926d
|
ICSE Guidelines
International Conference on Software Engineering (ICSE) Operating Rules and Guidelines
Updated October 20, 2019
Since 1975, the International Conference on Software Engineering (ICSE) has served as a premier forum for the presentation and exchange of the latest research results and practical experiences relating to software engineering theories, methods, techniques, tools, and practices. To ensure the continued excellence and success of the ICSE conference series.
A set of Guidelines (A-E) is appended that provide more detailed information relating to those aspects of ICSE organization, process and rules. The purpose of the guidelines is to provide guidance to all stakeholders for conducting the conference and a reference for making decisions. To reflect evolution of conference structure and scope, the operating rules and guidelines may be updated by the ICSE Steering Committee by majority vote.
I. Parties
The parties to ICSE are:
- ICSE Steering Committee (SC)
- ACM Special Interest Group in Software Engineering (SIGSOFT)
- IEEE-CS Technical Council on Software Engineering (TCSE)
- Association for Computing Machinery, Inc. (ACM)
- Institute of Electrical and Electronics Engineers (IEEE), incorporated, through its IEEE Computer Society (IEEE-CS)
II. Roles
The roles, authorities, and responsibilities with regard to ICSE are:
A. **ACM and IEEE-CS are the co-sponsors of the ICSE conference**: they are represented by their respective software engineering societies in the organization of the ICSE conference through those societies’ participation in the SC and through their review and approval of the budget for each conference. Responsibilities and services of the co-sponsors are further detailed in Guideline A.
B. **ACM and IEEE-CS alternate as the Administrative Co-sponsor (AC)**: responsibilities and services of the administrative co-sponsor as detailed in the ACM/IEEE MOU
C. The ICSE SC is responsible for constituting and guiding each edition of the conference as operated in the operating rules.
D. The ICSE SC is responsible for establishing and updating guidelines and evaluating practices for the continued scientific and financial success of ICSE.
III. Membership of the ICSE SC
A. The ICSE SC shall comprise:
- Current chair of ACM SIGSOFT
- Current chair of IEEE-CS TCSE
ICSE Guidelines
- The two most recent past ACM SIGSOFT and IEEE-CS TCSE Chairs
- All General and Program Chairs or Co-Chairs and one Software Engineering in Practice chair/year (from industry), who have been approved by the ICSE SC for future conferences
- All General and Program Chairs or Co-Chairs and one Software Engineering in Practice chair/year of the preceding three conferences
B. Representation shall reflect the goal of providing continuity, expertise, and organizational memory for ICSE planning and oversight. It shall also provide equal representation of the co-sponsors ACM and IEEE-CS and their respective software engineering societies ACM SIGSOFT and IEEE-CS TCSE.
C. The Chair of the ICSE SC shall be elected by and from among the SC members for a term of two years. The Chair must be a SC member at the time of election. The Chair will serve for two years and can be nominated for a second term regardless of the membership status.
D. The ICSE SC may formulate a process to appoint liaisons to include constituencies that may not be effectively represented in the SC. Liaisons are non-voting members and are appointed for a two-year term.
IV. Conference Sponsorship
A. ACM and IEEE-CS shall be the co-sponsors of the conference per their MOU. At the request of the ICSE SC, a Local co-sponsor may be added for up to 50% for a particular conference with ACM and IEEE splitting the remaining percentage of responsibility equally.
B. The ICSE co-sponsorship covers all conference tracks and events, the workshops and those co-located events that opt to stay within the ICSE budget. The organizers of an event who apply for co-location with ICSE will be asked to choose explicitly between taking own and separate sponsorship, or stay under the full ICSE sponsorship. In the latter case, ACM and IEEE-CS (as well as the LCS if any, see IV.C) will split evenly legal and financial liability as per ICSE. Therefore, the request for event co-location must be done normally at least eight months before the conference and should undergo the appropriate approval processes. New collocated events must be approved by the GC in consultation with ACM SIGSOFT and IEEE-CS TCSE. All co-located events within ICSE budget must fill out an ACM Preliminary Approval Form (PAF, see at http://cms.acm.org/tmrf/cms_paf.cfm) that ACM SIGSOFT will review and approve. Because handling collocated events outside ICSE sponsorship adds a burden on ICSE organizers, full ICSE sponsorship is the preferred option (and a General Chair may decide not to accept a co-located event which does not opt for this scheme). The collocated events within the ICSE Budget will need to complete the IEEE Conference Application form as well that will be reviewed and approved by TCSE.
C. For each year, part of the surplus coming to the ACM-SIGSOFT and IEEE-CS TCSE will be attributed to the conference for re-investment in future editions, granted that IEEE-CS TCSE and ACM SIGSOFT may apply to their respective shares different surplus/cost models (see Appendix). The surplus funds that IEEE-CS TCSE and ACM SIGSOFT return to the conference will be spent on enhancing the experience and augmenting the learning opportunities of the ICSE attendees, at the discretion of the GC in consultation with the Conference Operations Committee. Changes in the
ICSE Guidelines
IEEE-CS TCSE and ACM SIGSOFT funding models must be communicated to the SC 24 months in advance.
V. Publication
A. Proceedings Volumes: The proceedings will be published into multiple volumes with differing ISBN numbers, including for example:
- one volume with the just papers from the technical research track,
- one volume with the just papers from the industrial track,
- one volume with the just papers from the education track,
- one volume for all workshop proceedings,
- one volume for the remaining tracks (e.g., societal track, Doctoral Symposium, Posters, ...)
B. Timeliness of publication: Both ACM and IEEE-CS must include the proceedings of the conference, including workshop proceedings, in their respective digital libraries each year (cf. Section V-C above). Before inclusion, the papers will be checked for plagiarism. The General Chair must notify the publisher of the proceedings that the publisher is required to forward the intellectual property in electronic format to both ACM and IEEE-CS as early as possible, and in no case later than two weeks after the conference is concluded to ensure timely posting into the digital libraries. To foster early dissemination, authors of accepted papers are allowed to upload to the ICSE website a link to a preprint.
VI. Conference Rotation
As a general rule, the location of ICSE will rotate yearly among three regions: (1) Europe, (2) North America, and (3) one of Africa, Asia, Oceania, and South America. The SC, in special circumstances, can institute an exceptional change in the rotation.
VII. Responsibilities
A. ACM SIGSOFT and IEEE-CS TCSE are responsible for: the review and approval of all conference budgets; promoting and publicizing the conference; scheduling and coordinating calendars to prevent overlap of the ICSE conference with other conferences in software engineering. Specific responsibilities of the ACM SIGSOFT and IEEE-CS TCSE are enumerated in ICSE Guidelines Part A.
B. The ICSE SC is responsible for general oversight of the conference, including guiding the scope of the conference, choosing conference leaders (including General Chair and Program Co-Chairs), selecting conference locations, proposing any change in the AC rotation, and providing financial and operational guidance conforming to the policies and procedures of the co-sponsors. Information about ICSE history, reports from past organizers, specific operational expectations and procedures for an ICSE conference are maintained on the ICSE conference series home page at http://icse-
conferences.org/. Specific responsibilities of the ICSE SC are enumerated in ICSE Guidelines Part C.
C. The General Chair (GC) holds central responsibility for the overall planning and execution of an ICSE conference concerning both scientific and financial aspects. With the rest of the conference organization committee, the GC shapes the conference program and structure complying with the guidelines for conference operations set forth by the AC and the ICSE SC. Specific responsibilities of the GC are enumerated in ICSE Guidelines Part D.
D. The General Chair cannot submit to any event of the conference, including workshops or co-located events. The ICSE Program Co-Chairs cannot submit to any event within the ICSE Proceedings, including workshops, but they can submit to the co-located events. The Chairs of any Track or Workshop within the ICSE Proceedings cannot submit to their own event, but they can submit to the other tracks or workshops and the co-located events.
E. When an LCS is a co-sponsor of an ICSE conference, the specific responsibilities and authorities of the LCS must be put in writing and ratified by the SC, ACM, and IEEE-CS, in consultation with the General Chair of that conference.
VIII. Budgets and Financial Reporting
A. The General Chair of an ICSE conference shall use a single Conference Budget Form in budgeting for the conference. The General Chair shall look first to use the IEEE Conference Budget Form to provide consistency of budget information among instantiations of the conference, and in order to support consistency in ICSE conference budgeting and ease of reference. Use of the ACM TMRF is also permitted. Both societies shall approve an ICSE conference budget, on a single timeline, to allow a single notification of budget approval through the AC to the General Chair.
B. Administrative and overhead fees required by the co-sponsors shall be included in the budgeting process.
C. The AC and the General Chair (with the Financial Chair) will work diligently to present a final financial report on the conference no later than six (6) months after an ICSE conference. This report shall be approved by the SC and by ACM and IEEE-CS. The co-sponsors will receive their share of the surplus funds or will cover their share of a loss not later than 30 (thirty) days after the submission of the final financial report.
D. The ICSE SC expenses and contracted services to support conference continuity and success shall be funded via an expense line item in each ICSE’s Conference Budget Form. The amount shall be approved by the ICSE SC, ACM and IEEE-CS each year. Any expenditure shall be explicitly approved by the Chair of the ICSE SC.
IX. Non Discrimination
In line with IEEE and ACM policies, ICSE is committed to the principle that all persons shall have equal access to programs, facilities, services, and employment without regard to personal characteristics not related to the ability, performance, or qualifications as determined by IEEE and ACM policies and/or applicable laws. ACM and IEEE codes of ethics and antiharassment policies can be found in the following references:
ICSE Guidelines
- https://www.acm.org/special-interest-groups/volunteer-resources/conference-planning/opening-slide-on-acm-activities-policy
- https://www.acm.org/special-interest-groups/volunteer-resources/acm-conflict-of-interest-policy
- https://www.ieee.org/about/corporate/governance/p7-8.html
- https://www.ieee.org/about/compliance/conflict-of-interest/index.html
ICSE prohibits discrimination, harassment or bullying against any person because of age, ancestry, color, disability or handicap, national origin, race, religion, gender, sexual or affectional orientation, gender identity, appearance, matriculation, political affiliation, marital status, veteran status or any other characteristic protected by law. ICSE expects that its organizers and suppliers shall maintain an environment free of discrimination, including harassment, bullying, or retaliation when and wherever those individuals are conducting ICSE business or participating in ICSE events or activities.
X. Organizational Agreements
ACM and IEEE-CS will keep the ICSE-SC informed of organizational agreements, such as signing a new MOU.
ICSE Guidelines
ICSE Guidelines
Part A
Responsibilities and Services
of ACM SIGSOFT and IEEE CS-TCSE
I. ICSE Steering Committee Meeting Attendance
The ACM SIGSOFT and IEEE-CS TCSE Steering Committee members are expected to
attend—in person or in exceptional circumstances by teleconference—the biannual ICSE
Steering Committee meetings. These include:
- The Chair of ACM SIGSOFT
- The Chair of IEEE-CS TCSE
- The two most recent past ACM SIGSOFT Chairs
- The two most recent past IEEE-CS TCSE Chairs
- Administrative Co-Sponsor Liaisons (without vote)
II. Administrative Co-Sponsor Liaisons
- Both ACM and IEEE-CS will designate a staff person as liaison to the ICSE
conference.
III. Community Coordination and Investment
- ACM SIGSOFT and IEEE-CS TCSE are expected to act on behalf of the general
software engineering community to provide a voice on behalf of the members of their
communities to the deliberations of the ICSE SC.
- In addition to ICSE, ACM SIGSOFT and IEEE-CS TCSE each sponsor a large number
of regularly scheduled events. ACM SIGSOFT and IEEE-CS TCSE are responsible for
providing coordinated scheduling for these events so that they do not conflict with
ICSE. In particular, ACM SIGSOFT and IEEE-CS TCSE are responsible for making
best efforts not to schedule any ACM SIGSOFT and IEEE-CS TCSE-sponsored events
from being held within one week prior to or following the full week of ICSE including
its collocated events and workshops.
- Surpluses generated by the ICSE conference series, which are returned to ACM
SIGSOFT and IEEE-CS TCSE should be used by ACM SIGSOFT and IEEE-CS TCSE
to support ICSE activities (as per Section IV.D of the MOU) and the software
engineering communities through a variety of vehicles, with preference being given to
programs such as travel subsidies for students and other needy groups, achievement
and recognition awards, and subsidizing new events.
IV. Publication of Logos
- ACM SIGSOFT and IEEE-CS TCSE are responsible for monitoring ICSE products
and materials so that they bear the names and logos of ACM, IEEE, ACM SIGSOFT,
IEEE-CS TCSE, and those of any additional approved financial co-sponsors (if any)
and that the logos of the co-sponsors and the societies shall be featured equally.
Products include the ICSE proceedings and any other ICSE publications; materials
ICSE Guidelines
include web sites, calls for papers, proposals and participation, advance and final programs, and any other publicity materials.
V. Digital Libraries
- ACM SIGSOFT and IEEE-CS TCSE are responsible for monitoring their respective digital libraries to ensure that the ICSE proceedings appear immediately following ICSE each year. In particular, ACM SIGSOFT and IEEE-CS TCSE are responsible for ensuring that the ICSE proceedings appear roughly at the same time in these digital libraries.
VI. Publicity
- ACM SIGSOFT and IEEE-CS TCSE are responsible for providing advertising of ICSE through their mailing lists, websites, and publications.
- ACM SIGSOFT and IEEE-CS TCSE use their respective mailing lists to promptly distribute material provided by and by the explicit request of the General Chair.
ICSE Guidelines
ICSE Guidelines
Part B
Responsibilities and Services
of the Administrative Co-Sponsor
I. Administrative Co-Sponsor
• ACM and IEEE-CS alternate as Administrative Co-sponsor (AC) for the ICSE conference.
II. Administrative Co-Sponsor Liaisons
• Both ACM and IEEE-CS will designate a staff person as liaison to the ICSE conference.
• The staff liaison for the AC will be the co-sponsors’ primary liaison for the year. Staff liaisons will facilitate providing organizers access to additional staff that is knowledgeable in different areas of conference management and shall be entitled to participate in the SC meetings in a non-voting capacity.
III. Approval of Local Co-Sponsors
• Local Co-Sponsors (LCS) may be selected and approved in accordance with the principles given in the MOU (Section IV.C of the MOU).
IV. Budget and Financial Reporting
• Budgeting and financial accounting shall proceed in accordance with the principles given in the MOU (Section IX).
• The AC is responsible for the approval of the conference budget, according to the principles given in the MOU. More specifically, the AC is responsible for:
o Receiving budget, and forwarding copy to co-sponsor(s) for comment and approval
o Gathering comments on budget and working with conference leaders to clarify and resolve problems
o Submitting revised budget for approval by co-sponsors (on reasonable timeline)
o Receiving budget approval from sponsoring societies and notifying conference leadership and Chairs of SIGSOFT, TCSE, and any other sponsoring agency of the conference approval
• ACM and IEEE-CS shall maintain an archive of budget documents of previous ICSE conferences (i.e., approved budgets and final financial reports). The documents shall be maintained in the format of the agreed Conference Budget Form to provide consistency of budget information among instantiations of ICSE and for ease of reference.
ICSE Guidelines
V. Contracts
- The AC is responsible for negotiating and executing the venue contract. If the General Chair needs support from local agency, the latter needs to be approved and its operation regulated by the AC.
- The AC is responsible for issuing requests for proposals and approving all major contracts, including but not limited to venue, conference management, registration management, publisher management, website support, audio/visual management, food and beverage, and contracts. AC will review/negotiate and execute contracts with the General Chair endorsement making sure that contracts comply with AC contract guidelines.
VI. ICSE Trademarks
- ACM is responsible for guarding and defending the ICSE trademarks. IEEE agrees to cooperate with ACM in obtaining registration of the Conference Marks and to execute any documents and take any actions that may be necessary to enable ACM to secure registration of and enforce rights in the Conference Marks.
- The Service Mark, “INTERNATIONAL CONFERENCE ON SOFTWARE ENGINEERING” is the property of ACM—Registration number 1246626, Registration Date: July 26, 1983, United States Patent and Trademark Office. The Service Mark, “ICSE” is the property of ACM—Registration number 3508250, Registration date July 15, 2008, United States Patent and Trademark Office. IEEE shall have a non-exclusive, non-transferable, royalty-free license to use the ICSE Conference Marks in connection with ICSE. IEEE agrees to cooperate with ACM in obtaining registration of the ICSE Conference Marks and to execute any documents and take any actions that may be necessary to enable ACM to secure registration of and enforce rights in the ICSE Conference Marks.
- ACM and IEEE-CS agree to share the costs of establishing, guarding and defending the marks.
VII. Co-Sponsor Benefits
- ACM and IEEE provide name recognition, brand name, quality seal, industry standard
- Conference registration discounts to ACM, ACM SIGSOFT and IEEE-CS members
- Indemnity for conference organizers
- Legal liability, legal representation, and liability insurance
- Each Sponsoring Party represents and warrants that they maintain general liability insurance in an amount no less than US$1 Million to cover potential liabilities that could arise from the Sponsoring Parties participation in the Conference
- Financial liability (proportionate to the percentage of sponsorship)
- Financial risk management
VIII. Co-Sponsor Services
- Access to ACM and IEEE-CS personnel, experience and technology
- Advice on all aspects of conference organization through experienced personnel
ICSE Guidelines
- Budget development and approval support
- Liaison to steering committee
- Liaison to General Chair
- Maintenance of corporate knowledge
- Budget history
- Attendance history
- Conference space requirements history
- Hotel room requirements history
- Corporate knowledge including other conferences
- Hosting archival ICSE website (ACM)
- Corporate knowledge archiving
- Maintain legacy publications
- Publicity services
- ACM and IEEE-CS calendars
- Promotion and marketing strategies; IEEE-CS marketing team
- Production, printing, distribution of promotional materials
- Trademark/logo/web domain names enforcement
- Hosting of websites and e-mail distribution lists
- Contract services
- RFP preparation, solicitation and screening
- Venue contract negotiations including standardized agreements with preferred hotel chains
- Visit conference venue with General Chair if needed
- Relationships with venue representatives
- Monitoring venue pick up and working with venue
- Other vendor contract negotiations (e.g., registration, conference management, A/V, food and beverage)
- Issues arising regarding contracted deliverables (e.g., scope of service is not met or delivered)
- Publication services
- Author templates
- Copyright forms
- PDF Express free of charge
- Digital libraries (preparation, indexing, hosting, publicity)
- Priority indexing service
- Ownership for Intellectual Property (IP)
- IP issues (short- and long-term)
- Copyright infringement and patent dispute cases (short-term and long-term)
- Receipt and management of manuscripts
- Production and printing of products
- Financial services
- Banking services (in-house and/or outside)
- Banking MOUs with universities
- Oversee setting up clear responsibilities for authorization of payments
- Accounting services
- Invoicing
ICSE Guidelines
- Credit card processing
- Advance loans
- Collect tax information from conference organizers, and issue the necessary documents (e.g., the 1099 form in the US) as required
- Tax-exempt status and coverage
- VAT filing services
- Disbursements
- Invoicing for donations (in part)
- File music licensing forms and payments as needed
- Conference closing and account reconciliation support
- Discounted conference audit services
- Visa letters (in part)
IX. Co-Sponsor Conference Organization Resources
- ICSE Conference Organization and History is maintained at:
http://www.icse-conferences.org/
- ACM provides several resources at the page:
https://www.acm.org/special-interest-groups/volunteer-resources/conference-planning/
- IEEE provides several resources at the page:
https://www.ieee.org/conferences/organizers/organizers-new-index.html
ICSE Guidelines
ICSE Guidelines
Part C
Responsibilities of the ICSE Steering Committee (SC)
I. ICSE Steering Committee Meetings
- The ICSE Steering Committee holds face-to-face meetings twice a year - one of the meetings shall be held during the ICSE conference week and the other approximately six (6) months later (normally in colocaiton with FSE or ESEC/FSE conference). The meetings are set up and chaired by the SC chair.
- SC members should make their best effort to attend the meeting in person. Members who cannot attend will excuse themselves with the SC chair. Electronic participation is admitted when feasible – especially for SC members who must report to the committee.
- The meetings are closed and as a general rule the discussions are kept confidential. A report about the SC decisions will be made public on the ICSE conference web page at http://icse-conferences.org/
II. ICSE Practices
- The ICSE SC is responsible for establishing and evaluating practices that are binding upon the organizers of each conference for the continued technical and financial success of ICSE.
- ICSE SC can consider and decide major changes to established practices, e.g., concerning the conference tracks, the organizing committee, the paper selection process, the publishing formats, and other relevant practices. The changes can be requested by the General chair(s) or the Program chair(s) with proper advance time and must be properly motivated. Normally, major changes once approved should remain in place for at least three years, and performance data should be collected for evaluation.
- The ICSE SC utilizes two structural mechanisms to improve its efficiency, namely:
A. Two Standing Committees, composed of subsets of the SC, that provide guidance and support for general conference organization and for the conference’s research track. They operate semi-independently of the SC, bringing items for discussion and recommendations to the whole SC as required. Precisely:
o The Conference Operations Committee is charged with assisting General Chairs (GC) by establishing a consistent operational framework and providing oversight and organizational memory. The committee maintains a body of guidelines and templates to retain organizational memory. This committee is composed of all past, current and future GCs, and one of the IEEE TCSE and one of the ACM SIGSOFT representatives from the SC.
o The Technical Research Review Committee is charged with establishing and maintaining guidelines for supporting PC Chairs in setting schedules, making changes, and forming their teams, while remaining cognizant of ICSE being the premier software engineering conference. This committee includes one PC Chair from each ICSE from the current SC.
B. The Task Forces are established by the SC to deal with specific emerging challenges and opportunities that are out of the scope of the two Standing Committees. The Task Forces each have a specific objective and timeframe. They
ICSE Guidelines
include SC and may include non-SC members, operate semi-independently, and bring updates and recommendations to the SC.
III. Constituting an ICSE Conference
The ICSE SC is responsible for:
• Constituting each edition of the ICSE conference. The specifics of an edition structure and contents will be decided by the conference leaders in agreement with the SC.
• Approving conference locations. As stated in MOU Section VI, the conference location normally rotates between North America, Europe, and rest of the world.
• Approving the conference leaders, the city and potential venue for the future ICSE conference, normally at least four years in advance.
• Within the established rotation scheme, the SC will launch in due time open invitations to submit letters of interest to host a future ICSE, and will evaluate thoroughly the proposed teams and locations.
• Proposing any change in the AC rotation. The SC can propose changes in the conference location rotation under exceptional circumstances.
• Ratifying a Local Co-Sponsor (LCS) for an ICSE conference in accordance with the principles given in the MOU Section IV.
• Approving the following conference leaders:
o General Chair or General Co-Chairs
o Program Co-Chairs
o Software Engineering in Practice Co-Chairs
IV. Oversight of an ICSE Conference
• The ICSE SC is responsible for overseeing and guiding the scope, scientific success, financial success, and operational success of an ICSE conference.
• The ICSE SC is responsible for ensuring that the selected ICSE conference chairs receive a copy of the ICSE Memorandum of Understanding (MOU) and Guidelines and that they agree explicitly to act in accordance with the terms in those documents.
V. ICSE Steering Committee Budget
• The ICSE SC is responsible for its own budget.
• The ICSE SC budget is used to pay for the committee’s expenses, including any contracted services to support conference continuity and success.
• Funding for the ICSE SC budget shall be obtained via an expense line item in each ICSE’s Conference Budget Form.
• The annual expense line item amount shall be justified by a statement of proposed expenses and is subject to approval by ACM and IEEE-CS.
ICSE Guidelines
ICSE Guidelines
Part D
Responsibilities of ICSE Conference General Chair
I. Accountability and Reporting
- The General Chair of an ICSE reports to the ICSE Steering Committee Chair and to the Administrative Co-sponsor (AC).
- Upon request by the IEEE CS or ACM or ACM SIGSOFT or IEEE-CS TCSE, and at reasonable intervals, the General Chair is to provide a detailed update on current conference activity, including, but not limited, to current financial and registration activity.
II. Duration of Appointment
- The term of appointment for an ICSE General Chair is 48 months (3 years before an ICSE conference and one year after an ICSE conference).
III. Responsibilities and Obligations
- To plan and execute an ICSE conference so that it is a scientific and financial success.
- To oversee the activities of all conference sub-committee chairs and co-chairs.
- To ensure that the conference objectives as established by the ICSE Steering Committee (SC) are met.
- To ensure that the conference objectives of the societies and co-sponsors are met.
- To serve as a focal point for communications between the conference organization committee and the staff of the AC.
IV. Selection Criteria for General Chairs
- Must be a member of ACM or ACM SIGSOFT or (IEEE or IEEE-CS)+TCSE
- Must be of sufficient stature within the ICSE software engineering community.
- Must be a competent manager, preferably with significant management and budgeting experience.
- Must have outstanding communications skills.
- Must have support from employer since chairing an ICSE conference is a major commitment requiring significant time and energy over a four-year period.
- Is advised against committing to other major volunteer activities since the success of the conference depends on the ongoing and regular management of the conference committee.
V. Conference Organization Resources
The General Chair must be familiar with the ICSE MOU, the Conference Operations Committee, and the conference organization resources collected at:
http://www.icse-conferences.org/
VI. Major Responsibilities
A. **Conference Venue:** In consultation with ACM and IEEE-CS staff, identify conference city and venue. Seek approval of conference site from ICSE SC. Let ACM and IEEE-CS staff negotiate venue contract (it is recommended that the General Chair does not negotiate on their own).
B. **Progress Reports:** For the entire duration of the appointment, present semi-annual progress reports in person to the ICSE SC.
C. **Master Plan and Risk Analysis:** Develop a master plan and perform risk analysis for the entire conference, including financial and technical risks, responsibilities, timelines, milestones, deadlines, and check lists for the entire conference for all sub-committee chairs and co-chairs.
D. **Preliminary Approval Form (PAF):** This form allows conference organizers to secure dates on the ACM and IEEE-CS conference calendars and obtain agreement in principle from all sponsors (ACM, IEEE-CS and other co-sponsors) that the conference will occur. Note that this form does not grant rights to conference organizers to enter into contracts, to incur expenses, to advertise conference registration rates, to open a bank account, or to collect funds for the conference.
E. **Learning Opportunities:**
- It is highly recommended that General Chairs of a future ICSE attend every postmortem session of prior ICSE conferences to gain experience with ICSE conference organization.
- The ICSE SC—with its many past General Chairs and Program Co-Chairs—is a rich source of information for how to organize and execute an ICSE conference. General Chairs are strongly encouraged to solicit feedback from SC Chair and selected SC members on all aspects of ICSE conference organization and execution.
- It is also suggested to take advantage of other learning opportunities be provided, such as “shadowing” another General Chair or being involved or at least being copied in important conference organization discussions.
F. **Conference Budget Form (CBF):**
- Work with Finance Chair to prepare the ICSE budget using the IEEE-CS Conference Budget Form. Review and approve all items that exceed approved budgeted expenses. The General Chair is ultimately responsible for the revenue and expenses of the conference. It is important to review and understand the requirements of the Administrative Co-sponsor (AC) (e.g., administrative fees).
- The overall purpose of the CBF is to collect the information that is necessary to evaluate the proposed conference for approval. The CBF is an important planning document to help plan the finances of the conference and identify decisions that must be made in the planning process. Consistently using the IEEE-CS CBF will provide readily comparable information for future conference leaders.
G. **Financial Management:**
ICSE Guidelines
- Each ICSE conference is expected to generate a surplus.
- In consultation with Treasurer and AC, decide on financial management for the conference
- Central versus distributed banking and accounting (e.g., central account at AC in USD as well as local university in local currency)
- Invoicing of donations (e.g., by AC in USD or local university in local currency)
- Contracts (e.g., paid by AC in USD or local university in local currency)
- For conferences outside US/North America:
- Working with AC to identify potential local co-sponsoring organizations.
- If a local co-sponsor is added, ensure that a Joint Sponsorship Agreement or Memorandum of Understanding is developed and signed that covers percentages of conference sponsorship and other financial, legal, and copyright issues.
H. Organization Committee
Recruit and appoint the ICSE organization committee that is formed by all (co-)chairs for the technical and administrative positions of the conference: Some examples are outlined below and other leadership positions can be appointed at the discretion of the General Chair. Inform and oversee all these subcommittee chairs of their duties and responsibilities. Be sure that each chair understands budgetary allocations, task deadlines, and the ICSE conference policies of the SC and the AC.
- Identify and recruit chairs for several conference sub-committees dealing with different aspects of the technical success of an ICSE program, such as (example list):
- Program Co-Chairs (must be approved by ICSE SC)
- Workshop Co-Chairs
- Co-located Events
- Software Engineering in Practice Track (must be approved by ICSE SC)
- Software Engineering Education and Training Track
- Research Demo Track
- New Faculty Symposium
- New Ideas and Emerging Results Track
- Doctoral Symposium
- Identify and recruit chairs for several conference sub-committees dealing with different aspects of the financial and organizational success of an ICSE conference, such as (example list):
- Web Master
- Publications Chair(s)
- Treasurer or Finance Chair(s)
- Fund-raising and Sponsorship Chair(s)
- Promotions and Publicity Chair(s)
- Registration Chair(s)
- Local Arrangements Chair(s)
- Data Chair(s)
- Student Volunteers Chair(s)
ICSE Guidelines
- Student Contests and Mentoring Chair(s)
- Establish discretionary policies (i.e., policies not outlined by AC) governing conference activities working with treasurer (e.g., expense reimbursement guidelines and payment approval guidelines), web master (e.g., major and minor updates and schedule), registration chairs (e.g., complementary registration for keynotes and program co-chairs).
- As sponsoring organizations, ACM or IEEE retain publication rights. During the preliminary preparation for each instance of the conference, the General Chair must ensure the necessary forms required by either the IEEE or ACM policies are completed to insure the subsequent timely posting of the publications materials into the digital libraries as quickly as possible after the conference.
- In consultation with program co-chairs, invite keynote speakers
I. Communication Channels:
- Establish effective communication with the AC.
- Establish effective communication channels with key conference committee members through website, mailing lists, regular conference calls, progress reporting and tracking.
- Schedule program and conference committee meetings.
- Define publicity strategy, timeline, and milestones, including website, calendars, calls, ads, registration, mailings, poster, postcard, advance programs, and logistics.
- Prepare progress reports and agendas for conference committee meetings and distribute minutes of meetings to members of the Conference Committee, SC Chair, and the AC.
J. Execution of ICSE Conference Contracts:
Work with the AC on issuing RFPs to conference vendors and evaluating proposals. All major contracts must be endorsed by General Chair and approved by the AC, including venue, conference management, registration management, publisher or publications management, audio/visual management, food and beverage. The AC will review/negotiate and execute contracts making sure that contracts comply with contract guidelines. Consult extensively with the AC on all contracts.
K. Conference Management
- Logistical management
- Conference week schedule
- Room assignments including ancillary meetings, including ACM SIGSOFT, IEEE-CS TCSE town hall meetings, ICSE+1/2 Conference Committee, ICSE+1 Program Committee, IEEE TSE board, ACM TOSEM board, FSE PC, ...
- Display of sponsor logos
- Signage
- Wireless Internet access
- Conference and sponsors banners
- Conference bags
- AV schedule
- Catering schedule
- Exhibits schedule (if any)
- Final program
ICSE Guidelines
- Hotel room block management
- Free hotel rooms for VIPs management
L. Conference Week
- Establish an evaluation mechanism for all aspects of the conference.
- Chair opening and closing sessions of the conference.
- Chair awards session (or appoint delegate Award Chair).
- Chair victory dinner.
- Conduct a postmortem session at the end of the conference for future conference organizers.
- Ensure that the appropriate thank-you notes are sent to all conference and program committee members, and to organizations that have made financial contributions to the conference.
- ACM SIGSOFT and IEEE-CS TCSE will present to the General Chair and the Program Co-Chairs a Certificate of Recognition.
- Endorse all catering changes.
M. Final Reports:
- Together with the AC and conference leaders, prepare a final financial report on the conference no later than six (6) months after an ICSE conference. The co-sponsors will receive their share of the surplus funds or will cover their share of a loss not later than thirty (30) days after AC validation of the final financial report.
- Prepare a final report for the conference and submit it to SC Chair and the AC no later than six (6) months following the conference. The final report should include:
- A copy of the Conference Budget Form with actuals provided in the designated columns.
- All registration details (i.e., fees and number of attendees for each category), which will help organizers of future conference.
- List of conference participants
- Fund-raising strategy and report
- Publicity strategy and report
- Conference management strategy
- Lessons learned and a critique of problem areas and list of things you would have done differently. This will greatly enhance the planning efforts of future conference organizers.
- Note that this information will be posted on the ICSE conferences archival website as a reference for future conference leaders.
N. Chain of Accountability:
- The General Chair is responsible for overseeing the technical, financial, administrative and logistical management of all activities related to the conference and for upholding all policies and procedures of the AC.
- The General Chair is responsible for ensuring that no major expenses are incurred until the Conference Budget Form is approved by the AC.
- The General Chair is responsible for ensuring that ACM, IEEE-CS, ACM SIGSOFT, IEEE-CS TCSE, and potentially other co-sponsors are featured—equally—on all conference and particularly publicity materials (e.g., wherever ICSE is mentioned) including conference calendars at the societies, conference web
ICSE Guidelines
site, letter head, printed materials, call for papers, call for participation, registration forms, fliers, proceedings, CDs, conference bags, signage).
• The General Chair is ultimately responsible for the revenue and expenses of the conference and, thus, responsible for delivering on administrative fees as well as contingency and profit margins as required by the co-sponsors. Note that the Conference Budget Form is a living document that must be kept up-to-date throughout the conference planning to stay on top of the budget.
• The General Chair is responsible for keeping the conference planning on schedule.
• The General Chair is responsible for periodically reviewing the activities of the conference sub-committee co-chairs and members. If need be, the General Chair has to replace conference sub-committee chairs or add an additional co-chair.
• The General Chair, together with the AC is responsible for delivering the final financial report on the conference no later than six (6) months after an ICSE conference.
ICSE Guidelines
ICSE Guidelines
Part E
Responsibilities of ICSE Conference Program Co-Chairs
I. Accountability and Reporting
- The Program Co-Chairs (PCs) of an ICSE report to the ICSE General Chair.
II. Duration of Appointment
- The term of appointment for an ICSE Program Co-Chair is 18-24 months.
III. PCs Responsibilities and Obligations
The ultimate responsibility of PCs is to guarantee a high-quality, up-to-date and attractive scientific program that supports ICSE objectives, and, together with the General Chair, to serve as the editors of the ICSE conference proceedings (but not of the Companion volumes). They collect a team of world leading software engineering scientists, who can be organized into a one-tier (e.g., the Program Committee) or multi-tier (e.g., the Program Board and the Program Committee) structure, which help in the selection of technical papers. For the purpose of these guidelines we will call it the Scientific Team (ST). They organize the ST and the reviewing process according to the most adequate model that normally will be in continuity from previous ICSE editions. Major changes from previous year reviewing model must be approved by the SC.
The PCs serve as the point of communication between the General Chair and the ST.
For more details about PCs tasks, ICSE SC maintains a set of guidelines for the Program Co-Chairs in the document "ICSE Program Co-Chairs Guiding Document" that can be found on line in the page: http://icse-conferences.org/reports.html. The same page provides several PCs reports.
IV. Selection Criteria for Program Co-Chairs
- Must be a member of ACM or ACM SIGSOFT or (IEEE or IEEE-CS) + TCSE
- Must be of sufficient stature within the ICSE software engineering community.
- Must be able to organize and oversee the paper selection process.
V. Major Tasks
A. Appoint the Scientific Team:
- Recruit and appoint ST members at least one year in advance of the conference. The structure of the ST is to be approved by SC. In principle a reviewing model should stay in place for 3 years so that data could be collected. At any rate, major changes from the established model (for example, Program Board + Program Committee) and review process must be well motivated and analyzed by the Program Chairs.
- With assistance from the General Chair and ICSE SC, develop a list of potential ST members.
For a balanced ST membership, consider the topics covered, expertise, seniority, university/industry affiliations, geography, and gender.
When recruiting ST members, be clear that abiding by the established reviewing schedule and ensuring high-quality reviews as well as attending face-to-face or virtual established meetings for paper selection is mandatory—a member is dropped off the team if the member fails to comply.
It is recommended that a clear and detailed letter be sent, possibly re-using a standard template (e.g., one developed by previous PCs) when inviting team members.
B. ST Meetings:
- Set up a first ST (including PB and/or PC members, depending on ST structure) meeting at ICSE-1 (previous year ICSE).
- Select a date and (physical or virtual) venue for the ST meeting approximately six months before the conference.
C. Paper Submission Procedure:
- In consultation with General Chair and ICSE SC, establish a specific and documented process for paper submission and review with appropriate infrastructure and documentation.
- Select and contract for a web-based submissions system to handle all ICSE submissions (i.e., workshop proposals, tutorial proposals, special track papers and workshop papers); work with the manager of the web-based submissions system to set up the details of the system for ICSE.
- Study and test the web-based submissions system before operation—for submission, review, and ST meeting operations.
D. Timeline, Policies and Practices:
- In consultation with General Chair and publisher, prepare a timeline, deadlines, and a budget for all program related activities including submission, review, acceptance and final paper due dates. Work with publisher on final paper submissions date and then work backwards to determine the appropriate timeline.
- Contact the previous ICSE Program Co-Chairs and verify general policies of acceptance and page limits. Consult with the General Chair to ensure there is general agreement on these practices.
- Assign responsibilities (e.g., “distinguished paper” awards) to ST members and review timelines and budgets for these activities.
E. Call for Papers:
- Develop the list of topics and the Call for Papers (CFP).
- Coordinate with General Chair and Publicity Co-Chairs on the CFP.
- Solicit papers.
- Publish the CFP using web sites, mailing lists, and ads, within budget constraints.
F. Paper Reviewing Process:
- Receive papers.
- Reviewer preferences, conflicts, bidding.
- Solicit appointed members of the scientific team.
- Orchestrate the reviewing process.
- Prepare extensively for the ST selection discussion and meeting.
ICSE Guidelines
- Plan for the ST meeting including logistics
G. ST Meeting:
- Conduct and direct the (face-to-face or virtual) ST meeting.
- Manage conflicts effectively.
- Inform authors of accepted and rejected papers in a timely manner.
H. Program Development:
- In conjunction with other track chairs, such as the SEIP and journal-first tracks, develop the structure of the final technical program within the framework of the entire conference as outlined by the General Chair and previous conferences.
- Get the program on-line as quickly as possible after the selection process is complete.
- Provide materials on program content to the promotions chair in a timely manner.
- Develop the program carefully to minimize “overlaps”.
- Recruit session chairs. Manage the arrangements for session chairs and provide them with the information they require, such as speaker names and telephone numbers, introductory information concerning speakers, session times and locations.
- Manage all speaker communication (e.g., letters of invitations to speakers, promotional information, biographical information, session times and locations)
- Track author registration in collaboration with Proceedings chairs.
I. Best Paper Awards:
- Manage several “best paper” awards, including:
- ICSE Most Influential Paper Award (ICSE N-10)
- Process. There is not a standard process; most recent PCs have delegated the process to a respected member of the community.
- Plaque. The program co-chairs are responsible for preparing the plaque and producing one for each author.
- Program. No single, standard approach has been adopted both in terms of the actual presentation of the award and also in terms of any presentation one or more of the authors may be asked to give at ICSE.
- SIGSOFT Distinguished Paper Awards
J. ICSE Proceedings:
- Oversee the production of the ICSE proceedings and other technical by-products including collection of copyright and permission forms as appropriate and work with proceedings chair to insure the quality of the final publication.
K. ICSE Conference:
- Oversee the execution of the program.
L. ICSE Postmortem:
- Attend the ICSE postmortem session.
- Write a report with suggestions and lessons learned for future ICSE PC Co-Chairs and a non-confidential report for the ICSE archival website.
ICSE Guidelines
Appendix: IEEE-TCSE and ACM-SIGSOFT Models for Surplus and Deficit Distribution
ACM: See https://www.sigsoft.org/policies/surplus.html
|
{"Source-Url": "http://www.icse-conferences.org/ICSE-Operating-Rules-and-Guidelines-2019.pdf", "len_cl100k_base": 9946, "olmocr-version": "0.1.48", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 26312, "total-output-tokens": 11141, "length": "2e13", "weborganizer": {"__label__adult": 0.0006046295166015625, "__label__art_design": 0.001636505126953125, "__label__crime_law": 0.001007080078125, "__label__education_jobs": 0.09637451171875, "__label__entertainment": 0.0002853870391845703, "__label__fashion_beauty": 0.0005154609680175781, "__label__finance_business": 0.0115814208984375, "__label__food_dining": 0.0006837844848632812, "__label__games": 0.0030612945556640625, "__label__hardware": 0.0021114349365234375, "__label__health": 0.0012340545654296875, "__label__history": 0.0010843276977539062, "__label__home_hobbies": 0.0004887580871582031, "__label__industrial": 0.0010557174682617188, "__label__literature": 0.0007920265197753906, "__label__politics": 0.0009946823120117188, "__label__religion": 0.0010061264038085938, "__label__science_tech": 0.07818603515625, "__label__social_life": 0.00039267539978027344, "__label__software": 0.0308685302734375, "__label__software_dev": 0.7626953125, "__label__sports_fitness": 0.0008940696716308594, "__label__transportation": 0.0010242462158203125, "__label__travel": 0.0015411376953125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49529, 0.00175]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49529, 0.05245]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49529, 0.92346]], "google_gemma-3-12b-it_contains_pii": [[0, 2331, false], [2331, 5668, null], [5668, 8237, null], [8237, 11504, null], [11504, 12622, null], [12622, 14999, null], [14999, 15819, null], [15819, 17774, null], [17774, 20391, null], [20391, 22285, null], [22285, 23153, null], [23153, 26151, null], [26151, 28371, null], [28371, 30488, null], [30488, 33300, null], [33300, 35600, null], [35600, 38142, null], [38142, 40782, null], [40782, 41831, null], [41831, 44238, null], [44238, 46863, null], [46863, 49203, null], [49203, 49529, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2331, true], [2331, 5668, null], [5668, 8237, null], [8237, 11504, null], [11504, 12622, null], [12622, 14999, null], [14999, 15819, null], [15819, 17774, null], [17774, 20391, null], [20391, 22285, null], [22285, 23153, null], [23153, 26151, null], [26151, 28371, null], [28371, 30488, null], [30488, 33300, null], [33300, 35600, null], [35600, 38142, null], [38142, 40782, null], [40782, 41831, null], [41831, 44238, null], [44238, 46863, null], [46863, 49203, null], [49203, 49529, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49529, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49529, null]], "pdf_page_numbers": [[0, 2331, 1], [2331, 5668, 2], [5668, 8237, 3], [8237, 11504, 4], [11504, 12622, 5], [12622, 14999, 6], [14999, 15819, 7], [15819, 17774, 8], [17774, 20391, 9], [20391, 22285, 10], [22285, 23153, 11], [23153, 26151, 12], [26151, 28371, 13], [28371, 30488, 14], [30488, 33300, 15], [33300, 35600, 16], [35600, 38142, 17], [38142, 40782, 18], [40782, 41831, 19], [41831, 44238, 20], [44238, 46863, 21], [46863, 49203, 22], [49203, 49529, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49529, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
b091768a61495c7ff6597e0d3e53c199af6620ff
|
EDITORIAL PREFACE
iv Manuel Mora, Autonomous University of Aguascalientes (UAA), Aguascalientes, Mexico
RESEARCH ARTICLES
1 An Innovative Approach to the Development of an International Software Process Lifecycle Standard for Very Small Entities
Rory V. O’Connor, Lero - The Irish Software Engineering Research Centre, Dublin City University, Dublin, Ireland
Claude Y. Laporte, École de Technologie Supérieure, Montréal, Canada
23 Implications of Pressure for Shortening the Time to Market (TTM) in Defense Projects
Moti Frank, HIT-Holon Institute of Technology, Holon, Israel
Boaz Carmi, IMI-Israel Military Industries, Ramat Hasharon, Israel
41 Towards a Conceptual Framework for Open Systems Developments
James A. Cowling, School of Systems and Enterprises, Stevens Institute of Technology, Hoboken, NJ, USA
Christopher V. Morgan, PA Consulting Group, London, UK
Robert Cloutier, School of Systems and Enterprises, Stevens Institute of Technology, Hoboken, NJ, USA
55 An Agile Project System Dynamics Simulation Model
A. S. White, School of Science and Technology, Middlesex University, London, UK
Copyright
The International Journal of Information Technologies and Systems Approach (IJITSA) (ISSN 1935-570X; eISSN 1935-5718), Copyright © 2014 IGI Global. All rights, including translation into other languages reserved by the publisher. No part of this journal may be reproduced or used in any form or by any means without written permission from the publisher, except for noncommercial, educational use including classroom teaching purposes. Product or company names used in this journal are for identification purposes only. Inclusion of the names of the products or companies does not indicate a claim of ownership by IGI Global of the trademark or registered trademark. The views expressed in this journal are those of the authors but not necessarily of IGI Global.
Rory V. O’Connor, Lero - The Irish Software Engineering Research Centre, Dublin City University, Dublin, Ireland
Claude Y. Laporte, École de Technologie Supérieure, Montréal, Canada
ABSTRACT
For very small software development companies, the quality of their software products is a key to competitive advantage. However, the usage of Software Engineering standards is extremely low amongst such very small software companies. A primary reason cited by many such companies for this lack of quality standards adoption is the perception that they have been developed for large multi-national software companies and not with small and very small organizations in mind and are therefore not suitable for their specific needs. This paper describes an innovative systematic approach to the development of the software process lifecycle standard for very small entities ISO/IEC 29110, following the Rogers model of the Innovation-Development process. The ISO/IEC 29110 standard is unique amongst software and systems engineering standards, in that the working group mandated to develop a new standard approached industry to conduct a needs assessment and gather actual requirements for a new standard as part of the standards development process. This paper presents a unique insight from the perspective of some of the standards authors on the development of the ISO/IEC 29110 standard, including the rationale behind its development and the innovative design of implementation guides to assist very small companies in adopting the standards, as well outlining a pilot project scheme for usage in early trials of this standard.
Keywords: ISO/IEC 29110, Software Engineering, Software Process, Standards, Very Small Entities
1. INTRODUCTION
For many small and very small software companies, implementing controls and structures to properly manage their software development activity is a major challenge. Administering software development in this way is usually achieved through the introduction of a software process. All software companies are not the same and vary according to factors including size, market sector, time in business, management style, product range and geographical location.
DOI: 10.4018/ijitsa.2014010101
For example, a software company operating in India may have a completely different set of operational problems when compared to a software company in Canada, Mexico or Ireland. Even within a single geographical area such as Ireland, the range of operational issues faced by a small local Irish-owned firm can be radically different to those affecting a multinational subsidiary. The fact that all companies are not the same raises important questions for those who develop software process and process improvement models. To be widely adopted by the software industry, any process or process improvement model should be capable of handling the differences in the operational contexts of the companies making up that industry. But process improvement models, though highly publicized and marketed, are far from being extensively deployed and their influence in the software industry therefore remains more at a theoretical than practical level (Coleman & O’Connor, 2008a).
In a time when software quality is a key to competitive advantage, the use of ISO/IEC systems and software engineering standards remains limited to a few of the most popular ones. Research shows that small and very small companies can find it difficult to relate ISO/IEC standards to their business needs and to justify the application of the standards to their business practices (Laporte et al., 2008; O’Connor & Coleman, 2009). Most of these companies don’t have the expertise or can’t afford the resources - in number of employees, cost, and time - or see a net benefit in establishing software life-cycle processes. There is sometimes a disconnect between the short-term vision of the company, looking at what will keep it in business for another six months or so, and the long-term or mid-term benefits of gradually improving the ways the company can manage its software development and maintenance. A primary reason cited by many small software companies for this lack of adoption of software engineering standards, is the perception that they have been developed for large software companies and not with the small organization in mind (Coleman & O’Connor 2008b). To date the industrial reality is that Very Small Entities (VSEs) have limited ways to be recognized, by large organizations, as enterprises that produce quality software systems within budget and calendar in their domain and may therefore be cut off from some economic activities.
Accordingly there is a need to help such organizations understand and use the concepts, processes and practices proposed in the ISO/IEC JTC1/SC7’s international software engineering standards. The recently published ISO/IEC 29110 standard “Lifecycle profiles for Very Small Entities” (ISO, 2011a) is aimed at addressing the issues identified above and addresses the specific needs of VSEs.
The purpose of this paper is to chart the design and development of this new ISO/IEC standard by harnessing the expressive power of the 6-stage model of the innovation-development process model, developed by Rogers (2003). In addition it presents a unique insight from the perspective of two of the standards authors, as well as the initial results of some early pilot trials of ISO/IEC 29110.
The structure of this paper is as follows: Section 2 introduces background concepts and definitions such as the concept of Very Small Entities, Standards and their usage in small companies. Section 3 provides a high level summary of the approach used in this paper and a detailed description of the application of this approach and its outcomes. Section 4 will discuss the impact of this work, its limitations and planned future work.
2. BACKGROUND CONTEXT
2.1. Very Small Entities
The definition of “Small” and “Very Small” Entities is challengingly ambiguous, as there is no commonly accepted definition of the terms. For example, the participants of the 1995 Capability Maturity Model (CMM) tailoring workshop (Ginsberg & Quinn, 1995) could not even agree on what “small” really meant. Subsequently in 1998 SEPG conference panel
on the CMM and small projects (Hadden, 1998), small was defined as “3-4 months in duration with 5 or fewer staff”. Johnson and Brodman (1998) define a small organization as “fewer than 50 software developers and a small project as fewer than 20 software developers”. Another definition for VSE introduced by Laporte et al. (2006a) as “any IT services, organizations and projects with between 1 and 25 employees”.
To take a legalistic perspective the European Commission (2005) defines three levels of Small to Medium-sized Enterprise (SME) as being: Small to medium - “employ fewer than 250 persons and which have an annual turnover not exceeding 50 million Euro, and/or an annual balance sheet total not exceeding 43 million Euro”; Small - “which employ fewer than 50 persons, and whose annual turnover or annual balance sheet total does not exceed 10 million Euro” and Micro - “which employ fewer than 10 persons and whose annual turnover and/or annual balance sheet total does not exceed EUR 2 million”.
To better understand the dichotomy between the definitions above it is necessary to examine the size of software companies operating in the market today. According to the Organization for Economic Co-operation and Development (OECD) SME and Entrepreneurship Outlook report (2005), “SMEs constitute the dominant form of business organization in all countries world-wide, accounting for over 95% and up to 99% of the business population depending on country”. In Europe, for instance, 85% of the Information Technology (IT) sector’s companies have 1 to 10 employees. In the context of indigenous Irish software firms 1.9% (10 companies), out of a total of 630 employed more than 100 people whilst 61% of the total employed 10 or fewer, with the average size of indigenous Irish software firms being about 16 employees (Coleman & O’Connor, 2008a). In Canada, the Montreal area was surveyed. It was found that 78% of software development enterprises have less than 25 employees and 50% have fewer than 10 employees (Laporte et al., 2006b). In Brazil, small IT companies (companies with less than 50 employees) represent about 70% of the total number of companies (Anacleto et al., 2004).
Therefore based on the above discussions and the debate within the ISO community, for the purposes of this paper we are adopting the definition for VSE introduced in Laporte et al. (2006b) as “any enterprise, organization, department and project having up to 25 people”.
Furthermore, this is the definition agreed to by the various national representatives of the working group 24 of ISO/IEC JTC1 SC7.
The unique characteristics of small enterprises as well as the uniqueness of their needs make their style of business different (Mtigwe, 2005). Some of the unique differences between small and large enterprises behavior are given in Table 1. Software VSEs are subject to a number of distinctive and intrinsic characteristics that make them different from their larger counterparts, therefore affecting the content, the nature
<table>
<thead>
<tr>
<th>Characteristic</th>
<th>Small Enterprise</th>
<th>Large Enterprise</th>
</tr>
</thead>
<tbody>
<tr>
<td>Planning orientation</td>
<td>Unstructured/operational</td>
<td>Structured/strategic</td>
</tr>
<tr>
<td>Flexibility</td>
<td>High</td>
<td>Structured/strategic</td>
</tr>
<tr>
<td>Risk orientation</td>
<td>High</td>
<td>Medium</td>
</tr>
<tr>
<td>Managerial process</td>
<td>Informal</td>
<td>Low</td>
</tr>
<tr>
<td>Learning and knowledge absorption capacity</td>
<td>Limited</td>
<td>High</td>
</tr>
<tr>
<td>Impact of negative market effects</td>
<td>More profound</td>
<td>More manageable</td>
</tr>
<tr>
<td>Competitive advantage</td>
<td>Human capital centered</td>
<td>Organizational capital centered</td>
</tr>
</tbody>
</table>
Table 1. Characteristic differences between small and large enterprises (from Mtigwe, 2005)
and the extent of the activities. We partition our discussion of VSE characteristics below based on four main categories: financial constraints, typical customer profile, the focus of internal business processes and the constraints on learning and growth (Basri & O’Connor, 2011). VSEs are economically vulnerable as they are driven by cash flow and depend on project profits, so they need to perform the projects within budget. They tend to have low budgets which have many impacts, such as: Lack of funds to perform corrective post delivery maintenance; Few resources allocated for training; Little or no budget to perform quality assurance activities; No budget for software reuse processes; Low budget to identify, plan and mitigate risks; and Limited budget to perform Process Improvement and/or obtain a certification/assessment of their processes.
Typically the VSEs product has a single customer at a time, where the customer is in charge of the management of the system; the software integration, installation and operation. It is not a current practice for the customer to define quantitative quality requirements and for customer satisfaction to depend on the fulfillment of specific requirements that may change during the project. A close relationship between all involved project members including the customer shows that software development in small and very small companies is strongly human oriented and communication between them is important. For example, in contrast to small companies, very small companies often do not have regularly formal project meetings (O’Connor et al., 2010).
The internal business process of VSEs is usually focused on developing custom software systems, where the software product is elaborated progressively and incrementally, and typically software projects are independent of one another. Usually most management processes (such as human resource and infrastructure management) are performed through informal mechanisms, with the majority of communication, decision making and problem resolution being performed face to face.
The learning and growth characteristics of VSE are characterized by a lack of knowledge (or acceptance) of software process assessment and improvement and a lack of human resources to engage in standardization.
2.2. Standards: Benefits and Drawbacks
There are multiple approaches to organizing the software development process and multiple factors influencing the software development process (Clarke & O’Connor, 2012), which should be harmonized with software development setting (Jeners et al., 2013). Quality orientated process approaches and standards are maturing and gaining acceptance in many organizations. Standards emphasize communication and shared understanding more than anything. Examples are: any documentation is consistent and what is needed to meet the needs of the organization; all users understand the same meaning of words used - if one person says, ‘Testing is completed ‘all affected bodies understand what those words mean. This kind of understanding is not only important in a global development environment; even a small group working in the same office might have difficulties in communication and understanding of issues shared by all. Standards can help in these and other areas to make the business more profitable because less time is spent on non-productive work.
There are many potential benefits of using standards. From a VSE perspective, the benefits that certification can provide include: increased competitiveness, greater customer confidence and satisfaction, greater software product quality, increased sponsorship for process improvement, decreased development risk, facilitation of marketing and higher potential to export. While good internal software management might help meet the first five claims; the last two can only be the benefits of using widely recognized standards.
Although commercial Software Process Improvement (SPI) models (such as Capability
Maturity Model Integration for Development, CMMI-DEV) (SEI, 2010) have been highly publicized and marketed, they are not being widely adopted and their influence in the software industry therefore remains more at a theoretical than practical level (Coleman & O’Connor, 2006; O’Connor & Coleman, 2009). In the case of CMMI®, evidence for this lack of adoption can be seen by examining the SEI (Software Engineering Institute) CMMI data for the three-year period March 2008 to March 2011 (CMMI, 2011), which shows that worldwide during that period less than 3,500 individual appraisals were reported, which includes many divisions of the same company. It is clear that this represents a very small proportion of the world’s software companies and company in-house developers. In addition, there is evidence that the majority of small and very small software organizations are not adopting standards such as CMMI. For example, an Australian study (Staples et al., 2007) found that small organizations considered that adopting CMMI “would be infeasible”.
Further investigation of the SEI CMMI appraisal data reveals that in the case of Ireland – a country whose indigenous software industry is primarily made of small to medium sized organizations (SME) - fewer than 10 CMMI appraisals were conducted during the ten-year period 2001 - 2011, from a population of more than 900 software companies. Therefore it is also clear that the Irish software industry is largely ignoring the most highly publicized SPI models. In the case of CMMI (and its predecessor Software CMM), Staples and Niazi (2006) discovered, after systematically reviewing 600 papers, that there has been little published evidence about those organizations who have decided not to adopt CMMI.
Though it is not new to claim that SPI has an associated cost, many companies are deterred from investigating SPI models because of a perceived cost. Managers’ perceptions are that SPI means increased documentation and bureaucracy (O’Connor et al., 2010). Such a perception is widespread and is seen as a ‘feature’ of standards such as CMMI. Whether or not this is true is a debatable point. The fact that managers associate CMMI with increased overhead means that most small companies do not see the model as being a viable solution or even worthy of investigation.
There is evidence (Laporte et al., 2008; Coleman & O’Connor 2008a; O’Connor & Coleman, 2009) that the majority of small and very small software organizations are not adopting existing standards / proven best practice models because they perceive the standards as being developed by large organizations and orientated towards large organizations, thus provoking the debate in terms of number of employees, size does actually matter. Studies have shown that small firms’ negative perceptions of process model standards are primarily driven by negative views of cost, documentation and bureaucracy. In addition, it has been reported that SMEs find it difficult to relate standards to their business needs and to justify the application of the international standards in their operations. Most SMEs cannot afford the resources for, or see a net benefit in, establishing software processes as defined by current standards (e.g. ISO/IEC 12207) and maturity models (e.g. CMMI for Development).
2.3. VSE and Standards Usage
In a time when software quality is a key to competitive advantage, the use of ISO/IEC systems and software engineering standards by VSEs remains limited to a few of the most popular ones, such as ISO 9001. Research shows that VSEs can find it difficult to relate ISO/IEC standards to their business needs and to justify the application of the standards to their business practices. Most of these VSEs can’t afford the resources - in number of employees, expertise, cost, and time - or see a net benefit in establishing software life-cycle processes. There is sometimes a disconnect between the short-term vision of the organization, looking at what will keep it in business for another six months or so, and the long-term benefits of gradually improving the ways the company
can manage its software development and maintenance. A primary reason cited by many small software organizations for this lack of adoption of such ISO standards, is the perception that they have been developed by and for large multi-national software companies and not with the small organization in mind (Ahern et al., 2004). Subsequently, VSEs have no or very limited ways to be recognized as enterprises that produce quality software systems in their domain and may therefore be cut off from some economic activities.
Small software organizations, in the first instance, focus mostly on survival. This, in part, explains the success of agile methodologies whose ‘light’, non-bureaucratic techniques support companies in survival mode attempting to establish good, fundamental software development practices. Though CMMI is firmly anchored in the belief that better processes means better products, many small Irish software product companies are merely concerned about getting a product released to the market as quickly as possible. Development models, such as those within the agile approach, rather than CMMI or ISO 9000, are perceived as supporting this objective. This clearly poses questions for SPI and ISO 9001 researchers. However, if SPI models are to be more widely deployed by early stage (start-ups) companies, existing models may have to be broadened to take account of the necessity for these companies to meet their development targets and ‘walk before they can run’ (Basri & O’Connor, 2010a; Basri & O’Connor, 2010b).
2.4. International Organization for Standardization
The mandate of the International Organization for Standardization (ISO) Sub-Committee 7 (SC7) is to develop, maintain, promote and facilitate IT standards required by global markets to meet business and user requirements concerning Software and Systems Engineering. A description of SC7 and of the development of ISO/IEC JTC1/SC7 standards is presented in Coallier (2003).
In 2005, a new ISO/IEC JTC1/SC7 Working Group (WG 24) was established with a mandate to investigate the need for and propose software life cycle profiles and guidelines for use in very small entities. In 2011, a first set of documents, titled ISO/IEC 29110, targeted at VSEs involved in the development or maintenance of software has been published by ISO (2011).
It should be noted that the authors of this paper are all key members of the ISO/IEC JTC1/SC7 WG24 standards development group and are also editors of various parts of the ISO/IEC 29110 standard. As such they have a unique insight into the development of a new standard and a direct influence on its development. In addition the papers authors are author/editors of the Deployment Packages and Implementation Guides, which will be described later in this paper. Accordingly the authors are in a position to provide a unique insight into the design, development and initial deployment of this innovative standard.
3. INNOVATION-DEVELOPMENT PROCESS APPROACH
This section provides an explanation of the approach taken to the design, development and implementation of ISO/IEC 29110 from a research perspective. To illustrate the development of the standards we have adopted the 6-stage model of the innovation-development process model, developed by Rogers (2003), as illustrated in Figure 1. Rogers defines the innovation-development process as follows: all the decisions, activities, and their impacts that occur from recognition of a need or problem, through research, development, and commercialization of an innovation through diffusion and adoption of the innovation by users, to its consequences.
Here we will briefly outline the 6 stages of Rogers model and outline the key actions required by ISO/IEC 29110 standard developers to utilize this model for the design and development of a new standard (Laporte, 2009):
Stage 1 - The Recognition of Needs and Problems: Primarily concerned with the awareness of a problem. In this paper we outline the lack of awareness and acceptance of existing standards by small and very small software companies and justify the need for a new approach to the development of process standards aimed specifically at very small companies;
Stage 2 - Basic and Applied Research: We describe both the design and results of an international survey of very small software companies, leading to an enhanced understanding of the actual needs of very small software companies from a process standard;
Stage 3 - Development: We describe the combination of the traditional approach to the development of a new standard with a novel approach to support the implementation, i.e. the development of a set of Deployment Packages;
Stage 4 - Commercialization: We depart from the traditional Rogers model by examining the route to the formal publication and of a new international standard and the dissemination exercise aimed at those businesses wishing to put in place a portfolio of software development management practices;
Stage 5 - Diffusion and Adoption: We describe a series of mini-research pilot projects with very small software companies as a means to accelerate the adoption and utilization of ISO/IEC 29110;
Stage 6 - Consequences of an Innovation: We present the potential positive and negative consequences of the publication of standards, the novel approach taken and the results to date of the research pilot projects.
Figure 1. Stages of the innovation-development process (adapted from Rogers 2003)
The main body of this paper (Section 3) is structured according to the 6 stages above. However, prior to that discussion it is necessary to clearly define the target audience for this standard, namely Very Small Entities (VSEs).
In the remainder of this section, we describe the design, development and implementation of a new standard according to the six stages of the Rogers model of Innovation-Development Process.
3.1. Stage 1 - The Recognition of Needs and Problems
The ISO/IEC 29110 standard is unique amongst software and systems engineering standards, in that the working group mandated to develop a new standard approached industry to conduct a needs assessment and gather actual requirements for a new standard.
The origins of the ISO/IEC 29110 project date back to a 2004 meeting of the ISO sub-committee (SC7) mandated to develop international Software Engineering standards, where there was a general recognition of the adoption issues presented by SC7 standards for small and very small companies. This lead directly to the subsequent formation of a working group (ISO/IEC JCT1/SC7 WG24) whose brief was to develop a software process lifecycle standard specific to meet the needs of VSEs whilst remaining compatible with existing ISO/IEC standards to allow a path for VSEs future growth and standards adoption (Laporte et al., 2008).
Commercial SPI models have not been widely adopted by small and very small companies and their influence in the software industry therefore remains more at a theoretical than practical level. There is now a substantial
body of research evidence (Laporte et al., 2008; Coleman & O’Connor, 2008b) that the majority of small software organizations are not adopting existing standards because they perceive the standards as being orientated towards large organizations. Studies have shown that small firms’ negative perceptions of process model standards are primarily driven by negative views of cost, documentation and bureaucracy. In addition, it has been reported that SMEs find it difficult to relate standards to their business needs and to justify the application of the international standards in their operations.
However quality-orientated process approaches and standards are maturing and gaining acceptance in many companies (O’Connor & Laporte, 2011a) and there is a clear benefit even to VSEs in the usage of standards. Amongst other positive effects, standards emphasize communication and shared understanding more than anything. Examples are: any documentation is consistent and what is needed to meet the needs of the organization; all users understand the same meaning of words used - if one person says, ‘Testing is completed!’, all affected bodies understand what those words mean. This kind of understanding is not only important in a global development environment; even a small group working in the same office might have difficulties in communication and understanding of issues shared by all. Standards can help in these and other areas to make the business more profitable because less time is spent on non-productive work.
### 3.2. Stage 2 - Basic and Applied Research
In order to ascertain an enhanced understanding of the utilization of ISO/SC7 standards and to collect data to identify problems and potential solutions specific to VSEs, a survey of VSEs was designed to validate some of the groups initial working goals and better understand VSE attitudes to and requirements of standards. A survey questionnaire was developed and translated into 9 languages: English, French, German, Korean, Portuguese, Thai, Turkish, Russian and Spanish. The survey is made up of 20 questions structured in 5 parts: General information, Information about standards utilization in VSEs, Information about implementation and assessment problems in VSEs, Information about VSE needs and Information about justification for compliance to standard(s).
Over 400 responses were collected from 29 countries. The detailed major findings are documented in (Laporte et al., 2008), however some salient points are discussed here. An interesting finding of the survey is the difference in the percentage of certified companies with regard to company size: less than 18% of VSEs are certified, while 53% of larger companies (more than 25 employees) claim to be certified. Furthermore, among those 18% who are certified, 75% of them do not use standards. In larger companies using standards, two families of standards and models emerge from the list: ISO standards (55%) and models from the Software Engineering Institute (SEI; 47%).
The survey anticipated the weak use of standards by VSEs by asking questions designed to provide a better understanding of the reasons for this. The three main ones are: lack of resources; standards are not required; and the nature of the standards themselves, with 15% of the respondents consider that the standards are difficult and bureaucratic, and do not provide adequate guidance for use in a small business environment.
For a large majority (74%) of VSEs, it is very important to be evaluated or certified against a standard. ISO certification is requested by 40% of them. Of those requesting official market recognition, only 4% are interested in a national certification. From the VSE perspective, some benefits provided by certification are:
- Increased competitiveness;
- Greater customer confidence and satisfaction;
• Greater software product quality;
• Increased sponsorship for process improvement;
• Decreased development risk;
• Facilitation of marketing (e.g. better image);
• Higher potential to export.
However, VSEs are expressing the need for assistance in order to adopt and implement standards. Over 62% would like more guidance with examples, and 55% are asking for lightweight and easy-to-understand standards complete with templates. Finally, the respondents indicated that it has to be possible to implement standards with minimum cost, time and resources. All data about VSEs and standards clearly confirm WG24’s fundamental assumption and the requirements. Therefore, WG24 uses this information to help define its approach for the development of profiles, guides and templates to meet VSE needs.
3.3. Stage 3 - Development
The approach (Laporte et al., 2008) used to develop ISO/IEC 29110 started with the pre-existing international standard ISO/IEC 12207 (ISO, 2008) dedicated to software process lifecycles. The overall approach consisted of three steps: (1) Selecting ISO/IEC 12207 process subset applicable to VSEs (2) Tailor the subset to fit VSE needs; and (3) Develop guidelines for VSEs.
At the core of this standard is a Management and Engineering Guide (ISO/IEC 29110-5; ISO, 2011a) focusing on Project Management and Software Implementation and an Assessment Guide (ISO/IEC 29110-3; ISO, 2011b). It is worth noting that as with all proposed ISO standards, ISO/IEC 29110 is subject to the normal ISO review process. During the development of the standard in excess of 1250 comments have been processed between 2008 and 2010. The entire set of documents, targeted by audience, has been developed to improve product, service quality, and process performance. These are Part 1: Overview, Part 2: Framework and Taxonomy, Part 3: Assessment Guide, Part 4: Profile Specifications and Part 5: Management and Engineering Guides. Parts 1 and 5 are mainly targeted to VSEs, Part 3 is targeted for Assessors and VSEs and Parts 2 and 4 are targeted for standards producers, tool vendors and methodology vendors. When a new profile is needed, Parts 4 and 5 can be developed or tailored from existing Parts 4 and 5 without impacting the other documents and they become Part 4-x and Part 5-x respectively through the ISO/IEC process.
3.4. Stage 4 - Commercialization
A novel approach taken to assist VSEs in the deployment of ISO/IEC 29110 is the development of a series of deployment packages (DP), to define guidelines explaining in more details the processes defined in the ISO/IEC 29110 profiles (Laporte, 2009). These guidelines will be freely accessible on the Internet to VSEs. A DP is a set of artifacts developed to facilitate the implementation of a set of practices, of the selected framework, in a VSE. A DP is not a process reference model (i.e. it is not prescriptive). The elements of a typical DP are: description of processes, activities, tasks, roles and products, template, checklist, example, reference and mapping to standards and models, and a list of tools. The mapping is only given as information to show that a deployment package has explicit links to standards, such as ISO/IEC 12207, or models, such as the CMMI for Development, hence by deploying and implementing the package, a VSE can see its concrete step to achieve or demonstrate coverage. Packages are designed such that a VSE can implement its content, without having to implement the complete framework at the same time. A set of nine DPs have been developed to date and are freely available from (DP, 2011). In addition a series of “Implementation Guides” have been developed to help implement a specific process supported by a tool and are freely available from (DP, 2011). To date five such guides have been developed.
These Deployment Packages and Implementation Guides mark a significant departure from existing standards development and are specifically designed to ease many of the issues and problems VSE have with implementing standards on a day to day basis, as outlined earlier. In addition a series of Eclipse plug-ins and have been made freely available to the public.
It is worth noting that the formal ISO mandate of a working group stops at this point with publication a new standard, as ISO are not directly involved with the usage of new standards. However, the authors have been involved in the full Rogers cycle on innovation-development with respect to the standard. Further, many members of WG24 have participated in commercialization type activities of ISO/IEC 29110 through the publication of papers, the participation in conferences and workshops and participation in numerous industry events.
The Rogers (2003) model envisages a traditional view of commercialization of an innovation. However, that is not strictly compatible with the development and launch of an international standard, as ISO standards are not commercial in the pure sense. Although many ISO standards are sold on a commercial basis, the costs involved are comparatively small. In the case of ISO/IEC 29110, most parts of the standard are being made freely available.
It is worth noting that as with all proposed ISO standards, ISO/IEC 29110 was subject to the normal ISO review and ballot (voting) process, with a final successful ballot in 2010 and formal publication in 2011 (ISO, 2011a). In 2012, the Entry profile, targeted at a six person-months effort project or a start-up VSE, has been published (ISO 2012a). Upon the request of WG24, ISO has made available at no cost the set of ISO/IEC 29110 technical reports.
3.5. Stage 5 - Diffusion and Adoption
The authors are advocating the use of pilot projects as a means to accelerate the adoption and utilization of ISO/IEC 29110 by VSEs. Pilot projects are an important means of reducing risks and learning more about the organizational and technical issues associated with the deployment of new software engineering practices. A successful pilot project is also an effective means of building adoption of new practices by members of a VSE. Pilot projects are based on the ISO/IEC 29110-5 Management and Engineering Guide (ISO, 2011a) and the deployment package(s). In particular these are aimed to collect, as a minimum, the following data:
- Effort and time to deploy by the VSE;
- Usefulness for the VSE;
- Verification of the understanding of the VSE;
- Self-assessments data - A self-assessment at the beginning of the pilot and at the end of the pilot project DP.
To further assist with the roll out of a pilot project and to ensure that all pilot projects are conducted similarly around the world, a set of pilot project guidelines were developed in the form of a Deployment Package (DP, 2011) to describe a process to conduct pilot projects. The primary purpose of this Deployment Package is to provide tailorable and usable guidelines and materials in order to select and conduct pilot projects in VSEs. The high-level tasks of this Deployment Package are:
- Assess the opportunity to conduct a pilot project;
- Plan the pilot project;
- Conduct the pilot project; and
- Evaluate the results of the pilot project.
An additional target audience, and an often forgotten one, in the area of software engineering standards comprise undergraduate and graduate students. In 2009, at the WG24 meeting in India, an informal interest group about education was formed (Laporte, 2009). The main objective is to develop a set of courses for software undergraduate and graduate students such that students learn about the ISO standards for VSEs before they graduate.
Work is already underway on the development of course modules to support DPs via a VSE Education Special Interest Group. To date four of the six courses have been developed and are freely available (VSE SIG, 2011). In addition the WG245 team has created an initial set of Wikipedia information pages in the English, French, Portuguese and Spanish language versions of Wikipedia and also a set of introductory videos (in both English and French) available on both PlanetISO (http://www.youtube.com/user/PlanetISO) and YouTube.
3.5.1. Network of Support Centres
An informal meeting of the ISO working group delegates was organized, by Canada in 2008, to launch a Network of collaborators as well as to explain to new participants of WG24 the purpose, objectives, the collaboration agreement and accomplishments of the new Network (Laporte, 2009). Essentially, the purpose of the Network aims to promote, facilitate and develop collaborative activities between institutions in the field of software engineering, information technology and others to improve VSE capabilities especially in Software Engineering and Information Technology (Laporte et al., 2008). The main objectives of the Network are to accelerate deployment of Standard and Guides for VSEs and to accelerate the development and application of Guides and Deployment Packages (e.g. through pilot projects). The current participants to the Network are:
- **Belgium**: Centre d’Excellence en Technologies de l’Information et de la Communication (CETIC)
- **Brazil**: RIO SOFTWARE agent for Brazilian software excellence in Rio de Janeiro
- **Canada**: École de Technologie Supérieure (ETS)
- **Colombia**: Parquesoft Foundation
- **Finland**: Tampere University of Technology, Pori
- **France**: Université de Bretagne Occidentale
- **Haiti**: Institut Universitaire Quisqueya-Amérique (INUQUA)
- **Hong Kong**: Polytechnic University
- **Ireland**: Lero, The Irish Software Engineering Research Centre
- **Luxembourg**: Public Research Centre Henri Tudor
- **Peru**: University of Lima; Universidad Peruana de Ciencias Aplicadas; and Universidad de San Martin de Porres
- **Thailand**: Institute of Software Promotion for Industries
Additional countries, such as Ecuador, Mexico, Spain and Japan are considering joining the Network.
3.6. Stage 6 - Consequences of an Innovation
As the official publication of this standard occurred in 2011 (ISO, 2011a) and given the slow nature of adoption of standards by VSEs, it is still somewhat early to definitively comment on the consequences of the development of ISO/IEC 29110. Some potential consequences or side-effects that could result from the publication of the ISO/IEC 29110 standards in imposing the standards on all the VSEs in a country or on all a customer’s VSEs are (Laporte, 2009):
- Some VSEs may lose valuable employees who do not want to use formal processes;
- Some VSEs may decide to ignore the regulation or shut down;
- Some VSEs might not be able to afford to implement the standard because of lack of internal expertise;
- The standards may impose practices that are in opposition to the culture of a VSE;
- VSEs may not be eligible for contracts if they do not comply with the standards;
- A VSE of a multi-national organization could be forced to put in place compliant processes which are different from those of other VSEs in the same organization, burdening that VSE with having to use the standards (e.g. VSEs may need 2 sets of processes: one to comply with national regulations and one to engage in devel-
opment with other members of a multi-national company).
Some potential consequences or side-effects by not imposing the standards on VSEs (laissez-faire) are (Laporte, 2009):
- Some VSEs may decide to ignore the standard, thereby slowly losing competitiveness;
- Some VSEs may not know that such a standard exists, thereby missing an opportunity to become more competitive;
- No government support is available to help VSEs adapt and implement the standards;
- Each VSE would have to invest separately to implement the standard (e.g. purchase training courses);
- Assessors may not be locally available to consult on, or assess, compliance with the standards.
However, extremely positive feedback has been received in relation to the pilot projects and also to the innovative development of Deployment Packages.
Whilst space limitations do not allow for a detailed discussion on research methodology, it is worth noting that the purpose of a pilot project is as an exploratory study. This may be used as a prelude to larger research study and for doing causal investigations and is aimed at elucidating and understanding the internal dynamics of program operations. The primary advantage of this type of case study approach is “it often highlights new insights or ideas and when used as a pilot study, it can sometimes generate ideas and focus research” (Patton, 1987).
4. DISCUSSION
Prior studies have shown the main reason for VSEs not adopting standards include a lack customer requirement, a lack of resources and the perceived difficulties in defining an organizational process (O’Connor, 2012). However, this study also revealed a pattern that indicates that the acceptance level of quality standards such as ISO/IEC 29110 among VSEs are still low even though the staff and management are knowledgeable and aware the benefit of adopting such standards. The main reasons are more related to the lack of customer requirement and limited resources in the company. In addition the perception a heavyweight process especially in terms of documentation, cost and non-alignment with current development process are among the reasons why the companies did not plan to adopt a lifecycle standard in the short to medium term. It is therefore critical that this standard is introduced to VSE in a systematic manner to demonstrate first hand to VSEs the benefits of ISO/IEC 29110.
4.1. Pilot Projects
The working group (ISO/IEC JTC1/SC7 WG 24) behind the development of this standard is advocating the use of pilot projects as a means to accelerate the adoption and utilization of ISO/IEC 29110 by VSEs around the world. Pilot projects are an important means of reducing risks and learning more about the organizational and technical issues associated with the deployment of new software engineering practices. A successful pilot project is also an effective means of building adoption of new practices by members of a VSE. Pilot projects are based on the ISO/IEC 29110-5 Management and engineering guide (ISO, 2011a) and the deployment package(s). In particular these are aimed to collect, as a minimum, the following data:
- Effort and time to deploy by the VSE;
- Usefulness for the VSE;
- Verification of the understanding of the VSE;
- Self-assessments data - A self-assessment at the beginning of the pilot and at the end of the pilot project DP.
To date a series of pilot projects have been completed in several countries utilizing
some of the deployment packages developed. For example in Canada a pilot study has been conducted in an IT department with a staff of 4: 1 analyst and 3 developers, who were involved in the translation and implemented 3 DPs: Software Requirements, Version Control, Project Management (O’Connor & Laporte, 2012). In Belgium a VSE of 25 people started with a process assessment phase aiming to identify strengths and weaknesses in development related processes (Boucher et al., 2012). This company is now working on improvement actions mainly based on the following Deployment Packages: Requirement Analysis, Version Control, and Project Management.
A series of pilot projects are currently underway in Canada (Laporte et al., 2013a), Ireland (O’Connor and Sanders 2013), Belgium and France (Ribaud et al., 2010), with further pilot projects planned in the near future. To date we have published (Ribaud et al., 2010) the final conclusions and results of one pilot project that was conducted with a 14-person VSE based in France, which successfully implemented ISO/IEC 29110 processes utilizing the available Deployment Packages. From this we have identified some potential additional infrastructure and support process activities and suggestions for the future evolution of ISO/IEC 29110 Process Profiles.
Brazil has developed, with the Brazilian Standard organization ABNT (Associação Brasileira de Normas Técnicas) an ISO/IEC 29110 certification scheme. A first series of VSEs from Brazil should obtain an ISO/IEC 29110 certificate of conformance in 2013. The auditing scheme, developed by Brazil, will probably be used by other countries, such as Canada, to audit their VSEs (Laporte et al., 2013b).
4.2. Future Work
As ISO/IEC 29110 is an emerging standard there is much work yet to be completed (Laporte et al., 2013c). The main remaining work item is to finalize the development of the remaining two profiles: (a) Intermediate Level - Management of more than one project and (b) Advanced Level - business management and portfolio management practices. The Intermediate profile is targeted for publication by ISO either at the end of 2014 or at the beginning of 2015 (ISO, 2012c). In addition the development of additional Profile Groups for other domains such as critical software, game industry, scientific software development are being studied.
With any new initiative there is much to be learned from conducting pilot projects. One issue of major importance to VSEs which is emerging from these pilot projects and similar work by the ISO working group is the need for a light-weight flexible approach to process assessment. Whilst work is currently underway on an assessment mechanism for ISO/IEC 29110 (ISO, 2011b), a clear niche market need is emerging which may force the process assessment community to change their views on how process assessments are carried out for VSEs (O’Connor & Laporte, 2011b). In particular there is a strong need to ensure that VSEs are not required to invest anything similar in terms of time, money and other resources on process assessments, as may be expected from their larger SMEs (small and medium enterprises), or even MNC (multinational corporations) counterparts. Indeed some form of self-assessment, possibly supported by Internet based tools, along with periodic spot-checks may be a suitable alternative to meet the unique needs of VSEs. It is clear that the process assessment community will have to rethink process assessment, new methods and ideas for assessing processes in VSEs.
Furthermore, work is currently underway on broadening the ISO/IEC 29110 standard from purely Software Engineering lifecycle support to explicitly include Systems Engineering lifecycles (Laporte et al., 2012). It is anticipated that in the near future a Systems Engineering suite of VSE standards will emerge from ISO/IEC JCT1/SC7 Working Group 24. A systems engineering first profile, the Basic profile, has been circulated for a second round of review in
2012 (ISO 2012d). The Basic profile should be published by ISO in 2014. The draft Basic profile is already being piloted by a subway equipment manufacturer in Canada. The development of the systems engineering Entry profile has also been initiated in 2013. The Entry profile could be published either at the end of 2014 or at the beginning of 2015.
5. CONCLUSION
The documents used by WG24 and the approach that led to the development of the International Standards and Technical Reports for VSEs were presented. The approach taken by WG24 corresponds to the mixed economy approach, where the intent is to help VSEs succeed in business by providing them with a set of software engineering practices tailored to their needs, in the form of international standards, technical reports and deployment packages.
It is expected that some VSEs will use the technology developed on their own, other VSEs will get some help from government organizations, such as training or coaching, and some large organizations will impose the ISO/IEC 29110 standards on the VSEs that supply components for their products. A few countries have opted for the ‘survival of the fittest’ strategy for their VSEs, i.e. an approach where a government does not intervene in the marketplace and lets the market decide which VSEs will survive. At the same time, a number of government agencies, universities, research centers and associations are working to determine how to help VSEs. They share some of the following assumptions about the needs of VSEs (Laporte & Palza-Vargas, 2012):
- VSEs require low-cost solutions;
- VSEs require readily usable processes supported by guides, templates, examples and tools;
- VSEs require additional effort in communications and in standardizing vocabulary;
- VSEs require a staged approach to help them grow their capabilities;
- VSEs require ways to identify potential quick wins;
- VSEs require guidance in the selection and implementation of software practices.
ACKNOWLEDGMENT
This work was supported, in part, by Science Foundation Ireland grant 10/CE/I1855 to Lero - the Irish Software Engineering Research Centre (www.lero.ie).
REFERENCES
Copyright © 2014, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Rory V. O’Connor is a Senior Lecturer in Software Engineering at Dublin City University and a Senior Researcher with Lero, the Irish Software Engineering Research Centre. He has previously held research positions at both the National Centre for Software Engineering and the Centre for Teaching Computing, and has also worked as a software engineer and consultant for several European technology organizations. He is also Ireland’s Head of delegation to ISO/IEC JCT1/SC7, a member of ISO/IEC JTC1/SC7 Working Group 24 and editor of ISO/IEC 29110-2:2011. His research interests are centered on the processes whereby software intensive systems are designed, implemented and managed. His focus is on researching methods, techniques, tools and standards for supporting the work of software project managers and software developers in relation to software process improvement, and the management of software development projects.
Claude Y Laporte is a Professor of software engineering at the École de technologie supérieure. His research interests include software process improvement in small and very entities and software quality assurance. He is the co-author of 2 French textbooks about software quality assurance published by Hermes-Lavoisier in 2011. The IEEE Computer Society and John Wiley and Sons will publish an English version of the French textbooks in 2014. He is the Editor of the ISO/IEC JTC1 SC7 Working Group tasked to develop systems and software engineering standards and guides for use in very small entities. He is a member of the Computer Society of the Institute of Electrical and Electronics Engineers (IEEE), the Project Management Institute (PMI), the International Council on Systems Engineering (INCOSE) and the Professional association of engineers of the Province of Québec (l’Ordre des ingénieurs du Québec). He is overall managing editor of ISO/IEC 29110. He was awarded an honorary doctorate by the Universidad de San Martin de Porres (Peru) in 2013. Information about ISO/IEC 29110 standards and technical reports can be found at http://profs.etsmtl.ca/claporte/English/VSE/index.html
Table 4. Objectives of the software implementation process of the basic profile
<table>
<thead>
<tr>
<th>Objective</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>SI.O21</td>
<td>Tasks of the activities are performed through the accomplishment of the current Project Plan.</td>
</tr>
<tr>
<td>SI.O2</td>
<td>Software requirements are defined, analyzed for correctness and testability, approved by the Customer, baselined and communicated.</td>
</tr>
<tr>
<td>SI.O3</td>
<td>Software architectural and detailed design is developed and baselined. It describes the Software Components and internal and external interfaces of them. Consistency and traceability to software requirements are established.</td>
</tr>
<tr>
<td>SI.O4</td>
<td>Software Components defined by the design are produced. Unit test are defined and performed to verify the consistency with requirements and the design. Traceability to the requirements and design are established.</td>
</tr>
<tr>
<td>SI.O5</td>
<td>Software is produced performing integration of Software Components and verified using Test Cases and Test Procedures. Results are recorded at the Test Report. Defects are corrected and consistency and traceability to Software Design are established.</td>
</tr>
<tr>
<td>SI.O6</td>
<td>A Software Configuration, that meets the Requirements Specification as agreed to with the Customer, which includes user, operation and maintenance documentations, is integrated, baselined and stored at the Project Repository. Needs for changes to the Software Configuration are detected and related change requests are initiated.</td>
</tr>
<tr>
<td>SI.O8</td>
<td>Verification and Validation Tasks of all required work products are performed using the defined criteria to achieve consistency among output and input products in each activity. Defects are identified, and corrected; records are stored in the Verification/Validation Results.</td>
</tr>
</tbody>
</table>
APPENDIX
Overview of ISO/IEC 29110
The purpose of the Basic Profile is to define Software Implementation (SI) and Project Management (PM) processes from a subset of ISO/IEC 12207 and ISO/IEC 15289 appropriate for VSEs. The main reason to include project management is that the core business of VSEs is software development and their financial success depends on successful project completion within schedule and on budget, as well as on making a profit. The high-level relationship between the SI and the PM processes is illustrated in Figure 2.
As illustrated in Figure 3, the customer’s statement of work is used to initiate the PM process. The project plan will be used to guide the execution of the software requirements analysis, software architectural and detailed design, software construction, and software integration and test, and product delivery activities. Verification, validation, and test tasks are included in the SI process. The PM process closure activity will deliver the Software Configuration (i.e. a set of software products) and will obtain the customer’s acceptance to formalize the end of the project.
Overview of the Project Management Process
The purpose of the Project Management process is to establish and carry out the tasks of the software implementation project in a systematic way, which allows compliance with the project’s objectives in terms of expected quality, time, and costs. The seven objectives of the PM process are listed in Table 2.
Figure 3 illustrates the 4 activities of the project management process as well as their input and output product. Each activity is composed of tasks. The task description doesn’t impose any technique or method to perform it. Even though, a sequential view is presented in Figure
3, ISO/IEC 29110 is not intended to preclude the use of different life cycles such as waterfall, iterative, incremental, evolutionary or agile.
For illustration purposes, two tasks of the Project Planning activity are listed in Table 3. On the left side of the table are listed the roles involved in a task. The project manager (PM) and the customer (CUS) are involved in these 2 tasks. The customer is involved, during the execution of the project, when he submits change requests, during project review meetings, for the validation and approval of the requirements specifications and for the acceptance of the deliverables.
Overview of the Software Implementation Process
The purpose of the Software Implementation process, illustrated in Figure 4, is to achieve systematic performance of the analysis, design, construction, integration, and test activities for new or modified software products according to the specified requirements. Figure 4 illustrates the 4 activities of the SI process as well as their input and output products. Even though, a sequential view is presented in Figures 3 and 4, ISO/IEC 29110 is not intended to preclude the use of different lifecycles such as waterfall, iterative, incremental, evolutionary or agile.
The purpose of the (SI) process is to achieve systematic performance of the analysis, design, construction, integration, and test activities for new or modified software products according to the specified requirements. The seven objectives of the SI process are listed in Table 4.
Table 2. Objectives of the project management process of the basic profile
<table>
<thead>
<tr>
<th>Objective</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>PM.O1</td>
<td>The Project Plan for the execution of the project is developed according to the Statement of Work and reviewed and accepted by the Customer. The tasks and resources necessary to complete the work are sized and estimated.</td>
</tr>
<tr>
<td>PM.O2</td>
<td>Progress of the project is monitored against the Project Plan and recorded in the Progress Status Record.</td>
</tr>
<tr>
<td>PM.O3</td>
<td>The Change Requests are addressed through their reception and analysis. Changes to software requirements are evaluated for cost, schedule and technical impact.</td>
</tr>
<tr>
<td>PM.O4</td>
<td>Review meetings with the Work Team and the Customer are held. Agreements are registered and tracked.</td>
</tr>
<tr>
<td>PM.O5</td>
<td>Risks are identified as they develop and during the conduct of the project.</td>
</tr>
<tr>
<td>PM.O6</td>
<td>A software Version Control Strategy is developed. Items of Software Configuration are identified, defined and baselined. Modifications and releases of the items are controlled and made available to the Customer and Work Team including the storage, handling and delivery of the items.</td>
</tr>
<tr>
<td>PM.O7</td>
<td>Software Quality Assurance is performed to provide assurance that work products and processes comply with the Project Plan and Requirements Specification.</td>
</tr>
</tbody>
</table>
Table 3. Example of 2 tasks of the project planning activity
<table>
<thead>
<tr>
<th>Role</th>
<th>Task</th>
<th>Input</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>PM</td>
<td>PM.1.2 Define with the Customer the Delivery Instructions of each one of the Deliverables specified in the Statement of Work.</td>
<td>Statement of Work [reviewed]</td>
<td>Project Plan Delivery Instructions</td>
</tr>
<tr>
<td>CUS</td>
<td>PM.1.14 Review and accept the Project Plan. Customer reviews and accepts the Project Plan, making sure that the Project Plan elements match with the Statement of Work.</td>
<td>Project Plan [verified]</td>
<td>Meeting Record Project Plan [accepted]</td>
</tr>
</tbody>
</table>
Copyright © 2014, IGI Global. Copying or distributing in print or electronic forms without written permission of IGI Global is prohibited.
Figure 4. ISO/IEC 29110 software implementation process
CALL FOR ARTICLES
International Journal of Information Technologies and Systems Approach
An official publication of the Information Resources Management Association
MISSION:
The International Journal of Information Technologies and the Systems Approach (IJITSA) publishes research articles that are globally relevant for IT stakeholders and where a systemic interdisciplinary and/or a multi-methodology research perspective are considered. IJITSA improves scientific and technological knowledge regarding the engineering and management of IT systems by fostering the utilization of the Systems Approach.
COVERAGE/MAJOR TOPICS:
- Agent-based simulation
- Axiology of systems
- Complex systems foundations
- Complex systems frameworks, models and processes
- Critical heuristics systems
- Critical systems
- Epistemology of systems
- Information security systems
- Mathematical analysis of systems
- Multi-scale analysis
- Ontology of systems
- Philosophy of systems sciences
- Socio-technical systems
- Soft systems methodology
- System dynamics
- System of systems concepts
- Systemic action research
- Systemic analysis of ISO, IEEE, ANSI, TIA standards
- Systemic business process-oriented frameworks
- Systemic case study
- Systemic conceptual study
- Systemic decision-making models
- Systemic design of IT systems
- Systemic design of service systems
- Systemic design of SoS (System of Systems)
- Systemic design of systems
- Systemic evaluation of IT systems
- Systemic evaluation of software development tools
- Systemic experiments
- Systemic green IT frameworks
- Systemic implementation of IT systems
- Systemic IT service management frameworks
- Systemic IT service management standards (ITIL, ISO 20000, Co-bIT, CMMI-SVC, etc)
- Systemic review of ISO, CMMI and IEEE systems engineering standards
- Systemic review of software development agile methods
- Systemic review of software development business process-oriented methods
- Systemic review of software development service-oriented methods
- Systemic risk management
- Systemic service-oriented frameworks
- Systemic software process frameworks (CMMI, ISO 12207, ISO 29110, IEEE 1471, etc)
- Systemic surveys
- Systemic TOEP feasibility studies
- Systems Analysis
- Systems design
- Systems engineering frameworks
- Systems evaluation
- Systems simulation
- Total systems intervention
- Viable system models
IDEAS FOR SPECIAL THEME ISSUES may be submitted to the Editor-in-Chief.
Please recommend this publication to your librarian. For a convenient easy-to-use library recommendation form, please visit:
http://www.igi-global.com/IJITSA
|
{"Source-Url": "http://doras.dcu.ie/19995/1/oconnor_paper_jitsa_7.1.pdf", "len_cl100k_base": 13441, "olmocr-version": "0.1.50", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 63493, "total-output-tokens": 17976, "length": "2e13", "weborganizer": {"__label__adult": 0.0003421306610107422, "__label__art_design": 0.0004611015319824219, "__label__crime_law": 0.0003933906555175781, "__label__education_jobs": 0.00482940673828125, "__label__entertainment": 6.604194641113281e-05, "__label__fashion_beauty": 0.00018286705017089844, "__label__finance_business": 0.0019044876098632812, "__label__food_dining": 0.00033855438232421875, "__label__games": 0.0005664825439453125, "__label__hardware": 0.0005965232849121094, "__label__health": 0.0003840923309326172, "__label__history": 0.0003638267517089844, "__label__home_hobbies": 9.98377799987793e-05, "__label__industrial": 0.0004608631134033203, "__label__literature": 0.000362396240234375, "__label__politics": 0.0003352165222167969, "__label__religion": 0.0003695487976074219, "__label__science_tech": 0.0173797607421875, "__label__social_life": 0.00010150671005249023, "__label__software": 0.00980377197265625, "__label__software_dev": 0.9599609375, "__label__sports_fitness": 0.00024330615997314453, "__label__transportation": 0.0004651546478271485, "__label__travel": 0.00022745132446289065}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75488, 0.02216]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75488, 0.29025]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75488, 0.91508]], "google_gemma-3-12b-it_contains_pii": [[0, 1906, false], [1906, 4257, null], [4257, 8306, null], [8306, 12462, null], [12462, 16451, null], [16451, 20569, null], [20569, 24424, null], [24424, 27622, null], [27622, 31470, null], [31470, 35281, null], [35281, 39081, null], [39081, 42628, null], [42628, 46071, null], [46071, 50070, null], [50070, 53865, null], [53865, 58195, null], [58195, 62834, null], [62834, 65691, null], [65691, 67459, null], [67459, 69225, null], [69225, 69852, null], [69852, 72821, null], [72821, 72877, null], [72877, 75488, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1906, true], [1906, 4257, null], [4257, 8306, null], [8306, 12462, null], [12462, 16451, null], [16451, 20569, null], [20569, 24424, null], [24424, 27622, null], [27622, 31470, null], [31470, 35281, null], [35281, 39081, null], [39081, 42628, null], [42628, 46071, null], [46071, 50070, null], [50070, 53865, null], [53865, 58195, null], [58195, 62834, null], [62834, 65691, null], [65691, 67459, null], [67459, 69225, null], [69225, 69852, null], [69852, 72821, null], [72821, 72877, null], [72877, 75488, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75488, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75488, null]], "pdf_page_numbers": [[0, 1906, 1], [1906, 4257, 2], [4257, 8306, 3], [8306, 12462, 4], [12462, 16451, 5], [16451, 20569, 6], [20569, 24424, 7], [24424, 27622, 8], [27622, 31470, 9], [31470, 35281, 10], [35281, 39081, 11], [39081, 42628, 12], [42628, 46071, 13], [46071, 50070, 14], [50070, 53865, 15], [53865, 58195, 16], [58195, 62834, 17], [62834, 65691, 18], [65691, 67459, 19], [67459, 69225, 20], [69225, 69852, 21], [69852, 72821, 22], [72821, 72877, 23], [72877, 75488, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75488, 0.09281]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
c52d4d83ef2d0dc3c48a44aa05cfd1232bd560cd
|
[REMOVED]
|
{"Source-Url": "http://www.researchgate.net/profile/Chris_Stary/publication/225633967_Whom_to_talk_to_A_stakeholder_perspective_on_business_process_development/links/0c960526e2246b5870000000.pdf", "len_cl100k_base": 14273, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 65680, "total-output-tokens": 18067, "length": "2e13", "weborganizer": {"__label__adult": 0.0005445480346679688, "__label__art_design": 0.0036716461181640625, "__label__crime_law": 0.0006976127624511719, "__label__education_jobs": 0.0231781005859375, "__label__entertainment": 0.00027942657470703125, "__label__fashion_beauty": 0.00038695335388183594, "__label__finance_business": 0.0247650146484375, "__label__food_dining": 0.0006618499755859375, "__label__games": 0.001110076904296875, "__label__hardware": 0.0015230178833007812, "__label__health": 0.0007348060607910156, "__label__history": 0.0010595321655273438, "__label__home_hobbies": 0.0003769397735595703, "__label__industrial": 0.00279998779296875, "__label__literature": 0.001453399658203125, "__label__politics": 0.0007996559143066406, "__label__religion": 0.0007882118225097656, "__label__science_tech": 0.244873046875, "__label__social_life": 0.00025391578674316406, "__label__software": 0.040374755859375, "__label__software_dev": 0.6474609375, "__label__sports_fitness": 0.0003230571746826172, "__label__transportation": 0.0014448165893554688, "__label__travel": 0.0003573894500732422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 84679, 0.02398]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 84679, 0.56514]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 84679, 0.91503]], "google_gemma-3-12b-it_contains_pii": [[0, 3270, false], [3270, 8728, null], [8728, 14034, null], [14034, 19456, null], [19456, 24588, null], [24588, 28106, null], [28106, 33627, null], [33627, 35316, null], [35316, 36014, null], [36014, 37224, null], [37224, 39876, null], [39876, 43754, null], [43754, 45033, null], [45033, 48656, null], [48656, 49289, null], [49289, 52365, null], [52365, 54554, null], [54554, 56261, null], [56261, 56873, null], [56873, 60082, null], [60082, 62951, null], [62951, 66503, null], [66503, 70260, null], [70260, 75624, null], [75624, 80589, null], [80589, 84679, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3270, true], [3270, 8728, null], [8728, 14034, null], [14034, 19456, null], [19456, 24588, null], [24588, 28106, null], [28106, 33627, null], [33627, 35316, null], [35316, 36014, null], [36014, 37224, null], [37224, 39876, null], [39876, 43754, null], [43754, 45033, null], [45033, 48656, null], [48656, 49289, null], [49289, 52365, null], [52365, 54554, null], [54554, 56261, null], [56261, 56873, null], [56873, 60082, null], [60082, 62951, null], [62951, 66503, null], [66503, 70260, null], [70260, 75624, null], [75624, 80589, null], [80589, 84679, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 84679, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 84679, null]], "pdf_page_numbers": [[0, 3270, 1], [3270, 8728, 2], [8728, 14034, 3], [14034, 19456, 4], [19456, 24588, 5], [24588, 28106, 6], [28106, 33627, 7], [33627, 35316, 8], [35316, 36014, 9], [36014, 37224, 10], [37224, 39876, 11], [39876, 43754, 12], [43754, 45033, 13], [45033, 48656, 14], [48656, 49289, 15], [49289, 52365, 16], [52365, 54554, 17], [54554, 56261, 18], [56261, 56873, 19], [56873, 60082, 20], [60082, 62951, 21], [62951, 66503, 22], [66503, 70260, 23], [70260, 75624, 24], [75624, 80589, 25], [80589, 84679, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 84679, 0.01718]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
36fe82f7c274f9c4ce6ea174f132a0c4a6c234e2
|
An Exploratory Study on Faults in Web API Integration in a Large-Scale Payment Company
Aué, Joop; Aniche, Maurício; Lobbezoo, Maikel; van Deursen, Arie
DOI
10.1145/3183519.3183537
Publication date
2018
Document Version
Accepted author manuscript
Published in
ICSE-SEIP '18: 40th International Conference on Software Engineering: Software Engineering in Practice Track
Citation (APA)
Important note
To cite this publication, please use the final published version (if applicable). Please check the document version above.
ABSTRACT
Service-oriented architectures are more popular than ever, and increasingly companies and organizations depend on services offered through Web APIs. The capabilities and complexity of Web APIs differ from service to service, and therefore the impact of API errors varies. API problem cases related to Adyen’s payment service were found to have direct considerable impact on API consumer applications. With more than 60,000 daily API errors, the potential impact is enormous. In an effort to reduce the impact of API related problems, we analyze 2.43 million API error responses to identify the underlying faults. We quantify the occurrence of faults in terms of the frequency and impacted API consumers. We also challenge our quantitative results by means of a survey with 40 API consumers. Our results show that 1) faults in API integration can be grouped into 11 general causes: invalid user input, missing user input, expired request data, invalid request data, missing request data, insufficient permissions, double processing, configuration, missing server data, internal and third party, 2) most faults can be attributed to the invalid or missing request data, and most API consumers seem to be impacted by faults caused by invalid request data and third party integration; and 3) insufficient guidance on certain aspects of the integration and on how to recover from errors is an important challenge to developers.
CCS CONCEPTS
• Information systems → Web services; Web applications; • Software and its engineering;
KEYWORDS
web engineering, web API integration, webservice.
1 INTRODUCTION
Service-oriented architectures are now more popular than ever. Companies and organizations increasingly offer their services through Web Application Programming Interfaces (Web APIs). Web APIs enable clients to access third party services and data sources, and use them as building blocks for developing applications, e.g., Airbnb utilizes Google’s Calendar API to automatically insert bookings into the renter’s calendar, and Google Maps consumes Uber’s Ride Request API to offer Uber’s services as means of transportation in their maps application.
The capabilities and complexity of Web APIs inevitably differ from service to service. Retrieving a list of followers for a user on Twitter requires a GET request including a single parameter, and posting a Twitter status update using the Twitter API takes a single parameter POST request. As the complexity of the actions increases, so do the possibilities of failure. For instance, GitHub’s Repo Merging API supports merging branches in a repository. In addition to the intended merge, other possible outcomes are a merge conflict, a missing branch error or a nothing to merge response.
Adyen1, a multi-tenant Software as a Service (SaaS) platform that processes payments, offers an authorization request used to initiate a payment from a shopper, which takes up to 35 parameters. Multiple types of shopper interaction, and optional fields to optimize fraud detection and improve shopper experience lead to numerous failure scenarios. In addition to the happy path, the method can return at least 34 unique error messages to inform the API consumer that something has gone wrong.
To make error handling for client developers easier, practitioners have written a variety of best practice guides and blogposts on API design [11] [21] [13] [18]. Apigee [1], a platform offering API tools and services for developers and enterprises, discusses error handling in multiple books. Apigee’s error handling best practices focus on which HTTP status codes to use [2] and suggest to return detailed error messages for users and developers [3]. However, to our knowledge no research has been conducted on what type of errors occur in practice and what causes them to happen. Not only can this knowledge complement existing API design best practices, it can help improve API documentation and help developers understand the common integration pitfalls.
The potential impact of API errors on API consumer applications is enormous. At the same time an understanding of API errors that occur in practice and their impact is missing. This gap of knowledge motivated us to investigate the domain of Web API errors. To this aim, we study the API error responses returned by Adyen webservice which handle millions of API requests on a daily basis. We analyze 2.43 million error responses, which we
extract from the platform’s production logs, discover the underlying faults, and group them into high-level causes. In addition, we survey API consumers about their perceptions on the impact and how often they observe such cases in their APIs, as well as practices and challenges they currently face when it comes to integrating to Web APIs. Finally, we provide API developers and consumers with recommendations that would help in reducing the number of existing integration errors.
Our results show that (1) faults in API integration can be grouped in 11 causes: invalid user input, missing user input, expired request data, invalid request data, missing request data, insufficient permissions, double processing, configuration, missing server data, internal and third party. Each cause can be contributed to one of the four API integration stakeholders: end user, API consumer, API provider, and third parties; (2) most faults can be attributed to the invalid or missing request data, and most API consumers seem to be impacted by faults caused by invalid request data and third party integration; and (3) API consumers most often use official API documentation to implement an API correctly, followed by code examples. The challenges of preventing problems from occurring are the lack of implementation details, insufficient guidance on certain aspects of the integration and insights in problems and changes, insufficient understanding of the impact of problems, missing guidance on how to recover and a lack of details on the origin of errors.
The main contributions of this work are as follows:
(1) A classification of API faults, resulting in 11 causes of API faults, based on 2.43 million API error responses of a large industrial multi-tenant SaaS platform (Section 4.1).
(2) An empirical understanding of the prevalence of API fault types in terms of the number of errors and impacted API consumers (Section 4.2).
(3) An initial understanding of the impact of each cause as experienced by API consumers as well as their observations on current challenges during API integration (Section 4.3).
(4) A set of recommendations for API providers and API consumers to reduce the impact of API related faults (Section 5.1).
2 BACKGROUND: UNDERSTANDING THE WEB API ENVIRONMENT
An API integration can involve up to four different stakeholders, that all influence the interaction between the API and its consumer. As a result, each of these stakeholders can cause the API to return with an error that possibly leads to a failure in the consumer’s application. In this section, we give an overview of the API environment, the parties involved and API error related terminology, to clarify the differences and nuances that could lead to confusion.
In a typical integration with an API, two stakeholders, or parties, are involved. On one side the API provider, offering their services by exposing an API, and on the other side the API consumer, utilizing the services offered by communicating with the API. The API provider may optionally itself be connected to third party services behind the scenes in order to provide the intended functionality. For instance, an API offering stock data may itself be connected to different stock exchanges to obtain the latest stock prices. We deliberately refer to API consumer, instead of API user, to leave room for the term end user. The API consumer may optionally provide an application used by its customers, who indirectly make use of the API’s services. These end users supply information, while using the application, that is used as request data for the API. For example, Google Maps users are given the option to choose Uber as means of transportation when searching for directions. Indirectly they are supplying input to the Uber API, which locates nearby drivers and estimates the cost for the trip.
In the system under study, the API provider, Adyen, provides its payment services through its API. The API consumer is the merchant processing payments using the Adyen solution (e.g., a store). The end users are shoppers, who use the merchant’s services to buy goods or services. Finally, third parties connected to Adyen typically include banks, schemes, and issuers.
Each of the stakeholders in the API stakeholder overview can, by introducing a fault, potentially cause an erroneous response to be returned by the API, which if unexpected can result in problems for the application. We provide an overview of the integration environment containing the involved stakeholders and the relation between faults, errors and failure in Figure 1. In case the API is indirectly in use by customers of the API consumer, the end user can, by supplying invalid information, cause the API to return an error. The API consumer, on the other hand, may have implemented the API incorrectly, which can result in requests with a specific input to be rejected by the API. The API provider may have a bug in its system, which could, for instance, cause requests to fail on a specific input. Lastly, when a third party service fails, the API provider may decide to return an error to the API consumer.
3 RESEARCH METHODOLOGY
The goal of this study is to understand the faults that occur in API integration that can potentially result in production problems for consumers of an API. To this aim, we propose the following research questions:
RQ1. What type of faults are impacting API consumers?
Translating the understanding of faults in one API integration to API integrations in general is difficult, because every API has its own use cases, specific methods and corresponding errors. To enable generalization of the results we identify general causes of faults that can occur in an API integration.
RQ2. What is the prevalence of these fault types, and how many API consumers are impacted by them? The answer to this question provides insights into the frequency of each type of fault and the impact in terms of number of API consumers. API designers can leverage the information of what type of fault impact the user the most when designing an API to lower the probability that these faults take place and result into problems. In addition, the knowledge will help identify what aspects of integration are more difficult to get right, which therefore require more attention in terms of, for instance, documentation.
RQ3. What are the current practices and challenges to avoid and reduce the impact of problems caused by faults in API integration? Understanding what type of faults occur in API integrations, how often these faults occur and their impact is not enough to determine how the impact of production problems can be reduced. An understanding is needed of the current practices used to avoid and reduce problems, before recommendations for improvements can be made. Similarly, an understanding of the current challenges faced by API consumers is needed to identify areas of improvement.
To answer the RQs, we collect and analyze data from two different sources: over 2 million API error response logs from Adyen’s production services, and a survey with API consumers. We use this first batch of data to answer the types of fault in Web API integration as well as their prevalence. After, we challenge our findings by means of a survey with 40 API consumers. In the following, we detail each data collection mechanism.
3.1 Analysis of the API error response logs
The data extraction approach can be depicted into four steps: (1) We extract API error responses from production log data to obtain unique API errors, (2) we manually analyze each unique error message in context of the web service and API method to identify unique faults, (3) the time span covered by the data set is verified to cover enough data, and (4) we derive a set of causes that explain the API integration failures.
The logs of the system under study contain information about everything that happened in the production environment. Among the logs are the API requests and corresponding responses. Using domain knowledge of the system, we identified queries to capture the erroneous API response log messages from the entire set of log messages. The data set we use contains 28 days of data and 2.66 million API error responses.
To make sure 28 days would provide enough data for the analysis, we measured the amount of new information each new day was bringing to the dataset. We find that, after 14 days of data, at most 2 new faults are identified per day with the number decreasing as more days pass. For this reason we conclude that the most common and therefore impacting faults in our data set are discovered within 14 days and therefore consider the 28 day data set to cover a sufficient time span. In Figure 2, we show the amount of new information that each day aggregates to the dataset. However, the error messages alone are not enough to explain the faults. There are messages that indicate one fault, but in practice have a different meaning. For instance, “Unsupported currency specified”, appears to be a configuration mistake or an invalid input fault. However, this specific error is caused by a missing value. Other messages, e.g., “Internal error”, are too ambiguous to categorize in the first place. Thus, to reduce the number of unique messages with multiple explanations, we add more context to the unique error messages. To do so, we use the corresponding API method and web service that caused the error. For instance, the message “Invalid amount specified” has multiple explanations that depend on the API method used. Adding context allows for more granularity during analysis. We end up with 363 different errors to analyze.
In practice, we observed that the analysis of these errors are intensive manual tasks, i.e., for each error, we had to comprehend the failure, inspect the source code, and talk to the developers of the system. Thus, we consider errors that impacted 10 API consumers or more. Following this approach, we analyzed 89 of the 363 errors, which covers approximately 2.44 (91.3%) of the 2.66 million erroneous API responses. After analyzing each of them, we found 69 different explanations for these 89 errors (we refer to them as fault cases [FC01..FC69] and they can be found in our appendix [4]), which we use as an input to determine the high-level causes.
Identifying the causes and assigning each of them to a fault is an iterative process, based on a detailed qualitative analysis of the fault cases. Investigating a subset of faults gives the intuition needed to define initial causes, which can be assigned to most of the annotated faults. During further analysis, if a fault does not fit into one of the existing causes, we define a new cause. A cause that is too generic may have to be split up into two or more causes, while a cause that is too specific may be joined with another cause. Categorization can therefore not be described by a predefined set of steps, but is guided by our understanding of the problem domain, and the actual analysis of the cases at hand. After assigning a cause to each fault, we iterate once more over all faults to check that all causes are accurate. Following this procedure we obtain a set of causes that describe faults in API integration in general.
To verify the accuracy of the categorization, we asked a specialist in API integration from Adyen to check a subset of the cause assignments. As our list was already randomized, the specialist validated the first 50% assignments. In case the specialist does not agree with the cause, the difference is discussed until agreement is reached. Using this approach, we verify that the causes are understandable and reduce the possibilities of mistakes. At the end, we derived 11 causes that explain faults in Web API integration.
In practice, we observed that, due to unclear error messages, about half of the faults originating from error messages that have two or more different causes. Propagating these causes to the entire 2.43 million error messages would require analyzing each case in isolation. Thus, we are not able to perfectly estimate the prevalence of each cause; rather, we provide lower and upper bounds. The former is calculated by only counting the number of times that a cause unambiguously explains the error (i.e., the error message was clear enough to identify the exact cause) and ignoring the number of times we were not able to precisely identify that the cause was the root cause. The latter is calculated by counting all the times that cause was involved in an error (unambiguously or not).
### 3.2 Survey with API consumers
We challenge the 11 derived causes by testing them outside the scope of the system under study. To this end, we survey API consumers that have experience with problems related to API integration. We asked them for each cause whether they have experienced a problem. Furthermore, we allow them to name additional causes to capture the ones we may have missed.
The survey contains five main parts: 1) the process of integration to understand how the API consumer obtains the knowledge to implement the API correctly, 2) API fault prevention to identify areas of improvements for the API provider, which suggest current challenges face by the API consumer, 3) API error handling practices employed by API consumers and the challenges they face while doing so, 4) the fault detection mechanisms in place, and the areas the API consumer sees to improve and why this is not in place, and 5) the API consumer’s idea of what causes faults and related problems to occur.
The target audience of this survey is developers that have experience in API integration for an application that is used in production. To understand the participants in terms of experience we ask them about their years of experience in both software development and Web API integration. We exclude participants without API integration experience as they do not fit our target audience.
In order to learn the most about API problems we ask the participants to consider the API they worked with, which they consider to be the most complex and give them suggestions as to what kind of metrics they can use to determine this. These include: offered features and functionality, number of required or optional parameters and the number of possible error scenarios.
In addition, we ask them to answer the questions based on their experience, instead of what they believe is happening or is the ideal situation. For instance, we would like the participants to report their experience of what causes API errors to occur, and not what they think causes these errors in general.
We pre-tested the survey with five participants to make sure the questions are understandable and to remove possible ambiguities. The participants were asked to read the questions aloud as well as what they were thinking when answering the questions. This helped us understand the participants’ reasoning and identify problematic situations.
We posted the survey on the following programming communities: Code Ranch’s Web Services forum, Hackernews and Reddit’s subreddits programming (815,000 subscribers), Webdev (160,000 subscribers), API (600 subscribers) and WebAPIs (235 subscribers). Although the number of subscribers for the first two subreddits is high, the topics are very general, so the expected number of responses from these is relatively low compared to the more specific forums.
To increase the response rate, we additionally resorted to non-programming specific media and personal contacts. The survey was shared with the general public on Twitter by two colleagues; one with primarily academic followers (2500) and the other with a mix of academics and practitioners (4600 followers). In total, the posts were retweeted 25 times. On LinkedIn our post was viewed approximately 1000 times and was shared by two connections. Three companies in industry were contacted via personal contacts of which one was Adyen, the company under study. Lastly, the first author reached out to personal contacts that match the target audience.
The survey has been online for three weeks and a total of 40 qualified participants out of 70 who answered at least 1 question. We decided to consider partial responses in the results as well, but only those participants that answered questions that are not background related; 11 out of the 40 participants provided partial responses. The survey can be found in our online appendix [4].
### 3.3 Characterization of Survey Participants
On average, the respondents have over 10 years of development experience and 5 years of API integration experience. 13 of the developers were individually responsible for the API integration and 27 worked in a team of two or more developers.
95% of the respondents answered the survey based on an application that they worked on in a professional setting. The remaining 5% used an API in a hobby project, which however was used in production. According to 28% of the participants, the API they consume can be considered complex; 22% of them consider the API not complex, and 50% were neutral. 13 APIs used by the participants were data management related. For instance, providing data about products and orders, and managing financial and account data. Payment related APIs were considered 6 times. Even though many respondents are from Adyen, a payments company, only 3 of the respondents considered an payment related API. Other APIs that the participants integrated with are used for authentication, ecommerce, project management, geocoding and notifications, such as SMS services.
We observed inputs that (1) do not match a predefined list of API consumer, and the API provider and the third party stakeholder (FC-16, FC-36). In practice, invalid user input (FC-15, FC-33, FC-34, FC-37, FC-45, FC-63, FC-64), (3) do not expiry month, IBAN, credit card (FC-03, FC-09, FC-17, FC-21, FC-38, FC-61), as well as billing information, such as city, state, country, and street of the buyer (FC-04, FC-07, FC-05, FC-08).
Expired request data. Expired request data faults occur when the request is not handled in time. This occurs when the request contains a timestamp that defines a timeframe that the server has to handle the request (FC-19, FC-67). In Adyen’s case, a timestamp is generated when a shopper starts a transaction. When the request comes in, the system checks whether the start of the transaction is not too far into the past. If a shopper takes too much time an expired request data fault translates to an error being returned.
Invalid request data. Invalid request data faults are caused by input that cannot be handled by the API. There is a multitude of different reasons for such a fault to occur. We observe rounding problems, e.g., passing value 72.20 instead of 72.21 (FC-01, FC-68), functionality not available for that combination, e.g., chosen bank does not support recurring payments (FC-13, FC-54, FC-55, FC-66), invalid information, e.g., merchant does not exist (FC-41, FC-43, FC-47, FC-51), bad encoding, e.g., wrong URL encoding (FC-14), bad format or data outside a list of acceptable values, e.g., amount should be greater than zero (FC-20, FC-29, FC-30, FC-31, FC-32), and using test data into production environment, e.g., use testing payment reference in production (FC-44). This is similar to the mistake made by the end user causing an invalid user input fault, however, in this case, caused by the API consumer.
Invalid user input. Invalid user input regards requests that fail because an end user supplied input that cannot be used to complete the intended action. The invalid information is forwarded by the API consumer to the API. There are multiple types of input invalidity. We observed inputs that (1) do not match a pre-defined list of expected values or ranges, e.g., invalid country code, and month should be between 1 and 12 (FC-06, FC-22, FC-23, FC-35), (2) do not match the expected type or format, e.g., year should be an integer value (FC-15, FC-33, FC-34, FC-37, FC-45, FC-61), as well as billing information, such as city, state, country, and street of the buyer (FC-04, FC-07, FC-05, FC-08).
Invalid user input. Invalid user input regards requests that fail because an end user supplied input that cannot be used to complete the intended action. The invalid information is forwarded by the API consumer to the API. There are multiple types of input invalidity. We observed inputs that (1) do not match a pre-defined list of expected values or ranges, e.g., invalid country code, and month should be between 1 and 12 (FC-06, FC-22, FC-23, FC-35), (2) do not match the expected type or format, e.g., year should be an integer value (FC-15, FC-33, FC-34, FC-37, FC-45, FC-61), as well as billing information, such as city, state, country, and street of the buyer (FC-04, FC-07, FC-05, FC-08).
Expired request data. Expired request data faults occur when the request is not handled in time. This occurs when the request contains a timestamp that defines a timeframe that the server has to handle the request (FC-19, FC-67). In Adyen’s case, a timestamp is generated when a shopper starts a transaction. When the request comes in, the system checks whether the start of the transaction is not too far into the past. If a shopper takes too much time an expired request data fault translates to an error being returned.
Invalid request data. Invalid request data faults are caused by input that cannot be handled by the API. There is a multitude of different reasons for such a fault to occur. We observe rounding problems, e.g., passing value 72.20 instead of 72.21 (FC-01, FC-68), functionality not available for that combination, e.g., chosen bank does not support recurring payments (FC-13, FC-54, FC-55, FC-66), invalid information, e.g., merchant does not exist (FC-41, FC-43, FC-47, FC-51), bad encoding, e.g., wrong URL encoding (FC-14), bad format or data outside a list of acceptable values, e.g., amount should be greater than zero (FC-20, FC-29, FC-30, FC-31, FC-32), and using test data into production environment, e.g., use testing payment reference in production (FC-44). This is similar to the mistake made by the end user causing an invalid user input fault, however, in this case, caused by the API consumer.
Missing request data. Missing request data faults are similar to invalid request data faults. However, in this case the API consumer neglects to send in information that is required for the intended action. Also in this case we decided to distinguish between invalid and missing request data. We reason that the mistake of not supplying required information is of a different nature than making
<table>
<thead>
<tr>
<th>Stakeholder</th>
<th>Cause</th>
<th>Explanation</th>
<th>Fault Cases</th>
</tr>
</thead>
<tbody>
<tr>
<td>End user</td>
<td>Invalid user input</td>
<td>A fault introduced by invalid input by the end user of the application</td>
<td>FC6, FC15, FC16, FC19, FC22, FC23, FC33, FC34, FC35, FC36, FC37, FC45, FC63, FC64</td>
</tr>
<tr>
<td>End user</td>
<td>Missing user input</td>
<td>A fault introduced by missing input by the end user of the application</td>
<td>FC3, FC4, FC5, FC7, FC8, FC9, FC17, FC21, FC38, FC61</td>
</tr>
<tr>
<td>End user</td>
<td>Expired request data</td>
<td>The input data was no longer valid at the moment of processing</td>
<td>FC-19, FC67</td>
</tr>
<tr>
<td>API consumer</td>
<td>Invalid request data</td>
<td>A fault introduced by invalid data caused by the API consumer</td>
<td>FC1, FC13, FC14, FC20, FC29, FC30, FC31, FC32, FC41, FC43, FC44, FC47, FC51, FC54, FC55, FC66, FC68</td>
</tr>
<tr>
<td>API consumer</td>
<td>Missing request data</td>
<td>A fault introduced by missing data caused by the API consumer</td>
<td>FC10, FC25, FC27, FC28, FC39, FC46, FC48, FC52, FC58, FC59, FC60, FC65</td>
</tr>
<tr>
<td>API consumer</td>
<td>Insufficient permissions</td>
<td>Not enough rights to perform the intended request</td>
<td>FC40, FC49, FC50</td>
</tr>
<tr>
<td>API consumer</td>
<td>Double processing</td>
<td>The request was already processed by the API</td>
<td>FC11, FC18, FC69</td>
</tr>
<tr>
<td>API consumer</td>
<td>Configuration</td>
<td>A fault caused by missing/incorrect API settings</td>
<td>FC26, FC53</td>
</tr>
<tr>
<td>API consumer</td>
<td>Missing server data</td>
<td>The API does not have the requested resource</td>
<td>FC56, FC57</td>
</tr>
<tr>
<td>API provider</td>
<td>Internal</td>
<td>An internal fault caused by the API</td>
<td>FC2, FC12, FC62</td>
</tr>
<tr>
<td>Third party</td>
<td>Third party</td>
<td>A fault caused by a third party</td>
<td>FC24, FC42</td>
</tr>
</tbody>
</table>
Table 1: The 11 causes of API faults, their related stakeholder, and fault cases (FC) assigned to the cause.
Faults in API integration can be grouped in 11 causes: invalid user input, missing user input, expired request data, invalid request data, missing request data, insufficient permissions, double processing, configuration, missing server data, internal, and third party.
**4.2 RQ2. What is the prevalence of these fault types, and how many API consumers are impacted by them?**
In Table 2, we show the number of unique faults that occur in each of the 11 causes found during manual analysis. As aforementioned, due to ambiguity we are not able to present the exact percentage of errors and impacted consumers. For this reason, we show the estimated percentage of corresponding API error responses and estimated percentage of impacted consumers for each cause. In four causes of faults no ambiguity was present, hence the exact percentages are given instead of a range. Note that the total percentages for the lower and upper bound do not add up to 100% due to the estimation in the total number of errors, and to the fact that the same consumer may generate different faults.
In addition, in Figure 4, we show the perceptions of survey participants’ on the impact of each cause. We observe that: (1) Internal and third party related problems, caused by the API provider and third parties, are experienced as most impactful on production applications; (2) Problems originating from the end user, such as invalid user input and missing user input, have a relative small impact on the applications using the API; and (3) Interestingly, double processing related problems seem to have either no impact, or relatively much impact compared to the other causes.
4.3 RQ. What are the current practices and challenges to avoid and reduce the impact of problems caused by faults in API integration?
To understand how API consumers obtain the knowledge necessary to integrate with an API we asked them how often they used different information sources. Official API documentation is by far used the most. 74% of the respondents indicated to be using this source of information often or very often. Only 10% did not use official API documentation when integrating with the API they selected during the survey. Code examples are second most used with 44% of the participants using them often or very often. About one-third of the participants use them sometimes. Questions and answer websites are used never or rarely by 42% of the participants, while the number of participants that uses this information source very often is relatively low with 10%. The API provider support team is used the least with only 18% of the participants using this source often or very often.
In addition to the four proposed information sources the participants mentioned other sources of information. Four participants mentioned that they used a trial and error approach on the API to
Table 2: The number of faults per cause grouped by stakeholder, and the estimated percentage range of errors and impacted API consumers. The percentages are based on 2.43 million API errors and 1,464 impacted API consumers. Note that the percentages do not add up 100%.
<table>
<thead>
<tr>
<th>Cause</th>
<th>Cases (N=69)</th>
<th>Consumers (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Lower bound</td>
<td>Upper bound</td>
</tr>
<tr>
<td>Invalid user input</td>
<td>13</td>
<td>6.5 6.6</td>
</tr>
<tr>
<td>Missing user input</td>
<td>10</td>
<td>0.7 5.4</td>
</tr>
<tr>
<td>Expired request data</td>
<td>2</td>
<td>0.0 0.5</td>
</tr>
<tr>
<td>Internal error (n=21)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Third party error (n=14)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Configuration (n=21)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Double processing (n=14)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Missing server data</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Expired request data</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Invalid request data</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Insufficient permissions</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Missing request data</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Invalid user input</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Missing user input</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Figure 4: The impact of API related problems per cause as experienced by the survey participants.
For the end user, we see the input to be the largest cause of faults. 23 of the 25 faults are caused by invalid or missing input, collectively causing 7.2% to 12% of the errors. Invalid user input does not only result in more unique faults than missing user input, it also impacts more API consumers, 33.3% to 34.8% compared to 11.5% to 24.8%. Expired request data sent in by the end user causes two different faults, causing an impact in 2.0% to 15.8% of our consumers.
The request data causes the most faults for the API consumer, similar to the end user. Invalid request data results in 17 of the 39 unique faults caused by the API consumer. Faults in this category impact the most consumers for this stakeholder, namely between 23.9% and 62.3%. This corresponds to between 350 and 912 API consumers. Missing request data, good for 12 faults, has an impact on fewer consumers (between 20.2% and 24.0%), but does however yield more erroneous API responses. Interestingly, only 0.1% insufficient permissions related errors caused by 3 faults impact 9.5% of the API consumers. Double processing related error in comparison are also caused by 3 faults, but occurred 36.0% of the time corresponding to 875,000 errors for 12.3% of the consumers. Two configuration faults cause more than 400,000 errors (16.7%) for 19.9% to 21.4% of the consumers. This is similar to the missing request data, with the difference that this cause has 12 unique faults. Finally, 1.5% missing server data fault related error responses are given back to the API consumer, which is a relatively small amount compared to the other causes for this stakeholder. The number of impacted consumers, however, is similar to other causes.
The API provider and third party stakeholder both experience errors in one category each, internal faults and third party faults respectively. The number of unique faults caused by these stakeholders is small compared to the end user and API consumer. Third party faults however impact more API consumers, which is estimated to be between 319 and 682, or 21.8% and 46.6%.
In addition, to the four proposed information sources the participants mentioned other sources of information. Four participants mentioned that they used a trial and error approach on the API to
discover what is possible and what is not. Three respondents had access to the API’s source code or used the schema definition of the web service to understand the workings of the API. Finally, two participants used the source code of existing external libraries that wrap the API to understand how to use the API.
When it comes to preventing problems that they experienced with the API, 13 (of a total of 18) mentioned the documentation should be improved. Common implementation scenarios could help prevent problems, instead of only stating the different options for API calls. The restrictions of calls and parameters should be more clearly documented. The API provider should identify the most common API mistakes and describe how to prevent them. In addition, more details on error codes should be given and the edge cases should be highlighted and better explained. Two participants mentioned the need of an API status page to inform the API consumer of any outages. On call support for any issues was a suggested improvement by two more participants. The participants suggested both more informative error messages as well as a categorization of errors based on their similarities. Furthermore, the respondents mentioned the importance of an upgrade policy of the API and the usefulness of more code examples to illustrate the different API calls. Lastly, one participant suggests the API provider to set up a testing environment that is capable of returning all possible API calls. This allows the API consumer to properly test and handle these responses.
A subset of the participants (n = 15) elaborated on the challenges they face in error handling. One of the main difficulties is understanding the impact of API errors. Three impact perspectives were mentioned: an implementation perspective, business perspective and end user perspective. Not knowing the details and impact of an error makes it difficult from an implementation perspective to know what the request did and did not do. A participant exemplified: “You send a batch of 20 objects to be saved, but an error gets thrown. However, you don’t know if none of them was saved or all of them but one.” From a business perspective it is experienced as difficult to understand the business impact of the error. The error may explain that a parameter is invalid, but the consequences of this remain unclear. Finally, communicate errors to the end user is also experienced a challenge: “Translating the messages to something actionable by the end user.”
Another challenge faced in handling errors is the appropriate way to recover. Difficulties experienced include insufficient clarity and documentation about the right way to recover from a given error: “Often errors have no clear recovery option or even worse, do not clearly indicate what’s wrong.” Handling errors is difficult when the different flows the application should take given the API response are not clear. This is even more difficult when multiple related API calls are subsequently made and can fail with different errors.
The survey participants (n = 29) also apply different strategies to detect problems in their integration. The end user detects problems in the application related to the API integration for 23 respondents. Log analysis is second most effective in detecting problems with 19 respondents. Monitoring dashboards have detected issues for 13 respondents and both alerts, such as SMS or email, and API integration tests worked for 9 respondents. Five respondents had additional mechanisms in place, among which are “continuous live smoketesting”, “manual tests in production”, and monitoring API tools that can detect downtime and schedule API test cases, such as Runscope Radar.
**RQ3:** API consumers most often use official API documentation to implement an API correctly, followed by code examples. The challenges of preventing problems from occurring are the lack of implementation details, insufficient guidance on certain aspects of the integration, insufficient understanding of the impact of problems, and missing guidance on how to recover from errors.
## 5 DISCUSSION
In this section, we provide developers with recommendations that we derive based on our findings (Section 5.1). Finally, we discuss the possible threats to the validity of this work and actions we took to mitigate them (Section 5.2).
### 5.1 Recommendations
We observed that a great challenge for both API providers and consumers is indeed the documentation; providers need to keep it up-to-date, while consumers need to understand it. The same challenge has been observed by Robillard et al [17], where authors propose API documentation to have clear intent, code examples, matching APIs with scenarios, discuss the penetrability of the API, and to have a clear format and presentation. Our findings suggest that an important feature of documentation is regarding the possible errors an API may return.
We therefore suggest documentation to clearly state which error codes can be returned by the API and in what circumstances it can happen. The API provider should enrich API error responses with actionable information. An error type allows for generic error handling for groups of errors, a handling action indicates the right action for the API consumer to take to deal with the error, and a user message can inform the end user of the system about the error and actions to proceed. In addition, API providers should also make explicit which errors are ‘retriable’, i.e., where users may try again, and which cases users have no way of recovering from the error.
As recovering from errors is a fundamental part of the API consumer’s logic, we suggest API providers to offer easy-to-use test environments for integrations, where consumers can exercise not only the happy paths, but also the recovering paths. API consumers, on the other hand, should make sure that their application handles all error codes that are returned by the provider.
Finally, error messages are commonly logged by the API provider. Such logs are vital for future inspection and debugging. We suggest API developers to provide consumers with their logs. Toolmakers should step in and build dashboards that provide live insights about the consumers’ API usage and, more specifically, about their errors.
### 5.2 Threats to validity
In this section, we discuss the possible limitations of this work and our approach to mitigate them. We distinguish between the internal and external validity of our results.
Internal validity. Internal validity is concerned with how consistent the result is in itself. Factors that cannot be attributed to our technique, which can have an influence on the results, are a potential threat to validity: (1) The causes were derived manually and could therefore have been subject to bias or misinterpretation. To reduce this threat we worked together closely with the Adyen development and technical support team to avoid misunderstandings. (2) To discover possible multiple explanations of a fault, we analyzed the error messages for several API consumers. However, it is possible that a fault remained undiscovered because it occurred infrequently. This has a possible impact on our findings. Similarly, we filtered the data for analysis based on 10 impacted API consumers or more. The filtered data could be explained by faults that would alter the distribution of faults over the causes. For instance, internal faults could occur more often in the data that was filtered out, therefore posing a potential threat to validity.
External validity. External validity is concerned with the representativeness of the results outside the scope of the research data: (1) We used API error log data from the Adyen’s platform to determine the fault causes and provide insights into the frequency and impacted consumers of these faults. Since these results are applicable to Adyen only, we cannot generalize these results to faults in other APIs. To reduce this threat we verified the completeness of the fault causes by surveying API consumers. (2) An arbitrary window of 28 days of API error logs was selected for fault analysis and categorization. A different 28 day window could however have resulted in a different set of faults, and a different number of occurrences and impacted consumers. It would be useful to replicate the analysis based on a different time window to investigate the impact on the results. (3) We only obtained 40 survey responses, of which 11 were partial responses. This sample is insufficient to generalize results about integration, detection, handling and prevent practices, and future work would be required for such generalization.
6 RELATED WORK
Wittern et al. [27] identified three challenges for developers calling Web APIs and argue in favor of corresponding research opportunities to support API consumers: 1) API consumers have no control over the API and the service behind it, both of which may change, in contrast to a traditional local library. 2) The validity of the Web API request, in terms of URL, payload and parameters, is unknown until runtime. When using a local library the compiler can check whether the call conforms to the library’s API interface. Efforts to solve this challenge can help to reduce faults in the following categories we identified: invalid user input and invalid request data. 3) The distributed nature of the API connection comes with a set of issues concerning availability, latency and asynchrony. A different architecture or additional logic may be required to handle these issues.
Suter and Wittern [23] use API usage logs from 10 APIs to infer specifications based on API URLs and parameters using classification techniques to tag and detect parameters. The conclusion is that inferring web API descriptions is a difficult problem that is limited mostly by incomplete or noisy input data. Sohan et al. [20] apply a similar approach where API requests and responses are used to generate documentation. Using actual requests and responses the tool is able to include examples in addition to the documentation. The authors identified undocumented fields in 5 out of 25 API actions for which they generated documentation. However, in this work the precision of the generated documentation is not validated and compared to a ground truth making it difficult to see the usefulness of the proposed generator.
Bermbach and Wittern [5] performed a geo-distributed benchmark to assess the quality of Web APIs, in terms of performance and availability. The authors find a great variety in quality between different APIs. They make suggestions on how API providers can become aware of these problems by monitoring, and can mitigate them by suggesting architectural styles. This work discusses an angle of API related problems which we were not able to cover, as our work only considers API requests for which API consumers received an API response. We do however cover third party unavailability as this results into third party errors for the API consumer.
Wittern et al. [26] attempt to detect errors by statically checking API requests in JavaScript to overcome the fact that traditional compile-time errors are not available for developers consuming APIs. Their static checker aims to check whether the API requests in the code conform to the specifications that were made using the Open API specification. The authors report a 87.9% precision for payload data and a 99.9% precision on query parameter consistency checking.
A vast amount of research has been conducted in the field of traditional offline APIs, some of which can be relevant to the Web APIs as well. Robillard et al. [16] provide a survey on automated property inference for APIs. The authors state that using APIs can be challenging due to hidden assumptions and requirements, which is also found in this work. Robillard et al [15, 17] also investigated the obstacles of learning traditional offline APIs by surveying developers at Microsoft. Similar to our results, Robillard found most respondents use official documentation to learn APIs with code samples as the second most used source of information.
The learnability of an API can be affected by the overall usability of the API itself. Stylos et al. [22] find that if API providers take the effort to refactor their APIs to make them more usable this can help reduce the errors that could occur due to incorrect usage of the API. One such example shown by Ellis et al. [6] is the refactoring of the factory pattern in an API to the usage of the constructor directly. More recently, Stylos and Myers [12] have suggested that API usability techniques are not limited to the world of offline APIs, but are applicable to the world of web APIs as well.
The evolution of an API has an impact on the API clients as well. Linares-Vásquez et al. [10] have shown that breaking changes in Android APIs can have a negative impact on the rating of an Android app. Sawant et al. [19] conducted a study of 25,567 Java projects to show how deprecation of an API feature can impact an API client. Robbes et al. [14] study the ripple effect of API evolution in the entire SmallTalk ecosystem and show that deprecation of a single API artifact can have a large ranging impact on the ecosystem.
In the case of web APIs, evolution of an API can have a major impact too. Espinha et al. [8] explored the state of Web API evolution practices and the impact on the software of the respective API consumers. The impact of API changes on the clients’ source code was found to depend on the breadth of the API changes and the quality of the clients’ architectural design. Suggestions for API
providers include not changing too often, keeping usage data of different features and doing blackout tests, which involves disabling old versions for a short time to remind developers that changes in the API are coming. In other work, Espinha et al. [7] developed a tool to understand the runtime topology of APIs in terms of usage of different versions by different users. Wang et al. [25] study the specific case of the evolution of 11 REST APIs, where they collected questions and answers from Stack Overflow that concern the changing API elements and how API clients should deal with evolution. Li et al. [9] identified 6 new challenges when it comes to dealing with web API evolution as opposed to traditional API evolution. This understanding can be useful for maintenance purposes where the impact of changes can be evaluated and predicted.
Venkatesh et al. [24] mention that to help the integration process one should understand the challenges that are encountered by client developers. The authors base their analysis on developer forums and Stack Overflow by mining the questions and answers related to 32 Web APIs. They find that the top five topics per Web API category contribute to over 50% of the questions in that category. The findings imply that API providers can optimize their learning resources based on the dominant topics.
7 CONCLUSION
API errors can indicate significant problems for API consumers. In the system under study over 60,000 API error responses are returned every day, causing the potential number of problems and their impact on API consumer applications to be enormous. Practitioners have written a variety of best practice guides and blog posts on API design and error handling, however to our knowledge no research had been conducted on what type of API errors occur in practice and what their impact is.
Our results show that (1) faults in API integration can be grouped in 11 causes: invalid user input, missing user input, expired request data, invalid request data, missing request data, insufficient permissions, double processing, configuration, missing server data, internal and third party. Each cause can be contributed to one of the four API integration stakeholders: end user, API consumer, API provider, and third parties; (2) most faults can be attributed to the invalid or missing request data, and most API consumers seem to be impacted by faults caused by invalid request data and third party integration; and (3) API consumers most often use official API documentation to implement an API correctly, followed by code examples. The challenges of preventing problems from occurring are the lack of implementation details, insufficient guidance on certain aspects of the integration and insights in problems and changes, insufficient understanding of the impact of problems, missing guidance on how to recover and a lack of details on the origin of errors.
Our findings indicate that the integration between API providers and consumers is still far from ideal. We hope this work motivates researchers to further explore the domain of faults in Web API integration. Furthermore, we hope that API providers use our findings to optimize their APIs to enable better integration, and that API consumers use our ideas to reduce the impact that API errors may have on their applications.
REFERENCES
|
{"Source-Url": "https://pure.tudelft.nl/portal/files/42667586/mainwfonts.pdf", "len_cl100k_base": 11245, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35064, "total-output-tokens": 13575, "length": "2e13", "weborganizer": {"__label__adult": 0.00029158592224121094, "__label__art_design": 0.00035071372985839844, "__label__crime_law": 0.00024020671844482425, "__label__education_jobs": 0.000774383544921875, "__label__entertainment": 5.078315734863281e-05, "__label__fashion_beauty": 0.00011265277862548828, "__label__finance_business": 0.0002605915069580078, "__label__food_dining": 0.0002294778823852539, "__label__games": 0.0003688335418701172, "__label__hardware": 0.0003571510314941406, "__label__health": 0.0002779960632324219, "__label__history": 0.00016117095947265625, "__label__home_hobbies": 4.202127456665039e-05, "__label__industrial": 0.00017654895782470703, "__label__literature": 0.0001926422119140625, "__label__politics": 0.00016748905181884766, "__label__religion": 0.00029587745666503906, "__label__science_tech": 0.004665374755859375, "__label__social_life": 7.12275505065918e-05, "__label__software": 0.006427764892578125, "__label__software_dev": 0.98388671875, "__label__sports_fitness": 0.00015854835510253906, "__label__transportation": 0.0002377033233642578, "__label__travel": 0.00013637542724609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59436, 0.03834]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59436, 0.08376]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59436, 0.90463]], "google_gemma-3-12b-it_contains_pii": [[0, 885, false], [885, 5329, null], [5329, 11070, null], [11070, 16606, null], [16606, 22964, null], [22964, 30207, null], [30207, 31283, null], [31283, 37231, null], [37231, 43757, null], [43757, 50940, null], [50940, 59436, null]], "google_gemma-3-12b-it_is_public_document": [[0, 885, true], [885, 5329, null], [5329, 11070, null], [11070, 16606, null], [16606, 22964, null], [22964, 30207, null], [30207, 31283, null], [31283, 37231, null], [37231, 43757, null], [43757, 50940, null], [50940, 59436, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59436, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59436, null]], "pdf_page_numbers": [[0, 885, 1], [885, 5329, 2], [5329, 11070, 3], [11070, 16606, 4], [16606, 22964, 5], [22964, 30207, 6], [30207, 31283, 7], [31283, 37231, 8], [37231, 43757, 9], [43757, 50940, 10], [50940, 59436, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59436, 0.16854]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
638fe798b64c7562d530d9c639a05d033ec08df8
|
ASP-Based Declarative Process Mining
Francesco Chiariello\textsuperscript{1}, Fabrizio Maria Maggi\textsuperscript{2}, Fabio Patrizi\textsuperscript{1}
\textsuperscript{1} DIAG - Sapienza University of Rome, Italy
\textsuperscript{2} KRDB - Free University of Bozen-Bolzano, Italy
chiariello@diag.uniroma1.it, maggi@inf.unibz.it, patrizi@diag.uniroma1.it
Abstract
We put forward Answer Set Programming (ASP) as a solution approach for three classical problems in Declarative Process Mining: Log Generation, Query Checking, and Conformance Checking. These problems correspond to different ways of analyzing business processes under execution, starting from sequences of recorded events, a.k.a. event logs. We tackle them in their data-aware variant, i.e., by considering events that carry a payload (set of attribute-value pairs), in addition to the performed activity, specifying processes declaratively with an extension of linear-time temporal logic over finite traces ($\text{LTL}_f$). The data-aware setting is significantly more challenging than the control-flow one: Query Checking is still open, while the existing approaches for the other two problems do not scale well. The contributions of the work include an ASP encoding schema for the three problems, their solution, and experiments showing the feasibility of the approach.
Introduction
Process Mining (PM) for Business Process Management (BPM) is a research area aimed at discovering common patterns in Business Processes (BP)\textsuperscript{(van der Aalst, 2016)}. The analysis starts from event logs, i.e., sets of traces that record the events associated with process instance executions, and typically assumes a process model, which may be taken as input, manipulated as an intermediate structure, or produced in output. Events describe process activities at different levels of details. In the simplest perspective, here referred to as control-flow-only, events model atomic activity performed by a process instance at some time point; in the most complex scenario, typically referred to as multi-perspective, events also carry a payload including a timestamp and activity data.
Processes can be specified prescriptively, i.e., as models, such as Petri Nets, that generate traces, or declaratively, i.e., through logical formulas representing the constraints that traces must satisfy in order to comply with the process. This is the approach we adopt here. Specifically, we take a (untimed) data-aware perspective where events include the activity and set of attribute-value pairs, the payload.
In Declarative PM, the de-facto standard for expressing process properties is DECLARE\textsuperscript{(van der Aalst, Pesic, and Schonenberg, 2009)}
a temporal logic consisting in a set of template formulas of the Linear-time Temporal Logic over finite traces ($\text{LTL}_f$)\textsuperscript{(De Giacomo and Vardi, 2013)}
here, we use a strictly more expressive extension, which we call\textit{local}\textsuperscript{LT L}_f, i.e., $\text{LTL}_f$. This logic features a simple automata-based machinery that facilitates its manipulation, while retaining the ability to express virtually all the properties of interest in declarative PM. Specifically, $\text{LTL}_f$ subsumes DECLARE and even its multi-perspective variant MP-DECLARE\textsuperscript{(Burattin, Maggi, and Sperduti, 2016)}
without timestamps and correlation conditions (i.e., conditions that relate the attributes of some event to those of other events), but does not subsume full MP-DECLARE. Observe that since MP-DECLARE does not subsume $\text{LTL}_f$ either, the two logics are incomparable.
Our goal is to devise techniques for three classical problems in Declarative PM: Event Log Generation\textsuperscript{(Skydanienko et al., 2018)}, i.e., generating an event log consistent with a declarative model; Query Checking\textsuperscript{(Raim et al., 2014)}, i.e., discovering hidden temporal properties in an event log; and Conformance Checking\textsuperscript{(Burattin, Maggi, and Sperduti, 2016)}, i.e., checking whether the traces of an event log conform to a process model. The main challenge is dealing with data: in the data-aware framework, Query Checking is still open, while existing tools for the other two problems do not scale well.
We put forward Answer Set Programming (ASP\textsuperscript{(Niemelä, 1999)}) as an effective solution approach. ASP natively provides data-manipulation functionalities which allow for formalizing data-aware constraints and has experienced over the last years a dramatic improvement in solution performance, thus results in a natural and promising candidate approach for addressing the problems of our interest. We show how such problems can be conveniently modeled as ASP programs, thus solved with any solver. Using the state-of-the-art solver Clingo\textsuperscript{(Gebser et al., 2019)}, we experimentally compare our approach against existing ones for Log Generation and Conformance Checking, and show effectiveness of the approach for Query Checking in a data-aware set-
ing. Besides providing an actual solution technique, ASP facilitates reuse of specifications: the ASP encodings we propose here, indeed, differ in very few, although important, details. Previous related work include (Wieczorek, Jastrzab, and Unold 2020), where ASP is used to infer a finite-state automaton that accepts (resp. rejects) traces from a positive (negative) input set. This can be seen as a form of Declarative Process Discovery, i.e., the problem of obtaining a (declarative) process specification, which is complementary to the problems we address here. Our approach is similar, in that we use automata to model temporal properties. However, we propose a different automata encoding and show the effectiveness of the approach on three different problems. Another related paper is (Heljanko and Niemelä 2003), which shows how ASP can be used to check a Petri Net against an LTL specification, up to a bounded time horizon. Differently from our work, it: (i) deals with LTL over infinite, as opposed to finite, runs; (ii) adopts a prescriptive, as opposed to declarative, approach; and (iii) does not deal with data in events. From a broader perspective, we finally observe that while we deal with a set of specific problems, the work paves the way for ASP to become a general effective approach to Declarative PM.
The Framework
An activity (signature) is an expression of the form $A(a_1, \ldots, a_{n_A})$, where $A$ is the activity name and each $a_i$ is an attribute name. We call $n_A$ the arity of $A$. The attribute names of an activity are all distinct, but different activities may contain attributes with matching names. We assume a finite set $Act$ of activities, all with distinct names; thus, activities can be identified by their name, instead of by the whole tuple. Every attribute (name) $a$ of an activity $A$ is associated with a type $D_A(a)$, i.e., the set of values that can be assigned to $a$ when the activity is executed. For simplicity, we assume that all domains are equipped with the standard relations $<,\leq,=,\geq,>$. All results can be immediately adapted if some relations are absent in some domain.
An event is the execution of an activity (at some time) and is formally captured by an expression of the form $e = A(v_1, \ldots, v_{n_A})$, where $A \in Act$ is an activity name and $v_i \in D_A(a_i)$. The properties of interest in this work concern (log) traces, formally defined as finite sequences of events $\tau = e_1 \cdots e_n$, with $e_i = A_i(v_1, \ldots, v_{n_A})$. Traces model process executions, i.e., the sequences of activities performed by a process instance. A finite collection of executions into a set $L$ of traces is called an event log.
L-LTL$_f$
We adopt a declarative approach to process modeling, meaning that processes are specified through a set of constraints over their executions, i.e., over the traces they produce. The formal language we use to express properties of traces is a variant of the Linear-time Logic over finite traces, LTL$_f$ (De Giacomo and Vardi 2013), adapted to deal with the data attributes of activities. We call such variant Linear-time Logic with local conditions over finite traces, or local LTL$_f$ for short, and denote it as L-LTL$_f$.
Given a finite set of activities $Act$, the formulas $\varphi$ of L-LTL$_f$ over $Act$ are inductively defined as follows:
$$\varphi = \text{true} \mid A \mid a \circ a' \mid a \circ v \mid \neg \varphi \mid \varphi \land \varphi \mid X \varphi \mid \varphi U \varphi,$$
where: $a$ and $a'$ are attribute names from some activity in Act, $v \in D_A(a)$, for some $A \in Act$, $\circ$ is an operator from $\{<,\leq,=,\geq,>\}$, and $A$ is an activity name from Act. Formulas of the form $\text{true}$, $A$, $a \circ a'$, and $a \circ v$ are called atomic; formulas not containing the operators $X$ and $U$ are called event formulas.
The logic is interpreted over positions of finite traces. Formula $\text{true}$ holds at every position; $A$ checks whether activity $A$ occurs in the trace at the given position; $a \circ a'$ (resp. $a \circ v$) compares the value assigned to attribute $a$ with that of attribute $a'$ (resp. with that of value $v$), at the given position; boolean operators combine formulas as usual; the next operator $X \varphi$ checks whether $\varphi$ holds in the suffix starting at the next position; finally, the until operator $\varphi U \varphi'$ checks whether $\varphi'$ is satisfied at some position $k$, and whether $\varphi$ holds in all positions that precede $k$, up to the given position.
Formally, we define by induction when a trace $\tau = e_1 \cdots e_n$ satisfies an L-LTL$_f$ formula $\varphi$ at position $1 \leq i \leq n$, written $\tau, i \models \varphi$, as follows:
- $\tau, i \models \text{true}$;
- $\tau, i \models A$ iff $e_i = A(v_1, \ldots, v_{n_A})$;
- $\tau, i \models a \circ a'$ iff for $e_i = A_i(v_1, \ldots, v_{n_A})$ and $A_i(a_1, \ldots, a_{n_A})$ the signature of $A_i$, it is the case that, for some $j$ and $k$, $a = a_j$, $a' = a_k$, and $v_j \circ v_k$;
- $\tau, i \models a \circ v$ iff for $e_i = A_i(v_1, \ldots, v_{n_A})$ and $A_i(a_1, \ldots, a_{n_A})$ the signature of $A_i$, it is the case that, for some $j$, $a = a_j$ and $v_j \circ v$;
- $\tau, i \models \varphi_1 \land \varphi_2$ iff $\tau, i \models \varphi_1$ and $\tau, i \models \varphi_2$;
- $\tau, i \models \neg \varphi$ iff $\tau, i \not\models \varphi$;
- $\tau, i \models X \varphi$ iff $i < n$ and $\tau, i + 1 \models \varphi$;
- $\tau, i \models \varphi_1 U \varphi_2$ iff there exists $j \leq n$ s.t. $\tau, j \models \varphi_2$ and for every $1 \leq k \leq j - 1$, it is the case that $\tau, k \models \varphi_1$.
Notice that while, in general, the satisfaction of an L-LTL$_f$ formula $\varphi$ at some position $i$ of $\tau$ depends on the whole trace, and precisely on the suffix of $\tau$ starting at position $i$, event formulas depend only on the event at $i$.
As in standard LTL$_f$, $X$ denotes the strong next operator (which requires the existence of a next event where the inner formula is evaluated), while $U$ denotes the strong until operator (which requires the right-hand formula to eventually hold, forcing the left-hand formula to hold in all intermediate events). The following are standard abbreviations: $\varphi_1 \lor \varphi_2 \equiv \neg (\neg \varphi_1 \land \neg \varphi_2)$; $\varphi_1 \rightarrow \varphi_2 \equiv \neg \varphi_1 \lor \varphi_2$; $F \varphi = \text{true} U \varphi$ (eventually $\varphi$); and $G \varphi = \neg F \neg \varphi$ (globally, or always, $\varphi$).
Through L-LTL$_f$ one can express properties of process traces that involve not only the process control-flow but also the manipulated data.
Figure 1: Automaton for the Response constraint.
**Example 1** The $L$-$LTL_f$ formula $\varphi = G(\text{a} \rightarrow \text{Fb})$, a so-called Response constraint, says that whenever activity $a$ occurs, it must be eventually followed by activity $b$. A possible data-aware variant of $\varphi$ is the formula $\varphi' = G((\text{a} \land n < 5) \rightarrow \text{Fb})$, which says that whenever activity $a$ occurs with attribute $n$ less than 5, it must be followed by activity $b$.
Formulas of $LTL_f$, thus $L$-$LTL_f$, have the useful property of being fully characterized by finite-state, possibly nondeterministic, automata. Specifically, for every $L$-$LTL_f$ formula $\varphi$ there exists a finite-state automaton (FSA) $A_\varphi$ that accepts all and only the traces that satisfy $\varphi$ (De Giacomo and Vardi 2013). Such automata are standard FSA with transitions labelled by event formulas. For a $(\text{De Giacomo and Vardi} 2013)$. Such automata are standard FSA with transitions labelled by event formulas. For a fixed set of activities $Act$, let $\Gamma_{Act}$ be the set of event formulas over $Act$. An automaton $A$ over a set of activities $Act$ is a tuple $A = \langle Q, q_0, \rho, F \rangle$, where:
- $Q$ is a finite set of states;
- $q_0 \in Q$ is the automaton initial state;
- $\delta \subseteq Q \times \Gamma_{Act} \times Q$ is the automaton transition relation;
- $F \subseteq Q$ is the set of automaton final states.
Without loss of generality, we assume that formulas labeling transitions are conjunctions of literals. It is immediate to show that every FSA can be rewritten in this way.
A run of an FSA $A$ on a trace $\tau = e_1 \cdots e_n$ (over $Act$) is a sequence of states $\rho = q_0 \cdots q_n$ s.t. for all $0 \leq i \leq n - 1$ there exists a transition $(q_i, \gamma, q_{i+1}) \in \delta$ s.t. $\tau, i + 1 \models \gamma$. A trace $\tau$ over $Act$ is accepted by $A$ if it induces a run of $A$ that ends in a final state. Notice that satisfaction of $\gamma$, this being an event formula, can be established by looking at each event $e_{i+1}$ at a time, while disregarding the rest of the trace; thus, in order to construct the induced run $\rho$, one can proceed in an online fashion, as the next event arrives, by simply triggering, at every step, a transition outgoing from $q_i$ whose label is satisfied by the event.
**Example 2** Consider again the formulas $\varphi$ and $\varphi'$ shown above, and the (parametric) automaton depicted in Fig 1. It is easy to see that for $\varphi_1 = \text{a}$, $\varphi_2 = \text{b}$, $\varphi_3 = \neg \text{a}$, $\varphi_4 = \neg \text{b}$, the resulting automaton accepts all and only the traces that satisfy $\varphi$, as well as that for $\varphi_1 = \text{a} \land n < 5$, $\varphi_2 = \text{b}$, $\varphi_3 = \neg (\text{a} \land n < 5)$, $\varphi_4 = \neg \text{b}$, the obtained automaton accepts all and only the traces that satisfy $\varphi'$.
The details about the construction of $A_\varphi$ from $\varphi$ are not in the scope of this work, and we refer the interested reader to (De Giacomo and Vardi 2013) for more information; we rely on the results therein. We observe that while the automaton construction is time-exponential in the worst-case, wrt the size of the input formula $\varphi$, tools exist, such as Lydia, which exhibit efficient performance in practice; this, combined with the fact that the specifications of practical interest are typically small, makes the approaches based on automata construction usually feasible in practice. We can now formalize the problems addressed in this paper.
**Event Log Generation.** Given a set $\Phi$ of $L$-$LTL_f$ formulas over a set of activities $Act$ and a positive integer $t$, return a trace $\tau$ over $Act$ of length $t$ s.t., for every formula $\varphi \in \Phi$, it is the case that $\tau \models \varphi$. In words, the problem amounts to producing a trace of length $t$ over $Act$ that satisfies all the input constraints in $\Phi$. A more general version of the problem requires to generate a log $L$ of $n$ traces of fixed length $t$ satisfying the constraints. For simplicity, we consider the first formulation.
**Query Checking.** Query Checking takes as input formulas from the extension of $L$-$LTL_f$ with activity variables, defined as follows:
$$\varphi = \text{true} \lor \emptyset \lor A \lor a \circ a' \lor a \circ v \lor \neg \varphi \lor \varphi \land \varphi \lor X \varphi \lor \varphi U \varphi,$$
where symbols starting with “$\omega$” are activity variables and the other symbols are as in $L$-$LTL_f$ (given $Act$).
Given an $L$-$LTL_f$ formula with activity variables, by assigning an activity (from $Act$) to every variable, we obtain a “regular” $L$-$LTL_f$ formula. Formally, for an $L$-$LTL_f$ formula $\varphi$ (over $Act$), containing a (possibly empty) set of activity variables $Vars_\varphi$, an assignment to $Vars_\varphi$ is a total function $\nu : Vars_\varphi \rightarrow Act$. Given $\varphi$ and an assignment $\nu$ to its activity variables, $\varphi[\nu]$ denotes the (regular) $L$-$LTL_f$ formula obtained by replacing, in $\varphi$, every variable symbol $\omega$ with an activity name from $Act$. Observe that if $Vars_\varphi = \emptyset$ there exists only one assignment $\nu$ and $\varphi = \varphi[\nu]$. Given a trace $\tau$, since $\varphi[\nu]$ is a regular $L$-$LTL_f$ formula, we can check whether $\tau \models \varphi[\nu]$.
An instance of Query Checking consists in a log $L$ and an $L$-$LTL_f$ formula $\varphi$ with activity variables $Vars_\varphi$; a solution is a set $\Lambda$ of assignments to $Vars_\varphi$ s.t. for every assignment $\nu \in \Lambda$ and every trace $\tau \in L$, it holds that $\tau \models \varphi[\nu]$.
In words, query checking requires to find a set $\Lambda$ of assignments $\nu$, each transforming the input formula $\varphi$ into an $L$-$LTL_f$ formula $\varphi[\nu]$ satisfied by all the traces of the input log $L$. Observe that $\varphi$ variables can only span over activities.
**Conformance Checking.** Given a trace $\tau$ and a set $\Phi$ of $L$-$LTL_f$ formulas, both over the same set of activities $Act$, check whether, for all formulas $\varphi \in \Phi$, $\tau \models \varphi$. The problem can also be defined in a more general form, where $\tau$ is replaced by a log $L$ of traces over $Act$ and the task requires to check whether for all the traces $\tau$ of $L$ and all $\varphi \in \Phi$, it holds that $\tau \models \varphi$.
**Answer Set Programming (ASP)**
An ASP program consists in a set of rules which define predicates and impose relationships among them. The task of an ASP solver is that of finding a finite model of the program, i.e., an interpretation of the predicates that satisfies
---
1github.com/whitemech/lydia/releases/tag/v0.1.1
the program rules. ASP rules are written in a fragment of (function-free) First-order Logic (FOL) extended with a special negation-as-failure (NAF) operator (in addition to classical negation) which allows for distinguishing facts that are false from facts that are unknown. The presence of this operator, combined with the classical FOL negation, has a huge impact on the programs one can write and the way models are found. Here, we do not discuss these details, referring the interested reader to (Gelfond and Lifschitz 1988; Niemelä 1999). For our purposes, it will be sufficient restricting to the class of rules with the NAF operator as the only available negation operator (that is, disallowing classical negation).
Syntax
The basic constructs of ASP programs are: 1. constants, identified by strings starting with a lower-case letter; 2. variables, identified by strings starting with an upper-case letter; 3. terms, i.e., constants or variables; 4. atoms, i.e., expressions of the form \( p(t_1, \ldots, t_n) \), where \( p \) is a predicate, identified by a string, and each \( t_i \) is a term. A predicate \( p \) is said to have arity \( n \) if it occurs in an expression of the form \( p(t_1, \ldots, t_n) \). An atom containing only constant terms is said to be ground.
ASP rules are obtained by combining the basic elements through boolean operators and the NAF operator. In this work, we use rules of the following form:
\[
a \leftarrow t_1, \ldots, t_n, \neg t_{n+1}, \ldots, \neg t_m
\]
where \( a \) and each \( t_i \) are atoms \( p(t_1, \ldots, t_n) \), \( \neg \) denotes the NAF operator, and every variable occurring in the rule also occurs in some atom \( t_1, \ldots, t_n \). The left-hand side is called the rule’s head and is optional. When the head is absent, the rule is called an integrity constraint. The right-hand side is called the body and can be left empty, in which case the \( \neg \) symbol is omitted and the rule is called a fact.
Semantics
Intuitively, a model of an ASP program \( P \) is a set of ground atoms that satisfies all program rules. In general, many models exist. Among these, only those that are minimal wrt set inclusion and that contain a ground atom only “if needed”, i.e., if it occurs as the head of a ground rule, are taken as so-called minimal models. Among these, only those that are minimal wrt set inclusion. Intuitively, a model is a set of ground atoms that satisfies all program rules. In general, many models exist. Among these, only those that are minimal wrt set inclusion and that contain a ground atom only “if needed”, i.e., if it occurs as the head of a ground rule, are taken as so-called minimal models. Among these, only those that are minimal wrt set inclusion.
An interpretation \( I \) of a program \( P \) is a set of ground atoms \( p(c_1, \ldots, c_n) \), where \( p \) is a predicate of arity \( n \) occurring in \( P \) and \( c_1, \ldots, c_n \) are constants from the Herbrand universe of \( P \). Given a positive (i.e., without occurrences of \( \neg \)) program \( P \), an interpretation \( I \) is a model of \( P \) if, for every ground rule, \( a \leftarrow l_1, \ldots, l_n \) in \( G(P) \), whenever \( l_i \in I \) for \( i = 1, \ldots, l_n \), it holds that \( a \in I \). An answer set of \( P \) is a model \( I \) that is minimal wrt set inclusion.
The semantics of general programs is obtained as a reduction to positive programs. Namely, the reduct of a ground program \( G(P) \) wrt an interpretation \( I \) is the positive ground program \( G(P)^I \) obtained by:
- deleting all the rules
\[
a \leftarrow l_1, \ldots, l_n, \neg l_{n+1}, \ldots, \neg l_m
\]
of \( G(P) \) s.t. \( l_i \in I \) for some \( i \in \{n + 1, \ldots, m\} \);
- replacing all the remaining rules
\[
a \leftarrow l_1, \ldots, l_n, \neg l_{n+1}, \ldots, \neg l_m
\]
with \( a \leftarrow l_1, \ldots, l_n \).
Intuitively, the first transformation removes a rule, as already satisfied by \( I \); the second transformation removes the so-called negative body of the rule, because it is satisfied. As it can be easily seen, the resulting program \( G(P)^I \) does not mention the \( \neg \) operator. The interpretation \( I \) is an answer set of \( P \) if it is an answer set of \( G(P)^I \).
In this work, we do not discuss the algorithms to compute the answer sets of a program, but focus on how the problems of our interest can be encoded in ASP and then solved by an ASP solver, in such a way that the returned Answer Sets represent the solution to our problems. This is the focus of the next section. For the experiments, we use the state-of-the-art solver Clingo.
ASP for Declarative Process Mining
We encode Log Generation, Conformance Checking, and Query Checking into ASP programs. For every LTL\(_f\) formula \( \varphi \) we deal with, we assume available the corresponding automaton \( A_\varphi \). The three programs share some common parts, such as the automata and the traces, which are modeled through suitable predicates and ASP rules. Each encoding re-uses some of these parts, possibly customized, together with additional fragments used to model problem-specific features.
Activities are captured by the unary predicate \( act(A) \), where \( A \) is the activity name. In the presence of data, activity signatures are modeled by the binary predicate \( has\_attr(A, N) \), where \( A \) is the activity name and \( N \) is the attribute name. Attributes may be typed by stating the set of values they can take, through predicate \( val(N, V) \), where \( N \) is the attribute name and \( V \) one of its possible values. A trace is modeled by the binary predicate \( trace(A, T) \), where \( A \) is the activity and \( T \) the time point where it occurs. Time points come from predicate \( time(T) \), which contains the values \( \{0, \ldots, \ell\} \), for \( \ell \) the trace length. The trace is defined on time points from \( 0 \) to \( \ell - 1 \). In the presence of data, activity attributes are paired with values through predicate \( has\_val(N, V, T) \), where \( N \) is the attribute name, \( V \) the assigned value, and \( T \) the time point. Notice that the association is based on the time point (exactly one activity is performed at one time point). Simple integrity constraints are used to ensure that the mentioned attributes belong in fact
to the activity and that the assigned value comes from the corresponding type.
Automata are encoded with predicates $init(S)$, $acc(S)$, $trans(S, F, S')$, and $hold(F, T)$. The first and the second one model the initial state and the accepting states of the automaton, the third one models the existence of a transition from $S$ to $S'$ under the event formula represented by integer $F$, and the last one models satisfaction of (event) formula $F$ at time point $T$. In the presence of multiple LTL$_f$ formulas, each automaton is identified by a unique integer value and an additional parameter is added to the above predicates to refer to the various automata.
**Example 3** The ASP encoding of the automaton for the LTL$_f$ formula $G(a \rightarrow Fb)$, shown in Fig. 7 for $\varphi_1 = a$, $\varphi_2 = b$, $\varphi_3 = \neg a$, $\varphi_4 = \neg b$, is as follows:
\[
\begin{align*}
init(1, s0). \\
acc(1, s0). \\
trans(1, s0, 1, s1). \\
hold(1, 1, T) &\leftarrow trace(a, T). \\
trans(1, s1, 2, s0). \\
hold(1, 2, T) &\leftarrow trace(b, T). \\
trans(1, s0, 3, s0). \\
hold(1, 3, T) &\leftarrow \neg hold(1, 1, T), time(T). \\
trans(1, s1, 4, s1). \\
hold(1, 4, T) &\leftarrow trace(A, T), activity(A), A \neq b.
\end{align*}
\]
where $a$ and $b$ are activities and each formula $\varphi_i$ ($i = 1, \ldots, 4$) is identified by index $i$ in the encoding.
In a data-aware setting, conditions on data can be simply added to the rules for holds. For example the following rule:
\[
\begin{align*}
hold(1, 1, T) &\leftarrow trace(a, T), has_val(number, V, T), V < 5.
\end{align*}
\]
expresses the fact that the event formula $\varphi_1$ holds at time $T$ if activity $a$ occurs at time $T$ in the trace, with a value less than 5 assigned to its attribute number.
To capture satisfaction of an LTL$_f$ formula $\varphi$ by a trace $\tau$, we model the execution of the automaton $\mathcal{A}_\varphi$ on $\tau$. To this end, we introduce predicate $state(I, S, T)$, which expresses the fact that automaton (with index $I$) is in state $S$ at time $T$. Since the automaton is nondeterministic in general, it can be in many states at time point $T$ (except for the initial one). The rules defining $state$ are the following:
\[
\begin{align*}
state(I, S, 0) &\leftarrow init(I, S). \\
state(I, S', T) &\leftarrow state(I, S, T - 1), \\
trans(I, S, F, S'), hold(I, F, T - 1).
\end{align*}
\]
The first one says that at time point 0 every automaton $I$ is in its respective initial state. The second one says that the current state of automaton $I$ at time point $T$ is $S'$ whenever the automaton is in state $S$ at previous time point $T - 1$, the automaton contains a transition from $S$ to $S'$ under some event formula with index $F$ and the formula holds at time $T - 1$ in the trace.
Finally, the fact that a trace is accepted by all automata, i.e., that the trace satisfies the corresponding formulas, is stated by requiring that, for each automaton, at least one of the final states be accepting ($tlength(T)$ denotes the length $T$ of the trace):
\[
\{
state(I, S, T) : \text{not } acc(I, S), tlength(T)\} = 0.
\]
Next, we use these fragments to describe the ASP encodings for the problems of interest. For lack of space, we discuss only the main rules.
**Event Log Generation** The encoding schema of Event Log Generation is as follows:
1. Activities, attributes, attribute types, and trace length are provided as input and formalized as discussed above.
2. For each input LTL$_f$ constraint $\varphi$, the corresponding automaton $\mathcal{A}_{\varphi}$ is generated and modeled as discussed, using a unique integer value to identify it.
3. Suitable integrity constraints are defined to ensure that: each time point in the trace has exactly one activity; every attribute is assigned exactly one value; and the attributes assigned at a given time point actually belong to the activity occurring at that time point.
4. Finally, predicate $state$ is defined as above and it is required that every automaton ends up in at least one final state at the last time point.
5. Predicates $trace$ and $has_val$ contain the solution, i.e., they model a sequence of activities whose attributes have an assigned value, which satisfies all the input constraints.
**Query Checking** The ASP specification of query checking is analogous to that of Log Generation except for the following. Firstly, the problem takes as input a set of fully specified traces. This is dealt with in a simple way, by adding a parameter to predicate $trace$ representing the (unique) identifier of the trace and, consequently, by adding such parameter to all the predicates that depend on $trace$ (e.g., $has_val$, $hold$, $state$). Secondly, the input LTL$_f$ formulas contain activity variables. To deal with them, additional predicates $var(V)$ and $assgnmt(V, W)$ are introduced to account for, respectively, variables $V$ and assignments of value $W$ to variable $V$. Besides this, the automata $\mathcal{A}_{\varphi}$ associated with the formulas are obtained by treating activity variables as if they were activity symbols (without affecting the construction, which does not consider the semantics of such objects), thus obtaining automata whose transitions are labelled by event formulas, possibly containing activity variables instead of activity symbols. Such formulas become regular event formulas once values are assigned to variables and can thus be evaluated on the (events of the) input trace. Formally, this requires a slightly different definition of predicate $hold$, which must now take $assgnmt$ into account. To see how this is done, consider the formula $\varphi = G((?A1 \land \text{number} < 5) \rightarrow F ?A2)$. The corresponding automaton is the same as that of Fig. 1, where $\varphi_1 = ?A1 \land \text{number} < 5$, $\varphi_2 = ?A2$, $\varphi_3 = \neg \varphi_1$, and $\varphi_4 = \neg \varphi_2$. For formula $\varphi_1$, we have the following definition of predicate $hold$:
\[
\begin{align*}
hold(1, 1, J, T) &\leftarrow trace(J, A, T), assgnmt(varA1, A), \\
has_val(J, \text{integer}, V, T), V < 5.
\end{align*}
\]
The parameter $J$ stands for the trace identifier, as discussed above. The above rule generalizes the corresponding one in Log Generation in the presence of activity variable $\varA$. As it can be seen, in order to evaluate formula $\varphi_1$ (second parameter in $\text{hold}$) of automaton 1 (first parameter), such variable (modeled as $\text{varA}$) must be instantiated first, through predicate $\text{assgnmt}$. Observe that once all variables are assigned a value, the whole formula $\varphi$ becomes variable-free, and the corresponding automaton is a regular automaton. The returned extensions of $\text{assgnmt}$ and $\text{has_val}$ represent, together, the problem solution.
Conformance Checking Conformance Checking can be seen as a special case of Query Checking with a single input trace and where all input formulas are variable-free. In this case, the problem amounts to simply checking whether the whole specification is consistent, which is the case if and only if the input trace, together with the assignments to the respective activity attributes, satisfy the input formulas.
We close the section by observing how these problems provide a clear example of how the declarative approach allows for specification reuse. All the specifications, indeed, share the main rules (for trace, automaton, etc.) and are easily obtained as slight variants of each other, possibly varying the (guessed) predicates representing the solution.
Experiments
In this section, we provide both a comparison with state-of-the-art tools for Log Generation and Conformance Checking, based on multi-perspective declarative models, and an estimate of scalability for our query checking tool, for which, instead, no competitors exist. The state-of-the-art tool used for Log Generation is the one presented in Skydanienko et al. (2018), which is based on Alloy and tailored for MP-Declare; our results show that our ASP implementation for Log Generation scales much better than that and, at the same time, supports a more expressive data-aware rule language. As to Conformance Checking, we considered the state-of-the-art tool Declare Analyzer (Burattin, Maggi, and Sperduti 2016); we obtained comparable execution times but Declare Analyzer is specifically tailored for Declare and optimized to check conformance wrt Declare rules only, while our tool is more general in this respect. The experiments have been carried out on a standard laptop Dell XPS 15 with an intel i7 processor and 16GB of RAM. All execution times have been averaged over 3 runs. Source code, declarative models and event logs used in the experiments are available at https://github.com/fracchiariello/process-mining-ASP.
Log Generation
For testing the Log Generation tools, we have used 8 synthetic models and 8 models derived from real life logs. The experiments with synthetic models allowed us to test scalability of the tools in a controlled environment and over models with specific characteristics. The experiments with real models have been used to test the tools in real environments.
For the experiments with synthetic models, we built 8 reference models containing 3, 5, 7, and 10 constraints with and without data conditions. Each model was obtained from the previous one by adding new constraints and preserving those already present. Times are in ms.
The first and second blocks of Table 1 show the execution times for the ASP-based log generator, respectively with and without data conditions; the third and fourth blocks show the results obtained with the Alloy log generator, with and without data. Times refer to the generation of logs with 10000 traces (of length from 10 to 30). Consistent results are obtained also on additional experiments for logs of size between 100 and 5000, not reported here for space reasons.
The results obtained with models containing data conditions show that the ASP-based tool scales very well, requiring less than 2 sec in the worst case. This occurs when a model with 10 constraints is used to generate 10000 traces of length 30. As expected, the execution time increases linearly when the length of the traces in the generated logs increases. The number of constraints in the declarative model also affects the tool performance but with a lower impact.
Without data conditions the results are similar but, as expected, the execution time is lower and increases less quickly when the complexity of the model and of the generated log increases. In the worst case (a model with 10 constraints used to generate 10000 traces of length 30), the execution time is lower than 1 sec.
The results obtained with the Alloy-based tool show similar trends but with execution times almost 60 times higher than those obtained with the ASP-based tool.
The real life logs used in the experiments are taken from the collection available at https://data.4tu.nl/ We used
<table>
<thead>
<tr>
<th>Table 1: Log Generation (times in ms)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td>Trace len ↓</td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>15</td>
</tr>
<tr>
<td>20</td>
</tr>
<tr>
<td>25</td>
</tr>
<tr>
<td>30</td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>15</td>
</tr>
<tr>
<td>20</td>
</tr>
<tr>
<td>25</td>
</tr>
<tr>
<td>30</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>15</td>
</tr>
<tr>
<td>20</td>
</tr>
<tr>
<td>25</td>
</tr>
<tr>
<td>30</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>15</td>
</tr>
<tr>
<td>20</td>
</tr>
<tr>
<td>25</td>
</tr>
<tr>
<td>30</td>
</tr>
</tbody>
</table>
the declarative process model discovery tool presented in \cite{Maggi2018} to extract a process model using the default settings. The models in the real cases are much more complex and include a number of constraints between 10 and 49 for a minimum support of 80. The execution times needed for the Log Generation task with the ASP-based log generator and with the Alloy-based tool are shown, respectively, in the first and second block of Table 2. An asterisk indicates that for the specific model it was not possible to generate 10000 unique traces. The complexity of real life models makes even more evident the significant advantage of using the ASP-based tool with respect to the Alloy-based one. In particular, in the worst case, the ASP-based tool requires around 9 sec (to generate 10000 traces of length 30 for log PL) while the Alloy-based generator almost 4 mins.
**Conformance Checking**
Also for Conformance Checking we used synthetic and real life datasets. The former include the same declarative models as those used for Log Generation, plus synthetic logs of 1000 traces of lengths from 10 to 30. Table 3 shows the execution times for the ASP-based tool, with and without data conditions, and for the Declare Analyzer tool for synthetic datasets (times in ms). The results show that in all cases the execution times increase when the model becomes larger and the traces in the log become longer. The execution times obtained with the ASP-based tool and the Declare Analyzer are comparable for data-aware constraints, while, model constraints do not contain data conditions, the Declare Analyzer is around 5 times faster. This might be due to the use of the \texttt{#max} aggregate to compute a trace’s length, which yields performance degradations. A possible solution could be computing the trace length in advance and then provide it in the ASP encoding as a fact.
In the real life experiments, we tested the Conformance Checking tools using models obtained with the discovery tool by varying the minimum support between 60 and 90. The minimum support indicates the minimum percentage of traces in which a constraint should be fulfilled to be added to the discovered model. Clearly, a higher minimum support implies that the discovered models contain less constraints. As expected (see Table 4), the execution times decrease when the minimum support used to discover the reference models increases in size. Also in this case, the Declare Analyzer (second block in Table 4) is faster. However, the ASP-based tool also scales well (first block in Table 4) requiring in the worst case around 1min.
**Query Checking**
Since for Query Checking no competitor exists in the PM literature, we ran a set of controlled experiments to check how execution times vary under different conditions. We used the same synthetic logs used for Conformance Checking and tested 8 queries corresponding to 8 standard Declare templates, with and without data conditions. The results are shown in Table 5 (with and without data in the first and second block respectively). The execution times are comparable for different types of queries and the presence of data does not affect performance. In addition, as expected, the execution times increase when the traces in the log become longer.
**Conclusions**
We have devised an ASP-based approach to solve three classical problems from Declarative PM, namely Log Generation, Query Checking and Conformance Checking, in a data-aware setting. Our results include correct ASP-encoding schemata and an experimental evaluation against other approaches. The experimental results show that, for Log Generation, our approach drastically outperforms the state-of-the-art tool from PM. Time performance are slightly worse wrt to the existing ad-hoc Conformance Checker Declare Analyzer, which is optimized for Declare. As to Query Checking, our approach provides the first solution in a data-aware setting, a problem still open so far. We believe that,
<table>
<thead>
<tr>
<th>Constraints \ Trace len</th>
<th>Existence</th>
<th>Responded</th>
<th>Response</th>
<th>Chain</th>
<th>Response</th>
<th>Absence</th>
<th>Not Resp.</th>
<th>Not Resp.</th>
<th>Not Chain</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>521</td>
<td>736</td>
<td>534</td>
<td>503</td>
<td>566</td>
<td>783</td>
<td>602</td>
<td>385</td>
<td></td>
</tr>
<tr>
<td>15</td>
<td>704</td>
<td>1113</td>
<td>801</td>
<td>788</td>
<td>784</td>
<td>1180</td>
<td>879</td>
<td>606</td>
<td></td>
</tr>
<tr>
<td>20</td>
<td>1321</td>
<td>1675</td>
<td>1143</td>
<td>1128</td>
<td>1373</td>
<td>1821</td>
<td>1304</td>
<td>865</td>
<td></td>
</tr>
<tr>
<td>25</td>
<td>1397</td>
<td>3218</td>
<td>1528</td>
<td>1561</td>
<td>1562</td>
<td>2823</td>
<td>1807</td>
<td>1104</td>
<td></td>
</tr>
<tr>
<td>30</td>
<td>1674</td>
<td>2878</td>
<td>1824</td>
<td>1906</td>
<td>1905</td>
<td>2784</td>
<td>2028</td>
<td>1301</td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Constraints \ Trace len</th>
<th>Existence</th>
<th>Responded</th>
<th>Response</th>
<th>Chain</th>
<th>Response</th>
<th>Absence</th>
<th>Not Resp.</th>
<th>Not Resp.</th>
<th>Not Chain</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>399</td>
<td>658</td>
<td>541</td>
<td>632</td>
<td>441</td>
<td>799</td>
<td>806</td>
<td>772</td>
<td></td>
</tr>
<tr>
<td>15</td>
<td>616</td>
<td>1183</td>
<td>824</td>
<td>1057</td>
<td>595</td>
<td>1319</td>
<td>1121</td>
<td>1182</td>
<td></td>
</tr>
<tr>
<td>20</td>
<td>903</td>
<td>1778</td>
<td>1339</td>
<td>1550</td>
<td>874</td>
<td>1887</td>
<td>2127</td>
<td>2062</td>
<td></td>
</tr>
<tr>
<td>25</td>
<td>1188</td>
<td>2381</td>
<td>1724</td>
<td>2036</td>
<td>1101</td>
<td>3246</td>
<td>3200</td>
<td>2486</td>
<td></td>
</tr>
<tr>
<td>30</td>
<td>1461</td>
<td>3278</td>
<td>2066</td>
<td>2632</td>
<td>1333</td>
<td>3391</td>
<td>2766</td>
<td>2846</td>
<td></td>
</tr>
</tbody>
</table>
Table 4: Conformance Checking (times in ms)
Table 5: ASP Query Checking (times in ms)
by showing how the selected problems can be encoded and solved in ASP, we are not only offering a solution technique but, more in general, we are putting forward ASP an effective modeling paradigm for Declarative PM in a data-aware setting. For future work, we plan to extend the approach to deal with actual, non-integer, timestamps in events and to go beyond local \(LTL_f\) by investigating the introduction of across-state quantification to relate the values assigned to attributes at a given time point to those assigned at a different point.
**Acknowledgments**
Work partly supported by the ERC Advanced Grant White-Mech (No. 834228), the EU ICT-48 2020 project TAILOR (No. 952215), the Sapienza Project DRAPE, and the UNIBZ project CAT.
**References**
|
{"Source-Url": "http://export.arxiv.org/pdf/2205.01979", "len_cl100k_base": 11490, "olmocr-version": "0.1.50", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 36884, "total-output-tokens": 13561, "length": "2e13", "weborganizer": {"__label__adult": 0.0003287792205810547, "__label__art_design": 0.0005359649658203125, "__label__crime_law": 0.0005030632019042969, "__label__education_jobs": 0.0017757415771484375, "__label__entertainment": 0.00010770559310913086, "__label__fashion_beauty": 0.00020122528076171875, "__label__finance_business": 0.0009140968322753906, "__label__food_dining": 0.0004296302795410156, "__label__games": 0.0008039474487304688, "__label__hardware": 0.000888824462890625, "__label__health": 0.000518798828125, "__label__history": 0.0003349781036376953, "__label__home_hobbies": 0.00018453598022460935, "__label__industrial": 0.0011138916015625, "__label__literature": 0.0003762245178222656, "__label__politics": 0.0003380775451660156, "__label__religion": 0.0004801750183105469, "__label__science_tech": 0.154052734375, "__label__social_life": 0.00013172626495361328, "__label__software": 0.01800537109375, "__label__software_dev": 0.81689453125, "__label__sports_fitness": 0.00033283233642578125, "__label__transportation": 0.0007348060607910156, "__label__travel": 0.0001894235610961914}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47035, 0.05128]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47035, 0.3553]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47035, 0.84704]], "google_gemma-3-12b-it_contains_pii": [[0, 5071, false], [5071, 11816, null], [11816, 18667, null], [18667, 25060, null], [25060, 31203, null], [31203, 37949, null], [37949, 41940, null], [41940, 46012, null], [46012, 47035, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5071, true], [5071, 11816, null], [11816, 18667, null], [18667, 25060, null], [25060, 31203, null], [31203, 37949, null], [37949, 41940, null], [41940, 46012, null], [46012, 47035, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47035, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47035, null]], "pdf_page_numbers": [[0, 5071, 1], [5071, 11816, 2], [11816, 18667, 3], [18667, 25060, 4], [25060, 31203, 5], [31203, 37949, 6], [37949, 41940, 7], [41940, 46012, 8], [46012, 47035, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47035, 0.18182]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
782c6a7323f12dbda427c14a08373a0b6f2101a8
|
Set-Consensus Collections are Decidable
Carole Delporte-Gallet * Hugues Fauconnier *
Eli Gafni † Petr Kuznetsov §
Abstract
A natural way to measure the power of a distributed-computing model is to characterize the set of tasks that can be solved in it. In general, however, the question of whether a given task can be solved in a given model of computation is undecidable, even if we only consider the wait-free shared-memory model. In this paper, we address this question for a restricted class of models and tasks. We show that the question of whether a collection $C$ of $(j, \ell)$-set consensus tasks, for various $\ell$ (the number of processes that can invoke the task) and $j$ (the number of distinct outputs the task returns), can be used by $n$ processes to solve wait-free $k$-set consensus is decidable. Moreover, we provide a simple $O(n^2)$ decision algorithm, based on a dynamic programming solution to the Knapsack problem. We then present an adaptive wait-free set-consensus algorithm that, for each set of participants, achieves the best level of agreement that is possible to achieve using $C$. Overall, this gives us a complete characterization of a model equipped with a collection of set-consensus tasks through its set-consensus power. Therefore, the question of determining the relative power of models defined by set-consensus collections is decidable and, moreover, has an efficient solution. We conjecture that any “reasonable” shared-memory model can be characterized by its set-consensus power.
1 Introduction
A plethora of models of computation were proposed for distributed environments. The models vary in timing assumptions they make, types of failures they assume, and communication primitives they employ. It is hard to say a priori whether one model provides more power to programmer than the other. A natural way to measure this power is to characterize the set of distributed tasks that a model allows for solving. In general, however, the question of whether a given task can be solved in the popular wait-free model, i.e., tolerating asynchrony and failures of an arbitrary subset of processes, is undecidable [15].
In this paper, we address this question for a restricted class of models and tasks. We consider models in which $n$ completely asynchronous processes communicate through shared-memory but in addition can access set-consensus tasks. A $(j, \ell)$-set-consensus task solves set consensus among $\ell$ processes, i.e., the task can be accessed by up to $\ell$ processes with propose operations that take natural values as inputs and return natural values as outputs, so that the set of outputs is a
*IRIF, Université Paris-Diderot
†UCLA
‡Télécom ParisTech, corresponding author, petr.kuznetsov@telecom-paristech.fr
§The research leading to these results has received funding from the Agence Nationale de la Recherche, under grant agreement ANR-14-CE35-0010-01, project DISCMAT.
subset of inputs of size at most \( j^1 \). Set consensus is a generalization of consensus, and as well as consensus \([19]\) exhibits the property of universality: \( \ell \) processes can use \((j, \ell)\)-set consensus and read-write registers to implement \( j \) state machines, ensuring that at least one of them makes progress \([14]\). In this paper, we explore what level of agreement, and thus “degree of universality”, can be achieved using combinations of a collection of set-consensus tasks.
The special case when only one type of set consensus can be used in the implementation was resolved in \([6, 10]\): \((j, \ell)\)-set consensus can be used to implement \((k, n)\)-set consensus if and only if \( k \geq j \left\lfloor n/\ell \right\rfloor \). Indeed, by splitting \( n \) processes into groups of size \( \ell \) we trivially solve \( j \left\lfloor n/\ell \right\rfloor \)-set consensus.
Characterizing a general model in which processes communicate via an arbitrary collection \( C \) of possibly different set-consensus tasks is less trivial. For example, let \( C \) be \( \{(1, 2), (2, 5)\} \), i.e., every 2 processes in our system can solve consensus and every 5 can solve 2-set consensus. What is the best level of agreement we can achieve using \( C \) in a system of 9 processes? One can easily see that 4-set consensus can be solved: the first two pairs of processes solve consensus and the remaining 5 invoke 2-set consensus, which would give at most 4 different outputs. One can also let the groups of the first 5 and the remaining 4 each solve 2-set consensus. (In general, any two set-consensus tasks \((j_1, \ell_1)\) and \((j_2, \ell_2)\) can be used to solve \((j_1 + j_2, \ell_1 + \ell_2)\).) But could we do \((3, 9)\)-set consensus with \( C \)?
We propose a simple way to characterize the power of a set-consensus collection. By convention, let \((j_0, \ell_0)\) be \((1, 1)\), and note that \((1,1)\)-set consensus is trivially solvable. We show that a collection \( C = \{(j_0, \ell_0), (j_1, \ell_1), \ldots, (j_m, \ell_m)\} \) solves \((k, n)\)-set consensus if and only if there exist \( x_0, x_1, \ldots, x_m \in \mathbb{N} \), such that \( \sum_i \ell_ix_i \geq n \) and \( \sum_i j_ix_i \leq k \). Thus, determining the power of \( C \) is equivalent to solving a variation of the Knapsack optimization problem \([23]\), where each \( j_i \) serves as the “weight” of an element in \( C \), i.e., how much disagreement it may incur, and each \( \ell_i \) serves as its “value”, i.e., how many processes it is able to synchronize. We describe a simple \( O(n^2) \) algorithm for computing the power of \( C \) in solving set consensus among \( n \) processes using the dynamic programming approach \([3]\).
The sufficiency of the condition is immediate. Indeed, the condition implies that we can partition the set of \( n \) processes in \( r = \sum_i x_i \) groups, where for each group \( j = 0, \ldots, r \) is of size \( t_i \) and is associated to some \((s_i, t_i) \in C\), such that \( \sum_i s_i \leq k \). Now each group \( i \) can independently solve \( s_i \)-set consensus, which gives us at most \( k \) different outputs in total.
The necessity of the condition is much less trivial to derive. It required a carefully crafted simulation algorithm, showing that if a collection not satisfying the condition solves \((k, n)\)-set consensus, then \( k + 1 \) processes can solve \( k \)-set consensus, contradicting the classical wait-free set-consensus impossibility result \([4, 22, 25]\). Interestingly, the necessity of this condition holds even if we can use read-write registers in addition to the elements in \( C \).
Thus, we derive a complete characterization of models equipped with collections of set-consensus tasks. In particular, it allows us to determine the \( j \)-set-consensus number of a set-consensus collection \( C \) as the maximal number of processes that can achieve \( j \)-set consensus using \( C \) and read-write registers. Applied to arbitrary objects, this metric is a natural generalization of Herlihy’s consensus number \([19]\).
Coming back to the collection \( C = \{(1, 2), (2, 5)\} \), our characterization implies that 4-set consensus is the best level of set consensus that can be achieved by 9 processes with \( C \). Observe, however, that if only 2 processes participate, then they can use \( C \) to solve consensus, i.e., to achieve the
---
\footnote{In \([6, 10]\), notation \((\ell, j)\) was used for this object. We chose the notation with the opposite order of variables, for it is somewhat more convenient to use in collections of set-consensus tasks.}
“perfect” agreement. Applying our condition, we also see that participating sets of sizes 3 up to 5 can solve 2-set consensus, participating sets of size 6 up to 7 can solve 3-set consensus, participating sets of size 8 up to 10 can solve 4-set consensus, etc. That is, for every given participating set, we can devise an optimal set-consensus algorithm that ensures the best level of agreement achievable with $C$.
A natural question is whether we could adapt to the participation level and ensure the best possible level of agreement in any case? We show that this is possible by presenting an optimally adaptive set-consensus algorithm. Intuitively, for the currently observed participation, our algorithm employs the best algorithm and, in case the participating set grows, seamlessly relaxes the agreement guarantees by switching to a possibly less precise algorithm assuming the larger set of participants.
Our results thus imply that the question of whether one model defined by a set-consensus collection implements another model defined by a set-consensus collection is decidable and, moreover, it has an efficient solution. We believe that our characterization extends to models beyond collections of set-consensus tasks. Indeed, we conjecture that the ability of any “reasonable” (yet to be defined precisely) shared-memory system to solve set consensus, captured by its $j$-set-consensus numbers, characterizes precisely its computing power, e.g., with respect to solving tasks or implementing deterministic objects.
This work contributes to the idea that there is nothing special about consensus that set consensus cannot do. Indeed, set-consensus collections are decidable in the same way collections of consensus objects are [19]. This also complements the recent derivation of a deterministic object that precisely captures a collection of set consensuses [2], i.e., consensus is not unique in being able to characterize deterministic objects either.
Roadmap. The rest of the paper is organized as follows. In Section 2, we recall the basic model definitions and simulation tools. In Section 3, we present and prove our characterization of set-consensus collections, and describe an efficient algorithm to compute the characterizing criterion. In Section 4, we present an adaptive algorithm that achieves the optimal level of agreement for each set of active participants having access to a given set-consensus collection. We discuss related work in Section 5 and conclude in Section 6.
2 Preliminaries
In this section, we briefly state our system model, recall the notion of a distributed task, and sketch the basic simulation tools that we use in the paper.
Processes and tasks. We consider a system $\Pi$ of asynchronous processes that communicate via shared memory abstractions. We assume that process may only fail by crashing, and otherwise it must respect the algorithm it is given. A correct process never crashes. Shared abstractions we consider here include an atomic-snapshot memory [1] and a collection of distributed tasks [22]. A process invokes a task with an input value and the task returns an output value, so that the inputs and the outputs across the processes invoked the task respect the task specification and every correct process that participates decides (gets an output). More precisely, a task is defined through a set $I$ of input vectors (one input value for each process), a set $O$ of output vectors (one output value for each process), and a total relation $\Delta : I \rightarrow 2^O$ that associates each input vector with a set of possible output vectors. An input $\perp$ denotes a not participating process and an output value $\perp$ denotes an undecided process.
We assume that $\mathcal{I}$ and $\mathcal{O}$ are prefix-closed: if they contain a vector $S$, then they also contain any vector obtained by $S$ by replacing some entries with $\bot$. We stipulate that if $(I, O) \in \Delta$, then (1) if, for some $i$, $I[i] = \bot$, then $O[i] = \bot$, (2) for each $O'$, prefix of $O$, $(I, O') \in \Delta$ and, (3) for each $I'$ such that $I$ is a prefix of $I'$, there exists some $O'$ such that $O$ is a prefix of $O'$ and $(I', O')$ in $\Delta$.
An algorithm wait-free solves a task $T = (\mathcal{I}, \mathcal{O}, \Delta)$ if it ensures that in every execution in which processes start with an input vector $I \in \mathcal{I}$, every correct process decides, and all decided values form a vector $O \in \mathcal{O}$ such that $(I, O) \in \Delta$.
In the task of $k$-set consensus, input values are in a set of values $V$ $(|V| \geq k + 1)$, output values are also in $V$, and for each input vector $I$ and output vector $O$, $(I, O) \in \Delta$ if the set of non-$\bot$ values in $O$ is a subset of values in $I$ of size at most $k$. The special case of 1-set consensus is called consensus [13]. More generally, the task of $(k, \ell)$-set consensus ($k \leq \ell$) allows every subset of $\ell$ processes to solve $k$-set consensus.
Note that $k$-set consensus is an example of colorless tasks (also known as convergence tasks [7]): processes are free to use each others’ input and output values, so the task can be defined in terms of input and output sets instead of vectors. To solve a colorless task, it is sufficient to find an algorithm (a decision function) that allows just one process to decide. Indeed, if such an algorithm exists, we can simply convert it into a protocol that allows every correct process to decide: every process simply applies the decision function to the observed state of any other process and adopts the decision.
In contrast, $(\ell, k)$-set consensus is not colorless in a system of $n > \ell$ processes, as it does not allow a process to adopt the decision of another process, as the other process does not provide outputs for subsets of $\ell$ processes it does not belong to.
**Simulations tools.** An execution of a given protocol $A$ by the processes $p_1, \ldots, p_n$ can be simulated by a set of simulators $s_1, \ldots, s_\ell$ that mimic the steps of $A$ in a consistent way: for every execution $E_s$, there exists an execution $E$ of $A$ by $p_1, \ldots, p_n$ such that the sequence of states simulated for every process $p_i$ in $E_s$ is observed by $p_i$ in $E$.
A basic building block of our simulations is an agreement protocol [5,7] that can be seen as a safe part of consensus. It exports one operation propose($v$) taking $v \in V$ as a parameter and returning $w \in V$, where $V$ is a (possibly infinite) value set. When a process $p_i$ invokes propose($v$) we say that $p_i$ proposes $v$, and when the invocation returns $v'$ we say that $p_i$ decides on $v'$. Agreement ensures four properties:
(i) every decided value has been previously proposed,
(ii) no two processes decide on different values, and
(iii) if every participating process takes enough steps then eventually every correct participant decides.
Here a process is called participating if it took at least one step in the computation. In fact, the agreement protocol in [5,7] ensures that if every participating process takes at least three shared memory steps then eventually every correct participant decides. If a participating process fails in the middle of an agreement protocol, then no correct process is guaranteed to return.
A generalized version of the agreement protocol, $\ell$-agreement [6,10], relaxes safety properties of agreement by improving on the liveness side. Formally, in addition to (i) above, $\ell$-agreement ensures:
(ii') at most $\ell$ different values can be decided, and
Let \( C \)j consensus is also a solution of \((C, j)\). For brevity, we represent \( C \) as a set \( \{ (j_0, \ell_0), (j_1, \ell_1), (j_2, \ell_2), \ldots, (j_m, \ell_m) \} \) such that for each \( i = 0, \ldots, m \), the task of \((j_i, \ell_i)\)-set consensus can be solved. By convention, we assume that \((j_0, \ell_0) = (1, 1)\) is always contained in a collection \( C \): \( (1, 1) \)-set consensus is trivially solvable.
We notice that if \( C \) contains \((j_i, \ell_i)\), then \((j_i - 1, \ell_i)\) can be solved: any solution of \((j_i, \ell_i)\)-set consensus is also a solution of \((j_i - 1, \ell_i)\)-set consensus.
We show in this section that the optimal level of agreement that can be achieved by a collection of \( C \) can be defined as follows:
**Definition 1** [Agreement level] Let \( C = \{ (j_0, \ell_0), (j_1, \ell_1), \ldots, (j_m, \ell_m) \} \) be a collection of set-consensus tasks. The agreement level for \( n \) processes of \( C \), denoted \( k^C_n \), is defined:
- \( \min \sum_i \ell_i x_i \)
- under the constraints: \( \sum_i j_i x_i \geq n, x_0, \ldots, x_m \in \{ 0, \ldots, n \} \)
One can also interpret \( k^C_n \) as the lowest \( k \) for which there exists a multiset \( \{ (s_1, t_1), \ldots, (s_r, t_r) \} \) of elements in \( C \) such that \( \sum_i t_i \leq k \) and \( \sum_i s_i \geq n \).
We now can define a simple criterion to determine whether the model equipped with \( C \) allows for solving \((n, k)\)-set consensus. The criterion is sufficient, i.e., every model equipped with \( C \) that satisfies the criterion solves \((n, k)\)-set consensus, and necessary, i.e., every model equipped with \( C \) that solves \((n, k)\)-set consensus satisfies the criterion.
**Theorem 1** \((n, k)\)-set consensus can be solved using read-write registers and tasks in a set-consensus collection \( C \) if and only if \( k^C_n \leq k \).
**Proof.** Suppose that \( k^C_n \leq k \). Thus there exists a multiset \( \{ (s_1, t_1), \ldots, (s_r, t_r) \} \) of elements in \( C \) such that \( \sum_i t_i \leq k \) and \( \sum_i s_i \geq n \). We show how \( n \) processes can solve \( k \)-set consensus using \( S \). Every \( p_i, i = 1, \ldots, n \), is assigned to the element \((s_j, t_j) \in S \) such that \( \sum_{\ell=1}^{j-1} t_\ell < i \leq \sum_{\ell=1}^{j-1} t_\ell \) invokes the assigned task of \((s_j, t_j)\)-set consensus with its input and returns the corresponding output. Since \( \sum_i s_i \leq k \), the total number of outputs does not exceed \( k \).
Now suppose that \( C \) allows for solving \((k, n)\)-set consensus and let \( A \) be the corresponding algorithm. By contradiction, suppose that no multiset \( S \) satisfying the conditions above exists for \( k > k^C_n \).
\[ \text{Note that assuming that } (1, 1) \in C \text{ implies that } k^C_n \leq n. \]
Thus, for any multiset \( \{(s_1, t_1), \ldots, (s_r, t_r)\} \) of elements in \( C \) such that \( \sum_i s_i \leq k \), we have \( \sum_i t_i < n \).
We show that we then can use a simulation of \( A \) to solve \( (k, k+1) \)-set consensus using only read-write memory, contradicting the classical impossibility result \([4, 22, 25]\).
Each \( q_i \) simulates \( p_1, \ldots, p_n \) in the round-robin fashion: in every round of the simulation, \( q_i \) picks up the next simulated process \( p_\ell \) that is not currently blocked. To simulate a step of \( p_\ell \), \( q_i \) takes a snapshot of the memory to get \( p_\ell \)'s latest simulated state. Here we assume that in its position in the snapshot vector, every simulator maintains its estimate of the current simulated state of every process \( p_\ell \), so \( q_i \) computes \( p_\ell \)'s latest simulated state by choosing the most recent evaluated state of \( p_\ell \) found in the snapshot. If \( p_\ell \) is in its initial state, \( q_i \) employs the safe agreement protocol (1-agreement) to compute the input of \( p_\ell \) in the simulated run, using its own identifier \( i \) as a proposed value.
The state of \( p_\ell \) unambiguously determines the next step \( p_\ell \) is going to take in the simulation, which is either a write or snapshot operation, or an access to a \((s, t)\)-set-consensus task. In fact, a write operation by \( p_\ell \) is implicitly simulated by registering the last simulated state of \( p_\ell \) in the shared memory, so the simulators only need to explicitly simulate a snapshot operation, proposing the just read simulated system state as its outcome. In simulating an access of a \((s, t)\)-set-consensus task, the simulator proposes \( p_\ell \)'s input value as the decided value.
Different simulated operations require different agreement protocols:
- For a read operation, we use the agreement (1-agreement) algorithm \([4, 7]\).
Recall that a simulator that has started but not finished the agreement protocol for a given step may block the simulated process forever. However, since the faulty simulator may be involved in at most one agreement protocol at a time, it can block at most one simulated process.
- For an access to a \((s, t)\)-set-consensus task, \( s \)-agreement \([6, 10]\) (Section 2).
Recall that \( s \)-agreement may block forever only if \( s \) or more processes fail in the middle of its execution. When it is used to simulate an access to \((s, t)\)-set consensus, failures of \( s \) or more simulators may block \( t \) simulated processes.
Also, recall that \( s \)-agreement may return different values to different simulators (as long as there are at most \( s \) of them). To ensure that the outcome of each of the \( t \) simulated processes accessing the \((s, t)\)-set-consensus task is determined consistently by different simulators, the outcome of the the simulated step is then agreed upon using the conventional agreement (1-agreement).
The use of 1-agreement protocols for both simulated operations implies that every step is simulated consistently, the simulators agree on the next simulated state of each process in \( \{p_1, \ldots, p_n\} \). Moreover, since the proposals to these agreement protocols are coming from the recently taken snapshot of the simulated system state (in case a snapshot operation is simulated) or the value that a the simulated process must proposed based on its local state (in case an access to a \((s, t)\)-set-consensus task is simulated), the simulated states are indeed compliant with a run of \( A \).
It remains to show that at least one process in \( \{p_1, \ldots, p_n\} \) makes progress in the simulated run, assuming that at least one of the \( k + 1 \) simulators is correct. We show that in the simulated run, at least one of the simulated processes appears correct, i.e., takes sufficiently many steps.
A simulated process may stop making progress only if an agreement protocol used for simulating its step “blocks”, i.e., enters into an eternal waiting phase where live simulators are not able to
compute the new simulated state because one or more simulators stopped taking steps in the middle of the protocol.
An access of \((s,t)\)-set consensus may block in the simulation only if \(s\) or more simulators fail in the middle of the corresponding \(s\)-agreement protocol. By our assumption, for any multiset \(\{(s_1,t_1), \ldots, (s_r,t_r)\}\) of elements in \(C\), such that \(\sum_i s_i \leq k\), we have \(\sum_i t_i < n\). Note that simulating a read operation can be viewed as simulating an access to \((1,1)\)-set consensus. Therefore, \(k\) simulators can block at most \(n - 1\) simulated processes. Thus, at least one process makes progress in the simulated run and eventually decides. Assuming that the first simulator to witness a decision in the simulated run writes it in the shared memory, we derive that every correct simulator eventually decides.
Since all these values are coming from a run of an algorithm solving \((k,n)\)-set consensus, there are at most \(k\) distinct decided values. Each of the decided values is an input of some simulator. Thus, \(k + 1\) simulators read-write solve \(k\)-set-consensus—a contradiction.
### 3.2 Computing the power of set-consensus collections
Having characterized the power of a collection \(C\) to solve set-consensus, we are now faced with the question of how to compute this power.
By Theorem 4 determining the best level of agreement that can be achieved by \(C = \{(j_0, \ell_0), \ldots, (j_m, \ell_m)\}\) in a system of \(n\) processes is equivalent to finding \(\min \sum_i j_i x_i\), under the constraints: \(\sum_i \ell_i x_i \geq n\), \(x_0, x_1, \ldots, x_m \in \{0, \ldots, n\}\). This can be viewed a variation of the Knapsack decision problem [23], where we aim at minimizing the total weight of a set of items from \(C\) put in a knapsack, while maintaining a predefined minimal total value of the knapsack content. Here each \(j_i\) serves as the “weight” of an element in \(C\), i.e., how much disagreement it may incur, and each \(\ell_i\) serves as its “value”, i.e., how many processes it is able to synchronize. We use this observation to derive an algorithm to compute \(k^C_n\) in \(O(n^2)\) steps.
Note that if \(C\) contains \((j, \ell)\), then it can also be used to solve \((j, \ell - 1), (j, \ell - 2), \ldots, (j, j)\). Thus, in the following we assume that \(C\) is complete; for all \((j, \ell) \in C\) and \(j \leq x < \ell\), there exists \((j, x) \in C\). We also assume, without loss of generality, that \(C\) is lexicographically ordered: \((j, \ell) < (j', \ell')\) is defined as \((j < j') \lor (j = j') \land (\ell < \ell')\). Note that a lexicographically ordered \(C\) can be completed in \(O(n)\) steps. For example, the completion of \(C = \{(1,1), (2,3), (6,10)\}\) for \(n = 11\) would be \(\{(1,1), (2,2), (2,3), (6,6), (6,7), (6,8), (6,9), (6,10), (6,11)\}\).
We observe that for all \(r = 1, \ldots, n\), \(k^C_r = \min_{\ell_i \leq r} (j_i + k^C_{r-\ell_i})\). Thus, we can use the following simple iterative algorithm (a variation of a Knapsack solution based on dynamic programming [3]) to compute \(k^C_n\) in \(O(n^2)\) steps:
\[
\begin{align*}
k^C_0 &= 0; \\
\text{for } r = 1, \ldots, n \text{ do } & k^C_r = \min_{\ell_i \leq r} (j_i + k^C_{r-\ell_i}).
\end{align*}
\]
In each iteration \(r = 1, \ldots, n\) of the algorithm above, we only go over \(r\) checks, which gives us \(O(n^2)\) total complexity.
We can also consider a related notion of \(j\)-set-consensus number of \(C\), denoted \(m^C_j\) and defined as the maximal number of processes that can achieve \(j\)-set consensus using \(C\) and read-write registers: \(m^C_j = \max_{k^C \leq j} n\). This is a natural generalization of Herlihy’s consensus power [19]. Note that by a variation of the algorithm above we can compute \(m^C_j\) in \(O(j^2)\) steps.
4 An adaptive algorithm: reaching optimal agreement
Theorem 1 implies that, for every fixed \( n \), there exists a \( k_n^C \)-set-agreement algorithm \( ST_n^C \) (\( ST \) for static) using \( C \). We show that these algorithms can be used in an adaptive manner, so that for each set of participating processes, the best possible level of agreement can be achieved.
To understand the difficulty of finding such an adaptive algorithm, consider \( C = \{(1,1), (5,13), (9,20)\} \). For selected sizes of participating sets \( m \), the table in Figure 1 gives \( k_m^C \), and lists the elements of \( C \) used in the corresponding \( ST_m^C \).
<table>
<thead>
<tr>
<th>( m )</th>
<th>( k_m^C )</th>
<th>( ST_m^C )</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>(1,1)</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>(1,1) (1,1)</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td>(1,1) (1,1) (1,1)</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>(1,1) (1,1) (1,1) (1,1)</td>
</tr>
<tr>
<td>5 to 13</td>
<td>5</td>
<td>(5,13)</td>
</tr>
<tr>
<td>14</td>
<td>6</td>
<td>(5,13) (1,1)</td>
</tr>
<tr>
<td>15</td>
<td>7</td>
<td>(5,13) (1,1) (1,1)</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>( m )</th>
<th>( k_m^C )</th>
<th>( ST_m^C )</th>
</tr>
</thead>
<tbody>
<tr>
<td>16</td>
<td>8</td>
<td>(5,13)(1,1)(1,1)(1,1)</td>
</tr>
<tr>
<td>17</td>
<td>9</td>
<td>(5,13)(1,1)(1,1)(1,1)(1,1)</td>
</tr>
<tr>
<td></td>
<td></td>
<td>or (9,20)</td>
</tr>
<tr>
<td>18 to 20</td>
<td>9</td>
<td>(9,20)</td>
</tr>
<tr>
<td>21</td>
<td>10</td>
<td>(9,20)(1,1) or (5,13)(5,13)</td>
</tr>
<tr>
<td>22 to 26</td>
<td>10</td>
<td>(5,13) (5,13)</td>
</tr>
<tr>
<td></td>
<td></td>
<td>...</td>
</tr>
</tbody>
</table>
Figure 1: Selecting elements in \( C = \{(1,1), (5,13), (9,20)\} \) to solve \( k_m^C \)-set consensus.
If we have 16 processes, \( ST_{16}^C \) uses one instance of (5,13)-set consensus and three instances of (1,1)-set consensus to achieve \( k_{16}^C = 9 \). But if two new processes arrive we have to use (9,20)-set consensus to achieve \( k_{18}^C = 9 \). Interestingly, to achieve \( k_{22}^C = 10 \), we should abandon (9,20)-set consensus and use two instances of (5,13)-set consensus instead. In other words, we cannot simply add a set-consensus instance of the species we used before to account for the arrival of new processes. Instead, we have to introduce a new species.
We present a wait-free adaptive algorithm that ensures that if the set of participants is of size \( m \), then at most \( k_m^C \) distinct input values can be output. We call such an algorithm optimally adaptive for \( C \).
The algorithm is presented in Figure 2. The idea is the following: every process \( p \) writes its input in the shared memory, and takes a snapshot to get the current set \( P \) of participating processes and their inputs. The process then adopts the value written by the process observed in the largest participating set and computes its rank in \( P \). The chosen input is then proposed to an instance of algorithm \( ST_{|P|}^C \), where \( p \) behaves as process at position rank.
Note that since the set is derived from an atomic snapshot of the memory, the notion of the largest participating set if well-defined: the snapshots of the same size are identical. Therefore, at most \( |P| \) processes participate in \( ST_{|P|}^C \) and each of these \( |P| \) processes can only participate at a distinct position corresponding to its rank in \( P \).
**Theorem 2** Let \( C \) be a set-consensus collection, \( n \) be an integer. The algorithm in Figure 2 is optimally adaptive for \( C \).
**Proof.** We show first that every correct process eventually returns a value, and any returned value is a proposed one.
Let \( p \) and \( q \) take snapshots (Lines 2 or 11) in that order, and let \( P_p \) and \( P_q \) be, respectively, the returned participating sets. We observe first that \( P_p \subseteq P_q \). Indeed, each position in the snapshot
Shared objects:
\( R: \) snapshot object, storing pairs \((\text{value}, \text{level})\), initialized to \((\bot, \bot)\)
Local variables for process \( p \in \Pi \):
- \( r[1, \ldots, n] \): array of pairs \((\text{value}, \text{level})\)
- \( \text{prop}, v \): value
- \( \text{parts}, P \in 2^\Pi \)
- \( \text{index}: \) integer
Code for process \( p \in \Pi \) with proposal \( v_p \):
1. \( R.\text{update}(p, (v_p, 0)) \)
2. \( r[1, \ldots, n] = R.\text{snapshot}() \)
3. \( P = \text{set of processes } q \text{ such that } r[q] \neq (\bot, \bot) \)
4. \( \textbf{repeat} \)
5. \( \text{parts} := P \)
6. \( \text{rank} := \text{the rank of } p \text{ in } \text{parts} \)
7. \( k := \text{be the greatest integer such that } (−, k) \text{ is in } r \)
8. \( v := \text{be any value such that } (v, k) \text{ is in } r \)
9. \( \text{prop} := \mathcal{ST}_{|\text{parts}|}^C \text{ with value } v \text{ at position } \text{rank} \)
10. \( R.\text{update}(p, (\text{prop}, |\text{parts}|)) \)
11. \( r[1, \ldots, n] = R.\text{snapshot}() \)
12. \( P = \text{set of processes } q \text{ such that } r[q] \neq (\bot, \bot) \)
13. \( \textbf{until} \text{ parts } = P \)
14. \( \textbf{return} \text{ prop} \)
Figure 2: An optimally adaptive set-consensus algorithm.
Object \( R \) is initialized to \((\bot, \bot)\). Once, \( p \) updates \( R[p] \) with its value and participation level, the position remain non-\(\bot\) forever. Thus, if \( q \) takes its snapshot of \( R \) after \( p \), then \( P_p \), the set of processes whose positions are non-\(\bot\) in the resulting vector, is a subset of \( P_q \).
Therefore, the sets \( P \) and \( \text{parts} \) evaluated by \( p \) in Line 11 are non-decreasing with time. Since \( \mathcal{ST}_{|\text{parts}|}^C \) is wait-free, the only reason for a correct process \( p \) not to return is to find that \( \text{parts} \subseteq P \) in Line 13 infinitely often, i.e., both \( P \) and \( \text{parts} \) grow indefinitely. But the two sets are bounded by the set \( \Pi \) of all processes—a contradiction.
Furthermore, very returned value is a value decided in an instance of \( \mathcal{ST}_{|\text{parts}|}^C \). But every value proposed to algorithm \( \mathcal{ST}_{|\text{parts}|}^C \) was previously read in a non-(\(\bot, \bot\)) position of \( R \), which can only contain an input value of some process.
Hence, every correct process eventually returns a value, and any returned value is a proposed one.
Now consider a run of the algorithm in Figure 2 in which \( m \) processes participate. We say that a process \( p \) \textit{returns at level} \( t \) in this run if it outputs (in Line 14) the value \text{prop} returned by the preceding invocation of \( \mathcal{ST}_t^C \) (in Line 9). By the algorithm, if \( p \) returns at level \( t \), then the set \( \text{parts} \) of processes it witnessed participating is of size \( t \).
Let \( \ell \) be the smallest level \((1 \leq \ell \leq n)\) at which some process returns, and let \( O_\ell \) be the set of
values ever written in $R$ at level $\ell$, i.e., all values $v$, such that $(v, \ell)$ appears in $R$.
We show first that for all $\ell' > \ell$, if $R$ contains $(v', \ell')$, such that $\ell > \ell'$, in $R$. Thus, the immediately preceding snapshot taken by $q$ before this write (in Lines 2 or 11) witnessed a participating set of size $\ell'$. Hence, the snapshot of $q$ succeeds the last snapshot (of size $\ell < \ell'$) taken by any process $p$ that returned at level $\ell$. But immediately before taking its last snapshot, every such process $p$ has written $(v, \ell)$ in $R$ (Line 10) for some $v \in O_\ell$. Thus, $v' \in O_\ell$ (Lines 7 and 8).
Inductively, any subsequent process will have to adopt a value in $O_\ell$. Thus, every returned value must appear in $O_\ell$, where $\ell$ is the smallest level ($1 \leq \ell \leq n$) at which some process returns. Now we show that $|O_\ell| \leq k^C_m$.
Indeed, since all values that appear in $O_\ell$ were previously returned by the algorithm $STC_\ell$ (Line 9) and, as we observed earlier, the algorithm is used by at most $\ell$ processes, each choosing a unique position based on its rank in the corresponding snapshot of size $\ell$, there can be at most $k^C_\ell$ such values. Since at most $m$ processes participate in the considered run, we have $\ell \leq m$, and, thus, $k^C_\ell \leq k^C_m$.
Hence, in a run with participating set of size $m$, $|O_\ell| \leq k^C_m$ and, thus, at most $k^C_m$ values can be returned by the algorithm. Thus, we indeed have an optimally adaptive set-consensus algorithm using $C$. □
On unbounded concurrency. Our definitions of the agreement level and the set-consensus number of a set-consensus collection is agnostic to the size of the system: it is defined with respect to a given participation level. Our adaptive algorithm does account for the system size, as it uses atomic snapshots. But by applying the techniques designed in [18], we can easily extend our adaptive solution to the models of unbounded (but finite) concurrency.
5 Related work
The power of a set-consensus collection is grasped via a solution of the Knapsack optimization problem [23]. Our algorithm computing the power of a set-consensus collection in $O(n^2)$ steps (for a system of $n$ processes) is based the dynamic programming solution for the Knapsack problem described, e.g., in [3].
Herlihy [19] introduced the notion of consensus number of a given object type, i.e., the maximum number of processes that can solve consensus using instances of the type and read-write registers. It has been shown that $n$-process consensus objects have consensus power $n$. However, the corresponding consensus hierarchy is in general not robust, i.e., there exist object types, each of consensus number 1 which, combined together, can be used to solve 2-process consensus [24].
Borowsky and Gafni [6], and then Chaudhuri and Reiners [10] independently explored the power of having multiple instances of $(j, \ell)$-set-consensus tasks in a system of $n$ processes with respect to solving set consensus, which is a special case of the question considered in this paper. The characterization of [6, 10] is established by a a generalized BG simulation [5, 7] by Borowsky and Gafni, where instead of safe agreement protocol, a more general $j$-agreement protocol is used. Our results employ this agreement protocol to show a much more general and quite non-trivial result.
Gafni and Koutsoupias [15] and Herlihy and Rajsbaum [20] showed that wait-free solvability of tasks for 3 or more using read-write registers is an undecidable question. We show that in a special case of solving set consensus using a set-consensus collection, the question is decidable. Moreover, we give an explicit polynomial algorithm for computing the power of a set-consensus collection.
6 Concluding remarks
We believe that the ability to solve set consensus is the principal characteristics of a distributed computing model. Our conjecture is that our set-consensus numbers grasps precisely the computing power of any “reasonable” shared-memory model. An indication that the conjecture might hold is that set-agreement tasks are, in a precise sense, universal (generalizing the consensus universality [19]): using \((k, n)\)-set-consensus tasks, \(n\) processes can implement \(k\) independent sequential objects (state machines) so that at least one of them is able to make progress, i.e., to execute infinitely many commands. Other popular restriction on the model runs, such as adversaries [12] and failure detectors [8, 9] were successfully characterized via their power of solving set consensus [11, 16, 17]. Also, as well as consensus, set consensus can express deterministic objects [2].
Therefore, intuitively, we should be able to capture the behavior of a shared object, that can be accessed by different sets of processes, through a collection of set-consensus tasks, and it is very tempting to nail this intuition down.
Herlihy and Rajsbaum [21] showed how the ability of a superset-closed adversarial model to solve colorless tasks can be reduced to connectivity properties of the corresponding protocol complex, a combinatorial structure capturing executions of the model. It would be interesting to see if the properties of models defined by set-consensus collections can be studied in this vein.
References
**A An ℓ-agreement algorithm**
The algorithm (presented in Figure 3) uses two atomic snapshot objects $A$ and $B$, initialized with ⊥’s. A process writes its input in $A$ (line 15) and takes a snapshot of $A$ (line 16). Then the process writes the outcome of the snapshot in $B$ (line 17) and keeps taking snapshots of $B$ until it finds that at most $\ell - 1$ participating (i.e., having written their values in $A$) processes that have not finished the protocol, i.e., have not written their values in $B$ (Lines 18-21). Finally, the process returns the smallest value (we assume that the value set is ordered) in the smallest-size non-⊥ snapshot found in $B$ (containing the smallest number of non-⊥ values). (Recall that all snapshot outcomes are related by containment, so there indeed exists such a smallest snapshot.)
**Theorem 3** The algorithm in Figure 3 implements ℓ-agreement.
**Proof.** The validity property (i) is immediate: only the identifier of a participating process can be found in a snapshot object. The termination property (iii) of ℓ-agreement is immediate: if at most $\ell - 1$ processes that have executed line 15 fail to execute line 17 then the exit condition of the repeat-until clause in line 21 eventually holds and every correct participant terminates.
Suppose, by contradiction, that at least $\ell + 1$ different values are returned by the algorithm. Thus, at least $\ell + 1$ distinct snapshots were written in $B$ by $\ell + 1$ processes. Let $L$ be the set of processes that have written the $\ell$ smallest snapshots in $B$ in the run. The set is well-defined as all snapshots taken in $A$ are related by containment. We are going to establish a contradiction by showing that every process must return the smallest value in one of the snapshots written by the processes in $L$ and, thus, at most $\ell$ distinct inputs will be produced.
Let $p_i$ be any process that completed line 17 by writing the result of its snapshot of $A$ in $B$. Let $U$ be the set of processes that $p_i$ witnessed in $A$ and, thus, wrote to its position in $B$ in line 17.
---
Figure 3: The ℓ-agreement algorithm
If $p_i \in L$, i.e., $U$ is one of the $\ell$ smallest snapshots ever written in $B$, then $p_i$ will return the value of the smallest process in $U$ or a smaller snapshot written by some process in $L$. If $p_i \notin L$, then $U$ contains all $\ell$ distinct snapshots written by the processes in $L$. Since each process in $L$ is included in the snapshot it has written in $B$, we derive that $L \subseteq U$. Since $p_i$ returns a value only if all but at most $\ell - 1$ processes it witnessed participating have written their snapshots in $B$, at least one snapshot written by a process in $L$ is read by $p_i$ in $B$. Thus, $p_i$ outputs the value of the smallest process in the snapshot written by a process in $L$—a contradiction.
Thus, at most $\ell$ distinct values can be output and (ii)$'$ is satisfied. □
|
{"Source-Url": "http://arxiv.org/pdf/1607.05635v1.pdf", "len_cl100k_base": 11221, "olmocr-version": "0.1.48", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 51093, "total-output-tokens": 13723, "length": "2e13", "weborganizer": {"__label__adult": 0.0004303455352783203, "__label__art_design": 0.0005025863647460938, "__label__crime_law": 0.0004901885986328125, "__label__education_jobs": 0.0014667510986328125, "__label__entertainment": 0.00013077259063720703, "__label__fashion_beauty": 0.00024580955505371094, "__label__finance_business": 0.0006346702575683594, "__label__food_dining": 0.0005440711975097656, "__label__games": 0.00115966796875, "__label__hardware": 0.0025997161865234375, "__label__health": 0.0012712478637695312, "__label__history": 0.0006108283996582031, "__label__home_hobbies": 0.00022602081298828125, "__label__industrial": 0.0007944107055664062, "__label__literature": 0.0005707740783691406, "__label__politics": 0.0005245208740234375, "__label__religion": 0.0007596015930175781, "__label__science_tech": 0.352294921875, "__label__social_life": 0.00011360645294189452, "__label__software": 0.01004791259765625, "__label__software_dev": 0.623046875, "__label__sports_fitness": 0.00036215782165527344, "__label__transportation": 0.0010776519775390625, "__label__travel": 0.0002682209014892578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44873, 0.03916]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44873, 0.42041]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44873, 0.87875]], "google_gemma-3-12b-it_contains_pii": [[0, 2941, false], [2941, 7616, null], [7616, 11342, null], [11342, 15220, null], [15220, 18078, null], [18078, 22204, null], [22204, 26057, null], [26057, 29641, null], [29641, 32697, null], [32697, 36153, null], [36153, 39172, null], [39172, 41600, null], [41600, 44053, null], [44053, 44873, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2941, true], [2941, 7616, null], [7616, 11342, null], [11342, 15220, null], [15220, 18078, null], [18078, 22204, null], [22204, 26057, null], [26057, 29641, null], [29641, 32697, null], [32697, 36153, null], [36153, 39172, null], [39172, 41600, null], [41600, 44053, null], [44053, 44873, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44873, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44873, null]], "pdf_page_numbers": [[0, 2941, 1], [2941, 7616, 2], [7616, 11342, 3], [11342, 15220, 4], [15220, 18078, 5], [18078, 22204, 6], [22204, 26057, 7], [26057, 29641, 8], [29641, 32697, 9], [32697, 36153, 10], [36153, 39172, 11], [39172, 41600, 12], [41600, 44053, 13], [44053, 44873, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44873, 0.09326]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
bc9df02578265885407e9fb09bb2a5fc77fc063a
|
[REMOVED]
|
{"Source-Url": "http://www.researchgate.net/profile/Carlos_Pereira8/publication/228352491_Deraf_a_high-level_aspects_framework_for_distributed_embedded_real-time_systems_design/links/09e4150f7bf4187dd4000000.pdf", "len_cl100k_base": 10749, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 46619, "total-output-tokens": 12853, "length": "2e13", "weborganizer": {"__label__adult": 0.0003991127014160156, "__label__art_design": 0.00061798095703125, "__label__crime_law": 0.0003664493560791016, "__label__education_jobs": 0.0006151199340820312, "__label__entertainment": 7.712841033935547e-05, "__label__fashion_beauty": 0.00020766258239746096, "__label__finance_business": 0.0002562999725341797, "__label__food_dining": 0.0003452301025390625, "__label__games": 0.0008993148803710938, "__label__hardware": 0.0047760009765625, "__label__health": 0.0005154609680175781, "__label__history": 0.0003657341003417969, "__label__home_hobbies": 0.00012195110321044922, "__label__industrial": 0.0008339881896972656, "__label__literature": 0.00020647048950195312, "__label__politics": 0.0003273487091064453, "__label__religion": 0.0006108283996582031, "__label__science_tech": 0.0770263671875, "__label__social_life": 6.031990051269531e-05, "__label__software": 0.0074920654296875, "__label__software_dev": 0.90234375, "__label__sports_fitness": 0.00034737586975097656, "__label__transportation": 0.0009889602661132812, "__label__travel": 0.0002586841583251953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56263, 0.019]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56263, 0.42248]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56263, 0.90761]], "google_gemma-3-12b-it_contains_pii": [[0, 2568, false], [2568, 5659, null], [5659, 7742, null], [7742, 9650, null], [9650, 13820, null], [13820, 17477, null], [17477, 20768, null], [20768, 24293, null], [24293, 27131, null], [27131, 29112, null], [29112, 30978, null], [30978, 32866, null], [32866, 34691, null], [34691, 36704, null], [36704, 39423, null], [39423, 42695, null], [42695, 46029, null], [46029, 49290, null], [49290, 52743, null], [52743, 56263, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2568, true], [2568, 5659, null], [5659, 7742, null], [7742, 9650, null], [9650, 13820, null], [13820, 17477, null], [17477, 20768, null], [20768, 24293, null], [24293, 27131, null], [27131, 29112, null], [29112, 30978, null], [30978, 32866, null], [32866, 34691, null], [34691, 36704, null], [36704, 39423, null], [39423, 42695, null], [42695, 46029, null], [46029, 49290, null], [49290, 52743, null], [52743, 56263, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56263, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56263, null]], "pdf_page_numbers": [[0, 2568, 1], [2568, 5659, 2], [5659, 7742, 3], [7742, 9650, 4], [9650, 13820, 5], [13820, 17477, 6], [17477, 20768, 7], [20768, 24293, 8], [24293, 27131, 9], [27131, 29112, 10], [29112, 30978, 11], [30978, 32866, 12], [32866, 34691, 13], [34691, 36704, 14], [36704, 39423, 15], [39423, 42695, 16], [42695, 46029, 17], [46029, 49290, 18], [49290, 52743, 19], [52743, 56263, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56263, 0.2029]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
531cfc0609d77ae176f0f40246cb8fac65558a8b
|
[REMOVED]
|
{"Source-Url": "https://hal.science/hal-00531167/file/book1.pdf", "len_cl100k_base": 10510, "olmocr-version": "0.1.49", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 48075, "total-output-tokens": 12459, "length": "2e13", "weborganizer": {"__label__adult": 0.0003664493560791016, "__label__art_design": 0.00043082237243652344, "__label__crime_law": 0.0005812644958496094, "__label__education_jobs": 0.003078460693359375, "__label__entertainment": 0.00011807680130004884, "__label__fashion_beauty": 0.0002046823501586914, "__label__finance_business": 0.0009098052978515624, "__label__food_dining": 0.0004420280456542969, "__label__games": 0.0008730888366699219, "__label__hardware": 0.000927448272705078, "__label__health": 0.0006909370422363281, "__label__history": 0.0004584789276123047, "__label__home_hobbies": 0.0002262592315673828, "__label__industrial": 0.0012884140014648438, "__label__literature": 0.0003979206085205078, "__label__politics": 0.00036787986755371094, "__label__religion": 0.0005984306335449219, "__label__science_tech": 0.22509765625, "__label__social_life": 0.00020956993103027344, "__label__software": 0.06011962890625, "__label__software_dev": 0.70166015625, "__label__sports_fitness": 0.0003120899200439453, "__label__transportation": 0.0005192756652832031, "__label__travel": 0.0002799034118652344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47267, 0.0423]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47267, 0.54897]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47267, 0.90504]], "google_gemma-3-12b-it_contains_pii": [[0, 1093, false], [1093, 2388, null], [2388, 5303, null], [5303, 8089, null], [8089, 9336, null], [9336, 11522, null], [11522, 13545, null], [13545, 15616, null], [15616, 17574, null], [17574, 19749, null], [19749, 21791, null], [21791, 23669, null], [23669, 25567, null], [25567, 27824, null], [27824, 29852, null], [29852, 31995, null], [31995, 33544, null], [33544, 36109, null], [36109, 37762, null], [37762, 39583, null], [39583, 41853, null], [41853, 44551, null], [44551, 47267, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1093, true], [1093, 2388, null], [2388, 5303, null], [5303, 8089, null], [8089, 9336, null], [9336, 11522, null], [11522, 13545, null], [13545, 15616, null], [15616, 17574, null], [17574, 19749, null], [19749, 21791, null], [21791, 23669, null], [23669, 25567, null], [25567, 27824, null], [27824, 29852, null], [29852, 31995, null], [31995, 33544, null], [33544, 36109, null], [36109, 37762, null], [37762, 39583, null], [39583, 41853, null], [41853, 44551, null], [44551, 47267, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47267, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47267, null]], "pdf_page_numbers": [[0, 1093, 1], [1093, 2388, 2], [2388, 5303, 3], [5303, 8089, 4], [8089, 9336, 5], [9336, 11522, 6], [11522, 13545, 7], [13545, 15616, 8], [15616, 17574, 9], [17574, 19749, 10], [19749, 21791, 11], [21791, 23669, 12], [23669, 25567, 13], [25567, 27824, 14], [27824, 29852, 15], [29852, 31995, 16], [31995, 33544, 17], [33544, 36109, 18], [36109, 37762, 19], [37762, 39583, 20], [39583, 41853, 21], [41853, 44551, 22], [44551, 47267, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47267, 0.02413]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
37a4409e5a8a14df7b0ca074b2cf3925d134984e
|
Abstract
Ozone Widget Framework (OWF) is an event-based web platform for lightweight integration of widget applications. This technical report presents a formal model of OWF’s widget composition mechanism. First, we present a detailed description of Ozone’s end user composition mechanism. Then, we describe our architectural modeling approach and its value for analysis of OWF widget compositions. We go through the process of creating an architectural style to represent assemblies of Ozone widgets, reviewing modeling decision points and style alternatives.
Keywords: Ozone Widget Framework, end-user architecting, analysis, architectural model, Acme, Z.
**Contents**
1 Introduction 1
2 Ozone Widget Framework 3
3 Architectural Approach to Formal Modeling 7
4 Formal Modeling of Ozone Compositions 13
5 Future Research Directions 24
A Z Model of Ozone Compositions 26
B Ozone Acme Style Source 34
1 Introduction
Event-driven programming has been a time-proven paradigm to create programs where the computation is determined by the flow of distributed events, thus enabling loosely coupled integration. While event-driven programming paradigm itself has shifted from being used in scientific and business programming languages like PL/1 and locally operating systems in 1960s to those designed for large Internet-scale integration, such as widget frameworks [12], its traditional problems have still not been solved. A standard problem scenario is that while event-based decomposition promotes modularity and simplicity by using communication over an event-based infrastructure, it also makes it possible to create convoluted programs that cause ripple affects [6]. Another issue with event-based frameworks is the difficulty of formal verification of their behavior [5]. These issues place a greater value on the principled design of event-based systems that promotes required qualities and inhibits the undesirable ones. And, as the systems are growing to the Internet scale, designing them in a controllable manner becomes even more important because their use affects numerous organizations and social groups.
Another trend in software engineering is the shift of software development by end users who are not merely users, but developers in their own regards [2]. More and more often, users are provided not with a rigid interface with few points of customization, but with a powerful and expressive means of creating a customized software system. End-user architecting [7], a sub-discipline of end-user software engineering, deals with end-user environments that allow people to do work similar to that of software architects: compose computations from coarse-grained functional blocks to create a system with given functionality and qualities. One of the essential goals of end-user architecting is supporting end-user architects in their activities through model-based tools and techniques that have already gained respect in the software architecture community.
Frameworks in these end-user programming domains present interesting research challenges and therefore there has been a significant interest towards such research. Such systems provide end users with a visual way to combine components and wire them through an event-oriented environment. For such systems, formal representation and analysis can be beneficial, as it can help users deal with a hard-to-manage event environment. Also, design decisions for such frameworks are of interest because they promote or inhibit specific qualities during their usage. Furthermore, not all design decisions that go along designing these event frameworks are explicitly laid out, and these implicit decisions may have profound influence on the quality attributes of the system that uses the framework. It is worth making such hidden decisions explicit in order to clearly articulate their results. In this report, we discuss one such framework named Ozone Widget Framework (OWF) [10], or just Ozone, which is an open-source event-based integration framework, popular in intelligence and data analysis communities. OWF enables rapid assembly and configuration of rich, lightweight web applications (called widgets) produced by different third party contractors to provide various reports on data. OWF supports integration of such web-applications using a common publish-subscribe event model, where individual widgets can be hosted on different servers, but are integrated together on a centralized portal to provide summary views of dynamic information content.
OWF was designed to be a simple and robust end-user framework. Unlike most widget frameworks today that require writing extensive code, Ozone abstracts out unnecessary technical details
from the end users and provides a simple web front-end where end users can compose widgets and restrict communication amongst widgets. Additionally, Ozone provides APIs based on JavaScript to standardize the development, and ease the integration effort. However, this abstraction comes at a cost: it makes the underlying Ozone computation model more complicated that needs better understanding. Architecturally speaking, a major deviation from publish-subscribe style of computation comes from additional restrictions over event communications, and other abstractions that hide communication details. This aroused our interest to explore OWF’s computation model further, and we formalized the principles of composing OWF widgets to understand and document it better. In doing so, we stumbled across various design decisions of OWF – both explicit and implicit – that affect various qualities during its usage, and analyzed those decisions in their effect on qualities of OWF.
However, this modeling of OWF was not straightforward. And therefore, one of the goals of this report is to document the tradeoffs associated with formal modeling and analysis. This report describes our steps to formally model any such system, interpreting the vocabulary of the design constructs, and the design decisions that lead to particular quality attributes. Apart from providing a better understanding of the system, this exercise could be beneficial to end users in many ways: first, this could help them understand the details of low-level interaction using appropriate abstractions when required (which are at times opaque in many frameworks like OWF); and second, it could help them answer the various what-if questions for which currently they have to dig into code or just guess.
We used an architectural style written in Acme architecture description language [8] to capture the model of Ozone widget compositions; it can be used to define various domain-specific analyses. End users can use such analyses to examine the feasibility of a particular compositions, and examine them for problems at a level of abstraction that can be directly understood without detailed knowledge of the underlying technology. Also, the modeling process has provided the authors with enough insight to discuss Ozone’s design decisions and their impact of quality of this framework.
The rest of the report is organized as follows. The next section describes Ozone’s computational model from an end user’s point of view. Section 3 presents our architectural approach to modeling: why we chose it and how we tailor it to this framework. Section 4 gives our detailed steps towards creating an architectural style for OWF compositions and alternatives of the style; also, this section describes the style and an example of formal analysis based on the style. And finally, we discuss future research directions in Section 5.
2 Ozone Widget Framework
As we mentioned above, Ozone Widget Framework\(^1\) allows its users to place widgets on a web dashboard. Users of Ozone accesses this dashboard through a web browser. Widgets, technically being HTML iframes, are opened on this dashboard. Users selects a widget type to deploy (for example, a graph plotting widget), and after that a corresponding widget instance is created on the dashboard. Thus, one can create many instances of the same widget and work with them separately. In this report, the word ‘widget’ is invariably used as an instance of a widget. You can see a dashboard with four widgets in Figure 1.

The core service OWF provides to widgets is message exchange. It allows them to send and receive information from each other when they are open in the form of *messages* (or *events*). Such communication happens through *channels*. A channel is a runtime entity to which widgets can publish and subscribe. The semantics of publishing and subscribing in Ozone is similar to the general publish-subscribe architectural style \([5]\): if a widget publishes to a channel, all subscribers receive the message. There is no caching or logging of published events, so there is no way to read the “history” of messages sent to any channel. Each channel has a unique name that is used by widgets when they publish and subscribe to it. Channels tunnel only plain-text data.
From Ozone’s point of view, a widget’s subscription to a channel is a persistent aspect of the system’s state: it can be canceled only by explicitly unsubscribing (done by the widget’s code).
---
\(^1\)This report targets OWF version 6.0.2, released publicly at \([10]\).
or removing the widget (done by the user). At the same time, publishing is a one-time event: a widget executes an appropriate command, and a message is delivered. There is no preparation required for a widget before it engages in publishing as well as no obligation after it publishes. This distinction between subscribing and publishing is important for further modeling of Ozone widget compositions.
Widgets are produced and maintained by third parties. It is up to a user which widgets to deploy of his dashboard. Once a widget is downloaded by the user, its front end runs inside the user’s browser, whereas back end (if any) may be hosted on some other server. Event messaging also happens inside the user’s web browser. This approach makes it easier to assemble widgets into systems that are capable of performing complex computations.
Publishing and subscribing is a powerful mechanism of interaction, yet it is a complex one: a person who designs event-based interaction has to provide for appropriate reaction for relevant events for every widget as well as for naming of channels and protocols of event exchange. Perhaps having these considerations in mind, Ozone’s developers did not permit end users to explicitly alter what and where is published by any widget. It is up to widgets’ programmers to determine names of channels widgets subscribe to and event processing and publishing. This information is encoded in widgets’ sources and is out of users’ control unless a widget’s developers design a user interface for users to work with the mentioned details of event exchange. Moreover, event communications paths are completely opaque for users since channels have no visualization in Ozone dashboard.
### 2.1 Eventing Restrictions in Ozone
To compensate for the users’ inability to control communications, Ozone gives them a tool to limit event exchange — a restriction line\(^2\). Initially, any widget can subscribe to any channel and, consequently, receive messages from all other widgets that publish to the channel. Similarly, any widget can publish messages to any channel; the messages will be delivered to all the subscribers of this channel. Restriction lines control which widgets can talk to which. Once a user draws a restriction line between a pair of widgets, he blocks all communication between each of widgets in the pair and all the other widgets, but preserves the communication inside this pair. To permit other directions of message exchange for any of widgets in this pair, the user would have to draw another restriction line or to delete the first one.
More precisely, two distinct widgets in Ozone composition are permitted to communicate (via any channels — existing or created in the future) according to eventing lines if and only if one of two conditions holds:
- None of these two widgets is connected by the restriction line to any other widget.
- These two widgets are directly connected by the restriction line.
*Note:* a widget will always get its own messages from channels it both publishes and subscribes to no matter how restriction lines are placed.
Restriction lines are drawn by end users in a separate view. You can see a screenshot of such a view in Figure 2.
\(^2\)Starting OWF version 6, restriction lines are disabled in a default installation.
You can find the unambiguous documentation of Ozone messaging behavior and restriction lines carried out with a Z specification language model [11] in Appendix A. This Z model, while being mathematically precise and correct, does not allow for as much end-user support as an architectural model of widget compositions that is created in Sections 3 and 4. This motivates our deeper exploration of the computational model behind Ozone event system.
By deploying widgets that exchange messages and by manipulating restrictions on this messaging, users can create arbitrary dynamic compositions of widgets (also called configurations or orchestrations) that can serve a variety of computational purposes. The next section looks closer at what information is present in an Ozone composition. It is helpful to be able to reference different parts of it when discussing modeling and analyses.
### 2.2 Information in Ozone Composition
Each OWF composition is a superposition of following units of information:
1. The set of widgets deployed on the dashboard. This is a basic unit of information that is required so that subsequent ones are meaningful: it is impossible to describe what widgets publish to channels if the set of widgets is not defined.
2. The set of existing channels and publishing and subscribing relations on widgets and channels. This unit is based on how widgets are implemented because publishing and subscribing to channels is generally specified in source code.
3. Restrictions. The set of all restriction lines is the information in this unit. This information depends of how end users set up restriction lines. There is an important sub-unit of information here that actually determines which communications work and which do not:
a. The relation on widgets, “who can talk to whom”. It describes which widget is allowed
4. Actual communications in the system. This unit of information describes pairs of widgets that actually exchange events. This information can be inferred from the units 1–3. The space of all ongoing communications is split by restriction lines into two sets: public ones and private ones.
As we will see later, an ability of an OWF composition model to contain these units of information determines analyses that the model can provide.
2.3 Motivation for Formal Modeling
Formal modeling of OWF widget compositions brings the following benefits:
- Ozone is one of few representatives of event-based systems for end-user architecting. Precisely describing Ozone’s compositions is valuable to study this class of systems.
- Clarifying decisions that Ozone’s creators made and their impact on qualities of Ozone may provide insight into what are tradeoffs when designing an end-user composition environment, at least in the domain of event-based environments.
- A formal model documents principles upon which widgets are combined and facilitates the unambiguous understanding of these principles. For example, the exact rules of restriction lines’ behavior are not precisely documented and were discovered empirically by the authors.
- If a visual formal model of compositions is implemented as a view in Ozone, it can help users by explicitly showing channels and publish-subscribe relations between them and widgets.
- A formal model permits formal analysis that can help end users. For example, because of the complex logic behind restriction lines, it is presumably difficult for users to evaluate changes introduced by adding or removing a restriction. Automatic analysis can show the effects of such an action to users.
In the next section, we present our approach to modeling Ozone widget compositions.
---
3A communication is an ongoing message exchange between two widgets through a channel.
3 Architectural Approach to Formal Modeling
This section describes our approach to modeling OWF compositions through architectural representation.
3.1 Architectural Style
As described in the introduction, end-user analysts’ activity while using composition tools (and Ozone in particular) is similar to that of software architects. This fact brings us to modeling Ozone compositions with an architectural style [1] in an architecture description language (ADL) [4]. There are several specific reasons to this decision. First, Ozone compositions form a runtime architecture of an ad hoc computational system, and the component and connector model is an accepted way to represent runtime architectures [9]. Second, a style describes a vocabulary of a system’s elements and rules of combining them and unambiguously explains what a system is and what it is not. Last but not least, having a style would permit us to perform analysis on compositions to help end users in their tasks. We use Acme ADL to create an architectural style for OWF because Acme has strong support for customized analysis of architectural models and style extension.
An Acme architectural style (called family in Acme language) in the is a collection of types for modeling runtime elements of software systems. These types describe the following elements:
- Components — principal computational elements of a system. Components can contain ports.
- Ports — components’ interfaces for interaction. Ports can only be attached to roles.
- Connectors — elements that encapsulate interaction between components. Connectors can contain roles.
- Roles — responsibilities for interaction in connectors. Roles can only be attached to ports.
- Systems — configurations of components and connectors attached connected to each other through ports and roles. In this report we use the term compositions meaning actual assemblies of widgets or ADL systems that model them.
- Rules — first order logic predicates that specify what systems are considered valid. Rules can be either invariants (cannot be violated ever) or heuristics (can be violated selectively).
See Figure 3 for illustration of the mentioned ADL concepts.
Apart from providing a clear vocabulary of OWF composition elements and giving an opportunity for analysis, having an architectural style has additional benefits:
- Potential reuse of analyses in other end-user composition systems that would have the same or similar architectural style.
A style can be a basis for a more detailed model, should the need arise. For instance, a specialization of OWF style could permit analysis for data mismatch detection and repair. Another example of specialization is adding more detailed components that describe widget of a particular domain, e.g. geospatial intelligence analysis.
An architectural representation makes communication pathways explicit to users unlike the current Ozone visualization does. If users could see what channels are used, it would arguably make it easier for them to operate restrictions. Hence, a visual implementation of an architectural model in Ozone supports the activity of end-user analysts.
3.2 Requirements for Ozone Style
Using an architectural style, we can fulfill the motivation for formal modeling described in Section 2.3: a style provides a way of modeling a system, and modeling leads to clear documentation of underlying principles of Ozone and to analysis of widget compositions. However, not every style is equally good at describing composition laws and at providing analysis. So, we come the following style-specific requirements:
- Simplicity and understandability of systems produced by the style vocabulary. It means that models of OWF compositions should add as less complexity as possible to the inherent complexity of each particular composition. One important aspect is “scalability” of a style—measure of how much the number of the model’s elements grows in response to an increase in the number of elements in actual composition. For example, if adding one channel in OWF
world would make us create 3 connectors in the model, this way of modeling is less scalable than the one that would react with 2 connectors. Number and complexity of properties (of components, connectors, ...) also affects the simplicity.
- Providing enough information for analyses. For example, including information about where restriction lines go allows tools to predict how drawing a new line would affect message exchange, whereas not including such information makes this analysis impossible.
Before we start designing an architectural style for OWF compositions, it is worth outlining the potential analyses that the style might support. Style design alternatives will be evaluated based on what analyses are enabled and disabled by them.
### 3.3 Architectural Analyses
A formal architectural model of OWF user compositions can theoretically support analyses that are described below. The analyses are supposed to help users overcome speculative shortcomings of OWF or extend their possibilities in assembling widget-based systems. To classify analyses, they are grouped by ideas and discriminated in terms of their inputs. It is convenient to use units of information defined in Section 2.2 as inputs.
- **Message reachability analysis.** This analysis may come in different versions depending on what information about a composition is available. This analysis helps users overcome OWF’s inability to inform about what events are delivered to which widget. See Table 1 for variants of this analysis. Most of variants in this table answer questions: “who can talk/is talking to whom?” or “how to make these widgets talk?”.
- **Detecting data loss channels.** A *data loss channel* is a channel to which at least one widget publishes, but no widget is subscribed. An analysis can warn end users of such situations. See Table 2 for variants.
- **Privacy analysis.** Widgets are divided into two classes: widgets from trusted parties and untrusted parties. The goal is to prevent leaking of private data from trusted widgets to untrusted ones. This analysis needs additional specification of trusted and untrusted widgets. See Table 3 for variants.
- **Type mismatch analysis.** It might turn out that some widgets are publishing to channels they are not supposed to (e.g. users get control over assigning channels or there is a channel naming conflict in widgets coming from different parties). This situation can result in misbehavior of widgets because they might not be programmed to have wrong structure
---
4Choosing between the two requirements is a tradeoff: a style may produce quite simple systems with transparent structure and ways of interaction, but such a simple model would probably not contain enough information for most of analyses mentioned in the previous section.
5To find out actual usability problems in Ozone, a user study is needed.
6We assume that Unit 0—the set of deployed widgets—is always provided by a style.
Table 1: Variants of message reachability analysis.
<table>
<thead>
<tr>
<th>Input Unit</th>
<th>Additional Input</th>
<th>Description of analysis</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Two sets of pairs or widgets</td>
<td>How to set up restriction lines to make these pairs of widgets communicate and those pairs not communicate?</td>
<td>Set of restriction lines</td>
</tr>
<tr>
<td>3a</td>
<td>-</td>
<td>Can restriction lines be recreated from the given restrictions? If yes, what are they? An answer provides Unit 2 and enables corresponding analysis.</td>
<td>Potentially, set of restriction lines</td>
</tr>
<tr>
<td>2</td>
<td>An existing restriction line</td>
<td>What communications will be enabled and disabled by creating or removing the given restriction line?</td>
<td>Two sets of communications</td>
</tr>
</tbody>
</table>
Table 2: Variants of discovering data loss channels.
<table>
<thead>
<tr>
<th>Input Unit</th>
<th>Additional Input</th>
<th>Description of analysis</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>-</td>
<td>What are data loss channels? In this case, a non-empty answer indicates that a user might have forgotten to deploy some widgets.</td>
<td>Set of channels or connectors.</td>
</tr>
<tr>
<td>3</td>
<td>-</td>
<td>What are data loss channels? In this case, a non-empty answer indicates that a user might have set up too strong restrictions on communication.</td>
<td>Set of channels or connectors.</td>
</tr>
</tbody>
</table>
of messages in channels they are subscribed to. This analysis helps detect such situations. It needs additional specification of data type for each publishing widget. See Table 4 for variants.
- Mining common widget configurations. This analysis examines users’ behavior and extends users’ possibilities by recognizing common patterns in compositions, helping to establish them quickly, and showing differences between current compositions and patterns. See Table 5 for variants.
### 3.4 Style Design Heuristics
In the context of this report, choosing a style means committing to a particular way of modeling Ozone compositions. As it turned out, it is difficult to create a style that would evidently defeat all other options and, therefore, be the best solution for this modeling task. The design space of styles for OWF is non-trivial and vast. This is the reason why the next section is devoted to a detailed discussion of decision points and style alternatives.
Table 3: Variants of privacy analysis.
<table>
<thead>
<tr>
<th>Input Unit</th>
<th>Additional Input</th>
<th>Description of analysis</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>-</td>
<td>What are potential privacy violations?</td>
<td>Set of channels or connectors.</td>
</tr>
<tr>
<td>3</td>
<td>-</td>
<td>What are actual privacy violations?</td>
<td>Set of channels or connectors.</td>
</tr>
</tbody>
</table>
Table 4: Variants of type mismatch analysis.
<table>
<thead>
<tr>
<th>Input Unit</th>
<th>Additional Input</th>
<th>Description of analysis</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>1a</td>
<td>Data type for each port.</td>
<td>What is potential data type mismatch?</td>
<td>Sets of widgets that have data type conflict.</td>
</tr>
<tr>
<td>3</td>
<td>Data type for each port.</td>
<td>What is actual data type mismatch?</td>
<td>Sets of widgets that have data conflict.</td>
</tr>
</tbody>
</table>
The style alternatives will be informally evaluated based on the two style requirements. However, there is a number of loose style design heuristics\(^7\) that influence reasoning that is conducted below. Here is a list of the most relevant heuristics:
- Using properties of an architectural element (component, ...) to reference other architectural elements is not considered a good practice. There are two reasons for that: (i) it makes architectures less obvious because many information is hidden in properties, and (ii) rules that constrain values of such properties tend to be difficult to write, read, and evaluate.
\(^7\)Style design heuristics (rules of thumb in style design) and Acme language heuristics (first order logic predicates that are not strictly obligatory) are not to be confused.
Table 5: Variants of pattern detection analysis.
<table>
<thead>
<tr>
<th>Input Unit</th>
<th>Additional Input</th>
<th>Description of analysis</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>Statistics of usage</td>
<td>What are patterns of restriction lines?</td>
<td>Sets of restriction lines</td>
</tr>
<tr>
<td>3a</td>
<td>Statistics of usage</td>
<td>What are patterns of restrictions?</td>
<td>Sets of restrictions</td>
</tr>
<tr>
<td>3</td>
<td>Statistics of usage</td>
<td>What are patterns of communications?</td>
<td>Compositions of widgets and channels</td>
</tr>
<tr>
<td>3</td>
<td>Statistics of usage</td>
<td>What is the difference between a pattern and a current composition?</td>
<td>A set of widgets and a set channels</td>
</tr>
</tbody>
</table>
• Components with their ports should be *interaction-independent*. It means that a component or a port should not have properties that are related to the state of communication with other components—such information should be stored in connectors and roles.
• Connectors represent interaction between components, not just any relation between components. For instance, connectors are not intended to directly model restriction lines.
• Complex connectors should be avoided. The complexity of a connector is determined by how complicated the connector’s protocol of communication is. For example, if there is one event bus that serves pairs of components selectively based on several properties of roles (e.g. if a certain numeric property of two roles is equal), it is probably worth modeling it in a more detailed way.
Now, we are ready to go through the steps of devising an architectural style for OWF compositions.
4 Formal Modeling of Ozone Compositions
This section is devoted to detailed modeling Ozone widget compositions: it goes through decision points in the style design, evaluation of style alternatives, and the description of the finally selected style.
4.1 Basis of Modeling
The task is to come up with an architectural style for Ozone widget compositions. This section describes basic decisions. However somewhat apparent, they have to be mentioned to set up a foundation for less trivial aspects of creating a style.
First of all, widgets are to be represented with components through a strict one-to-one mapping. This decision rests upon that domain-specific computation is performed solely by widgets. We do not add any types of widgets or specific properties for them in this style because we are mostly interested in widgets’ interactions (modeled by ports), not their internal attributes. Nevertheless, specific properties of widgets can be added in specializations of the designed style.
As ports express the intent of inter-component communication, there is little flexibility of how they are used. Two types of widgets’ actions—publishing and subscribing—directly map into two corresponding types of ports.
If we speak in terms of how OWF technically works\(^8\), publishing happens instantly when the corresponding code is executed; that is, publishing is more an action than a process or a state. However, Acme language implies a more structure-oriented picture of runtime and compels us to view publishing as a recurring interaction (relation) and to model it with a port-role attachment.
The rest of modeling decisions are less straightforward and are covered in the next section.
4.2 Decision Points for Style
While designing a style, we came to a number of decision points that were not an easy task to go through. They are intertwined with each other, and each option presents tradeoffs that affect the resulting style. This section lists main decision points, alternatives, and their impact. The subsections follow the same pattern: a description, a list of options, a list of tradeoffs. Neither the list of decision points, nor lists of options or tradeoffs are comprehensive: the decisions, when combined, present even more detailed options that are not described.
4.2.1 Representing Communication
*Description:* Message exchange between widgets is carried out through channels. Representing channels and communication through them is a major decision that affects scalability of the style and understandability of produced compositions.
*Alternatives:*
\(^8\)See Appendix A for details in Z model.
RC1 Channels are one-to-one with connectors: each channel is modeled by one and only one connector.
RC2 Connector for each pair of components interacting: if there is communication between two components going, a connector for this pair is added to the model. All connectors have one publisher role and one subscriber role.
RC3 1-2 event buses are used to describe all channels. One bus is used in case if interactions are not divided to private and public, and two buses are used otherwise.
RC4 Connectors as “subscribe-sets”\(^9\) of a publishing component: components that publish information are complemented with a connector to which all subscribers of this component are connected.
RC5 Connectors as subchannels\(^10\). Every channel may have a public communication and a number of private communications (those enforced by restriction lines). Every such communication (subchannel) is represented with a connector in the model.
Tradeoffs:
1. Having connectors that represent several channels at a time makes diagrams cleaner (fewer connectors), but increases the complexity of connectors.
2. If connectors do not contain enough information about which channels are present, it hinders analysis capabilities.
3. If a connector strictly represents one channel, it results in ambiguous communication pathways (which widgets talks to which through this channel?) or creating complex role types (that store mappings to each other in order to preserve paths of interaction).
4.2.2 Representing Communication Types
Description: As was explained in Section 2.2, it is an important aspect of Ozone framework that every message is dispatched either through public or private communication domains. Representing this information in a style helps its understandability and in many cases can be a sufficient replacement for representing restrictions (as we see later).
Alternatives:
RCT1 Public/private roles. Type of role models type of communication (public or private) that is done through it.
RCT2 Public/private connectors. Type of connector models type of communication (public or private) that is done through it.
\(^9\)A subscribe-set of a widget is a set of widgets that are subscribed to that widget through all channels it publishes to.
\(^10\)See Section 4.4 for a more formal definition of the term subchannel
RCT3 No representation. Interactions are not divided into public and private.
Tradeoffs:
- These options depend on what kind of connector serves widget interaction, and not all combinations are possible.
- Not representing communication types makes the architectural model of compositions not information-rich enough for most analyses.
4.2.3 Representing Restrictions
Description: Restriction lines set up the relation of permitted communication\(^{11}\). In other words, after a user draws a set of restriction lines, Ozone is able to answer the question, “who is permitted to talk to whom”. It is a relation in the space of components. Acme language lacks first-class entities for representing custom relations on components. This fact brings about a question if we need to model restriction lines as they are (to be able to understand where they go given an Acme model of a composition), to model only restrictions (because they actually define what communication are permitted), or not to model at all.
Alternatives:
RR1 Restriction lines represented with properties: every component gets a property that lists other components to which it is connected.
RR2 Restrictions represented with properties: every component gets a property that lists other components to which it is allowed to communicate to.
RR3 External restrictions: restrictions are stored in a separate file and are used as an input for analysis.
RR4 No representation: restrictions are not represented explicitly in our architectural model.
Tradeoffs:
- Modeling a restriction line leads to a complicated style with many constraints that are difficult to write and evaluate. Also, it lowers the style’s understandability.
- Externalizing restrictions can be a delayed decision: it is possible to add the external restrictions up to any style that does not represent them.
\(^{11}\)This relation specifies what widgets are permitted to deliver messages to which.
4.2.4 Modeling Incomplete Communications
*Description:* This decision point depends on how we choose to represent communication; the least generic question to be answered is, “does architectural model of OWF compositions display inactive\(^{12}\) connectors?” For example, if a widget is subscribed to a channel that no other widget is subscribed to, should this channel be modeled or omitted from the model?
*Alternatives:*
MIC1 Include incomplete communications into the model. Depending on choices in other decision points, it might be a connector, a role, or a port that are not contributing to the picture of inter-widget communications (for instance, because of a restriction line).
MIC2 Include only elements (components, connectors) that form successful ongoing communications.
*Tradeoffs:*
- Omitting not active communications makes diagrams clearer and more understandable, but inhibits opportunities for “what-if” analysis.
- In some cases, one cannot include all incomplete communications (this opportunity may be disabled by other choices), and we would have to limit ourselves to partial choices, which increases the complexity of the style.
4.2.5 Default Ports and Roles
*Description:* In Acme, default ports for a component type can be specified, as well as roles for a connector type. If done so, every component (connector) of this type is created with a port (role) that cannot be deleted. That is, the decision is how to allocate default roles and ports to connectors’ and components’ types respectively.
*Alternatives:*
DPR1 Components [connectors] have a default publishing port [role] and/or a default subscribing port [role].
DPR2 Components [connectors] do not have default ports [roles].
*Tradeoffs:*
- Making a decision for this point might make a style more usable: if a connector cannot exist without some role, then this role should be a default one for the connector.
- This decision is based on semantics that is associated with port [role]: is it, for instance, “can publish” or “publishes”?\(^{16}\)
\(^{12}\)A connector/channel is *inactive* if no events flow through it. Otherwise, it is called *active*
4.3 Style Alternatives
Having the decision points above, it is impractical to decide on each one separately because combinations of various options cause unpredictable benefits, downsides, and further branching of decisions. Thus, styles need to be evaluated independently. To provide illustration for each style, we model a sample system (Figure 4): four widgets communicate through channels; widget A is linked by restriction lines to widgets C and D.

Figure 4: Sample system for modeling
*Note:* The option of representing restrictions is independent from other style design choices, and can be decided separately. For the sake of shorter review of alternatives, we do not consider any options other than RR4. Note that any OWF style can be augmented with one of the options above, but question is not considered in this report.
Below, several style alternatives are evaluated.
4.3.1 Style Alternative 1: Public and Private Roles
*Decisions:* RC1, RCT1, RR4, MIC1, DPR2.
This style alternative is built on choosing the first option in Representing Communication: each Ozone channel is matched with one and only one connector in the model. Let us also choose public/private roles to describe different types of communication. Unfortunately, modeling communication pathways unambiguously with this style is impossible unless we attribute roles with additional information about connections. Consider an example: two pairs of widgets privately communicate through one channel. Architectural model in this case would have one connector with 4 roles of two different types (publisher and subscriber). Without adding properties for roles, the actual pathways of events are not clear because they can go through any pair of differently
typed roles. Hence, at least private subscribe roles have to have an attribute set that contains names of components that that component is listening to.\footnote{The attribute to identify which roles interact with which is simplified to keep the description of alternatives shorter. Ideally, roles would have identifiers, and subscribers would point to publishers’ identifiers. In any case, this is considered a poor style design decision.}
You can see a model of the sample system in Figure 5. Notes show the attributes of subscribe roles—sets of components that roles receive information from.
*Units of information:* 1, 2, 4.
*Advantages:* Simple correspondence between OWF channels and connectors.
*Disadvantages:* Complicated logic of connectors; complicated roles.
---

**Figure 5:** Model of sample system in style alternative 1
### 4.3.2 Style alternative 2: Connector per Interaction
*Decisions:* RC2, RCT2, RR4, MIC2, DPR1.
For this style, we choose to have a connector for every pair of interactions. In this case, we can assign typing to connectors since each of them represents an atomic interaction, which is always either public or private. It also makes sense to have a default publisher and a subscriber roles for each connector since it will always connect a pair of interacting components. To preserve information about mapping from channels to connectors, each connector would have a string attribute with a channel name. A model of the sample is shown in Figure 6.
*Units of information:* 1, 2, 4.
*Advantages:* Public and private interactions are visually easier to tell apart.
*Disadvantages:* Many connectors on diagrams; not scalable for many channels (number of connectors grows quickly); difficult to visually identify channels in model.
4.3.3 Style Alternative 3: Event Buses
*Decisions:* RC3, RCT1, RR4, MIC1, DPR2.
This style variant attempts to fight the proliferation of connectors as number of channels grows. It is stated that architectural model always has two connectors: one for public domain of communications and the other one for private domain. To add at least information unit 3, we have to add an attribute to link subscriber roles to publisher roles; otherwise, it is impossible to find communication pathways in a diagram. To incorporate level 1, that attribute can be replaced by channel name for every role type. However, it make connectors significantly more complex.
A model of the sample system produced with this alternative is in Figure 7. Notes depict the said attribute of roles, analogous to the one in style 1.
*Units of information:* 1, 2, 4.
*Advantages:* Clean diagram due to fewer connectors.
*Disadvantages:* Overly complicated internal logic of connectors; difficult or impossible to see communication pathways.
4.3.4 Style Alternative 4: Subscribe Sets
*Decisions:* RC4, RCT3, RR4, MIC1, DPR2.
If we commit to RC4, architectural models of compositions have much less connectors than in case of RC1 or RC2 and do not need to have complicated roles or connectors. However, this style option has a significant drawback: it is impossible to devise what channels are used from such a model. For example, if a widget is publishing to two channels, both of them will be represented by one connector in the model. It means a style does not include information of unit 1 and disables a
number of potential analyses. The result of modeling the sample system with this style is depicted in Figure 8.
Units of information: 1, 4.
Advantages: Relatively fewer connectors; diagrams are clearer.
Disadvantages: Does not include information unit 1; no public/private division is possible.
4.3.5 Style Alternative 5: Subchannels
Decisions: RC5, RCT2, RR4, MIC1, DPR1
As we can see from previous alternatives, there needs to be a compromise between complexity of connectors’ logic, number of connectors on diagrams, and use of attributes. This style uses the following technique: every channel is viewed as one that has a public subchannel and potentially
a number of private subchannels. The presence of private subchannels is determined by following criterion: if there is interaction happening between widgets with restriction lines, there is a private connector involved.
This style keeps the number of connectors low as the number of channels grows, and at the same time provide public/private differentiation. A model of the sample system is shown in Figure 9.
*Units of information:* 1, 2, 4.
*Advantages:* Relatively fewer connectors; diagrams are clearer.
*Disadvantages:* More connectors than in alternatives 3 and 4.

### 4.4 Final OWF Style
From the style alternatives, we picked the Style Alternative 5: Subchannels. The main reason for it is that it gives a good balance between style requirements (Section 3.2) as well as style design heuristics (Section 3.4). Below, we refer to the chosen alternative as the OWF style and describe it in details.
The OWF style is a specialization of a generic publish-subscribe style [3]. The latter contains two component types (publisher and subscriber), an event bus connector type, and port and role types for publishing and subscribing.
```plaintext
// This Acme family describes the style of Ozone Widget Framework compositions
Family OzoneFam extends PubSubFam with {
// . . .
}
```
---
14 We considered many more than five alternatives, and presented only the most suitable of them.
In Ozone user composition style, widgets are represented with \( \text{WidgetT} \) - a component type that inherits both publishing and subscribing types.
```java
// A component type that represents widgets placed on the dashboard
Component Type WidgetT extends PublisherCompT, SubscriberCompT with {
// ...
}
```
To elaborate more on how channels are mapped to connectors, we need to formally define what a subchannel is. Consider a general situation: a number of widgets are subscribed and publish to a channel; some of widgets are connected with restriction lines. We want to model it with the minimal number of connectors possible, assuming that the logic of connectors stays simple: every widget subscribed to it gets all events from each publisher. Here we come to several definitions:
**Definition 1.** A subchannel of an Ozone channel \( X \) is a set \( S \) of widgets satisfying three statements:
- Every widget in \( S \) is publishing or subscribing to channel \( X \).
- For every subscribing widget \( A \) in \( S \) and for every publishing widget \( B \) in \( S \), it is true that \( A \) receives events from \( B \).
- Set \( S \) is maximal: no widget can be added to it without violating at least one of two previous statements.
**Definition 2.** A subchannel is called active if it has at least one publisher and subscriber.
**Definition 3.** A subchannel is called private if at least one of its widgets is attached to a restriction line. Otherwise, a subchannel is called public\(^{15}\).
There can be several subchannels for one channel. For example, if two widgets \( A \) and \( B \) publish to a channel, widget \( C \) subscribes to the channel, and \( A \) is connected by a restriction line to \( C \), this channel has two subchannels: \( \{ A, C \} \) (active, private) and \( \{ B \} \) (inactive, public).
Each connectors in this style represents a subchannel. The connector type `PublicChannelT` represents public subchannels, and `PrivateChannelT` represents private subchannels. Both of these connector types have an attribute that stores a corresponding channel’s name, which is always known and should be assigned to this attribute. It is a modeling rule that every subchannel of an OWF composition is represented in a model with an appropriate connector.
```java
Connector Type PublicChannelT extends EventBusConnT with {
// Name of a channel that corresponds to the connector
// This property should be unchangeable
Property channelName : string;
}
```
```
// A private channel connector represents widgets’ communication
// that happens through a restriction line ("private").
```
\(^{15}\)From the definition of a subchannel, it follows that every widget of a private subchannel is attached to a restriction line, whereas every widget of a public subchannel is not attached to a restriction line.
**Connector Type** PrivateChannelT extends EventBusConnT with {
// Name of a channel that corresponds to the connector
// This property should be unchangeable
Property channelName : string;
}
Ports types are inherited from the publish-subscribe style, and signify an intent of publishing or receiving messages. Roles of publisher and subscriber represent corresponding interaction responsibilities and can only be attached to respective ports.
The full code of OWF user composition Acme style is listed in Appendix B.
### 4.4.1 Data Loss Analysis
To exemplify how the style can be used for analysis, we implement a simple analysis carried out by Acme typechecker. This analysis searches all connectors in which data is lost, i.e. there are components publishing to them, but there are no components subscribed to them. According to how OWF works—no caching or logging messages is done—the information is lost in this situation, which might be of interest to user.
The implementation of data loss analysis consists of a function `dataLossEventBuses` that returns a set of connectors where data is lost and a rule demanding that this set be empty. If an Acme Studio user has a composition with such a connector, he will be notified of this rule’s violation. You can see an application of data loss analysis on Figure 10: a connector is marked with an exclamation sign because it violates the rule `noDataLoss`.
```
// Analysis: returns the connectors that are losing data
// (i.e. some components publish to them, but none subscribe to)
// in a given system.
dataLossEventBuses(s: System) : set{EventBusConnT} =
{select eb: EventBusConnT in s.CONNECTORS |
(exists pub: PublisherRoleT in eb.ROLES | true) and
(!exists sub: SubscriberRoleT in eb.ROLES | true)};
// Rule: there should be no data loss in any system.
rule noDataLoss = heuristic size(dataLossEventBuses(self)) == 0;
```
---
**Figure 10: Analysis finds a data loss connector**
```
// Analysis: returns the connectors that are losing data
// (i.e. some components publish to them, but none subscribe to)
// in a given system.
dataLossEventBuses(s: System) : set{EventBusConnT} =
{select eb: EventBusConnT in s.CONNECTORS |
(exists pub: PublisherRoleT in eb.ROLES | true) and
(!exists sub: SubscriberRoleT in eb.ROLES | true)};
// Rule: there should be no data loss in any system.
rule noDataLoss = heuristic size(dataLossEventBuses(self)) == 0;
```
5 Future Research Directions
The style presented in this report is a basic architectural formalization that enables structural analysis of widget compositions. There is opportunity for creating more specific models of OWF and respective analyses. These specific models would be represented by architectural styles that inherit the OWF style and extend it by adding new properties, or even component or connector types. This additional information would be used by new analyses that are made possible by it. It is reasonable for the extension of this style to be driven by user studies or user reports on interaction problems. The authors did not attempt such studies and had to speculate on what end-user problems might occur. A list of possible analyses has already been given in Section 4, summarizing extensions that might be helpful for OWF users.
Delivering analysis results to end users in a convenient way is a practical task yet to be solved. Building a runtime model of a widget dashboard requires obtaining up-to-date information about present widgets and their publishing and subscribing relations. A major implementation issue is that it is generally unknown to Ozone framework which channels a widget will publish to. This fact limits predictive and preventive analysis of widget composition. One possible solution is up-front static analysis of widget source code, but it lacks generality.
OWF and many other event-based frameworks for end-user widget composition remain unexplored from the formal architectural perspective. Devising common architectural styles would help generalize design decisions to the whole area of such frameworks. Also, if several frameworks share an architectural style, formal analyses of one of them can be applied to another. Another possible research direction is the principled design of such frameworks. Building a taxonomy of major design decisions, alternative options, and their impacts for event-based visual integration environments would facilitate the creation of such environments with respect to required quality attributes. There is a big body of potential work in this area: there is no agreement on the set of quality requirements relevant to such systems and on their priorities [13]. And, of course, the decisions themselves are yet to be gathered and categorized.
5.1 Conclusion
In this report, end-user compositions of Ozone Widget Framework were modeled with Acme architecture description language. We described the creation of style in detail: first, requirements for the style were formulated; then style design decision points and associated tradeoffs were examined; finally, several style alternatives and their positive and negative sides were reviewed, and the final style was picked. We have demonstrated that the style can serve as a basis for analysis by creating an analysis that finds channels through which data is lost.
References
A Z Model of Ozone Compositions
This appendix provides a model of OWF compositions in Z specification languages for clarification purposes. This model supplements the description of Ozone in Section 2.
A.1 Context of Z Modeling
The main purpose of the Z model [11] of Ozone compositions is to unambiguously convey how they work; our approach is to stay as close to the actual OWF messaging as possible (as long as it is simple). Unfortunately, it would hinder the generality of this model, but also it would provide deeper insights into how exactly Ozone widgets communicate.
The following main decisions for this Z model have been made:
- Only the details that are relevant to messaging and restrictions is included into the model.
- Data about current widgets, channels, and subscriptions is stored on the top level of the configuration. This decision is made to simplify constraints and pre-post conditions.
- Channels are created on-the-fly when they are accessed. After that, they stay in the model infinitely.
- Closed world assumption: all widgets that are currently in the system are known. Adding new widgets to a system is done through an operation.
A.2 Event Exchange Model
First, let us specify event dispatch of OWF in Z. By doing so, we will create a platform that can be used to model restriction lines and analyses. This decision will let us keep schemas simpler and compose them later as opposed to throwing all details in at once.
Widgets and channels are represented as basic types Widget and Channel (not as schemas) to make the specification more compact: putting data about present widgets, channels, and publish-subscribe relations between them into a single schema makes it possible to describe effects of publishing and subscribing with one schema, without using promotion. In the real world, of course, widgets have a rich set of attributes. These attributes might include name, URL, implementation technology, and unique ID, but none of them is relevant to event exchange.
[Widget, Channel]
The Configuration schema represents an instance of a dashboard with particular widgets and channels on it. The subscription partial function from widgets to sets of channels is included in this schema to keep track of which widgets are subscribed to which channels. However, publishing to a channel is not modeled as a function since it is an instant action in OWF and does not change the state of the system, except for maybe creating a channel. Thus, since channels are tracked separately in Configuration, there is no need for publishing as a relation in this schema.
The state invariant for the *Configuration* schema ensures that only widgets and channels registered in a configuration may participate in the *subscription* relation. Widgets that have not subscribed to any channel are mapped to an empty set.
<table>
<thead>
<tr>
<th><em>Configuration</em></th>
</tr>
</thead>
<tbody>
<tr>
<td>widgets : (\mathbb{P}) Widget</td>
</tr>
<tr>
<td>channels : (\mathbb{P}) Channel</td>
</tr>
<tr>
<td>subscription : (\text{Widget} \rightarrow \mathbb{P}) Channel</td>
</tr>
</tbody>
</table>
\[
\text{dom } \text{subscription} = \text{widgets} \\
\bigcup (\text{ran } \text{subscription}) \subseteq \text{channels}
\]
In the initial state of the *configuration* schema, there are no widgets or channels.
<table>
<thead>
<tr>
<th><em>ConfigurationInit</em></th>
</tr>
</thead>
<tbody>
<tr>
<td><em>Configuration</em></td>
</tr>
<tr>
<td>widgets = (\emptyset)</td>
</tr>
<tr>
<td>channels = (\emptyset)</td>
</tr>
<tr>
<td>subscription = (\emptyset)</td>
</tr>
</tbody>
</table>
Let’s start describing operations on configurations with adding and removing widgets. These operations do not change the set of channels.
The *AddWidget* operation takes a widget that is not yet present the configuration and adds it. Since it is required that the domain of *subscription* contains every element of *widgets*, we have to explicitly declare that the new widget is mapped to an empty set.
<table>
<thead>
<tr>
<th><em>AddWidget</em></th>
</tr>
</thead>
<tbody>
<tr>
<td>(\Delta \text{Configuration})</td>
</tr>
<tr>
<td>(w? : \text{Widget})</td>
</tr>
</tbody>
</table>
\[
\begin{align*}
\text{w?} \not\in \text{widgets} \\
\text{widgets}' = \text{widgets} \cup \{\text{w}\} \\
\text{channels}' = \text{channels} \\
\text{subscription}' = \text{subscription} \cup \{\text{w} \mapsto \emptyset\}
\end{align*}
\]
The operation of removing a widget is analogous to the one of adding a widget: it removes a given widget from the set *widgets*. Additionally, the *subscription* function removes the deleted widget from its domain to satisfy the state invariant.
Now, we can look at operations that change the subscription function: subscribe and unsubscribe. As noted before, channels are created on-the-fly, whenever they are published and subscribed to. In terms of our model, this fact means that there are no operations that directly add or remove a channel from channels. Addition of channels is indirectly managed by Subscribe and Unsubscribe: a referenced channel is set up if it doesn’t exist. Nevertheless, the main purpose of Subscribe is to record the fact that a certain widget now wants to receive messages from a certain channel. It is required that this widget isn’t subscribed to this channel at the moment when this operation is executed. After it is executed, the set of subscriptions for the widget is increased by the channel.
The Unsubscribe function removes a channel from a widget’s subscription set. Note that it does not delete a channel. That is, after having been added, a channel stays in the configuration forever. This modeling path has been chosen according to the assumption about channels’ existence that was stated in Section 1. Another way to decide on the presence of channels could be to delete them once they are not listened to, but this approach just complicates postconditions with no benefits.
The operation of publishing represents sending a message to a channel by some widget. Publishing doesn’t affect the state of the user’s orchestration, except for adding a channel if it hasn’t been used before. This operation, however, has an important aspect to model — the set of widgets that receive the sent message. This set is represented by the receivers! variable. Until we consider the concept of restriction line, receivers! is simply the set of widgets that have subscribed to the channel to which a message is published.
This concludes the formalization of basic messaging in the Ozone Widget Framework.
A.3 Event Restriction Model
The messaging model is now ready to be enhanced with the interesting way of controlling communication - the restriction line. We model it as a binary symmetric relation. This decision is made to reflect directly what’s going on in the real system.
An abbreviation for relations over widgets is introduced for brevity.
\[ \text{WidgetRel} == \text{Widget} \leftrightarrow \text{Widget} \]
As described in Section 1, drawing restriction lines between widgets defines a relation over them. This relation has two properties that follow from how OWF is implemented:
1. A restriction line cannot connect a widget to itself. In terms of relations, there is no pair
where the first element is equal to the second element.
2. A restriction line is symmetric (has no direction, or is bidirectional): if it connects widget A
to widget B, it also connects widget B to widget A. Thus, the relation should be symmetric
(equal to its inverse).
Note: a restriction line is not transitive. That is, if widget A is connected to widget B, which is
connected to widget C, widgets A and C are not allowed to communicate unless there is a direct
restriction line between A and C.
We use a helper schema to check whether a given relation over widgets can be defined by some
combination of restriction lines. The schema variable allRestrictionLines represents an infinite
set of widget relations that conform to a definition of restriction line. A relation can be described
by a layout of restriction lines if and only if the set allRestrictionLines contains it.
```
RestrictionLineDefinition
allRestrictionLines : \( \forall \) WidgetRel
allRestrictionLines = \{ r : WidgetRel |
(\( \forall \) w1, w2 : Widget \( \bullet \) (w1, w2) \( \in \) r \( \Rightarrow \) w1 \( \neq \) w2) \( \land \)
(r = r\(^\sim\))\}
```
Using the RestrictionLineDefinition schema, it is possible to define the OWF configuration
that keeps track not only of widgets, channels, and subscriptions, but also of restriction lines. The
relation restriction will store the current setup of restriction lines in the composition. This relation
is required to conform to the definition of restriction lines that has been presented above. Moreover,
it is necessary that only the widgets that are present in the configuration constitute this relation, so
we require the domain of restriction be a subset of widgets. From this fact and from the symmetry
of restriction it follows that the range of restriction is also a subset of widgets.
```
ConfigurationWithRestriction
Configuration
RestrictionLineDefinition
restriction : WidgetRel
dom restriction \( \subseteq \) widgets
restriction \( \in \) allRestrictionLines
```
The only plausible value for the restriction relation in the initial configuration is an empty set
because there are no widgets present.
```
ConfigurationWithRestrictionInit
ConfigurationWithRestriction
ConfigurationInit
restriction = \( \emptyset \)
```
Two framing schemas are defined below: \textit{RetainMessagingFrame} and \textit{RetainRestrictionsFrame}. The former declares that the basic messaging part (widgets, channels, subscriptions) is not changed, while the latter ensures that eventing restrictions don’t change.
\begin{align*}
\text{RetainMessagingFrame} & \quad \Delta \text{ConfigurationWithRestriction} \\
\text{widgets' } &= \text{widgets} \\
\text{channels' } &= \text{channels} \\
\text{subscription' } &= \text{subscription}
\end{align*}
\begin{align*}
\text{RetainRestrictionsFrame} & \quad \Delta \text{ConfigurationWithRestriction} \\
\text{restriction' } &= \text{restriction}
\end{align*}
\textit{AddRestriction} models drawing a restriction line between two different widgets \(w_1?\) and \(w_2?\) provided it hasn’t been there. In order to modify the \textit{restriction} relation correctly, both pairs \((w_1?, w_2?)\) and \((w_2?, w_1?)\) are added. Otherwise, the symmetry requirement is violated.
\begin{align*}
\text{AddRestriction} & \quad \text{RetainMessagingFrame} \\
\text{w}_1?, \text{w}_2?: \text{Widget} & \\
\text{w}_1? \neq \text{w}_2? & \\
(w_1?, w_2?) \notin \text{restriction} & \\
\text{restriction' } &= \text{restriction} \cup \{(w_1?, w_2?), (w_2?, w_1?)\}
\end{align*}
\textit{RemoveRestriction} is the opposite of \textit{AddRestriction}: a line between two widgets is deleted, which results into removing two pairs from the relation \textit{restriction}.
\begin{align*}
\text{RemoveRestriction} & \quad \text{RetainMessagingFrame} \\
\text{w}_1?, \text{w}_2?: \text{Widget} & \\
(w_1?, w_2?) \in \text{restriction} & \\
\text{restriction' } &= \text{restriction} \setminus \{(w_1?, w_2?), (w_2?, w_1?)\}
\end{align*}
We need to adapt the operations over \textit{Configuration} to \textit{ConfigurationWithRestriction}. The operations of adding a widget, subscribing, and unsubscribing can be promoted to the restriction level by being conjoined with \textit{RetainRestrictionsFrame} because they don’t modify the layout of eventing lines. The operations promoted to the level with restrictions get a -Rest suffix.
Promoting `RemoveWidget` needs more attention because it changes the messaging restrictions: if the deleted widget had restriction connections, these connections should be destroyed. After translating into the language of the `restriction` relation, this destruction is equivalent to removing the widget from both the domain and the range of this relation.
\[
\text{RemoveWidgetRest} \\
\quad \text{RemoveWidget} \\
\quad \Delta \text{ConfigurationWithRestriction} \\
\quad \text{restriction}^\prime = \{w?\} \iff (\text{restriction} \ni \{w?\})
\]
Adapting the `Publish` operation is even more complicated because the output parameter is modified in a non-trivial way by emergent restrictions. The approach is as follows: we take the original operation, rename the output parameter `receivers!` to `receivers?`, combine it with `RetainRestrictionsFrame` (because restrictions don’t change), and declare a new output parameter `receivers!`. All constraints on `widgets`, `channels`, and `subscription` are carried over from `Publish`.
How can the set of receivers be updated according to the restrictions? Certain widgets that are prohibited from communicating with `w?` should be dropped from `receivers?`. This fact turns us to the definition of the restriction line. That is, two distinct widgets are allowed to communicate if and only if they are directly connected with a line or when none of them is connected to any other widget. So in case of one widget `w?`, we start by checking whether it’s connected to any other widget `w1`. If yes, then we drop all widgets `w2` that don’t have a direct restriction connection to `w?` from `receivers?`. If no, we drop all widgets `w3` that are connected to some other widget `w4`. In the latter case, it is guaranteed that `w4` is equal neither to `w?` (because of false statement under `if`) nor to `w3` (because of the property of `restriction`).
We shouldn’t miss out on one small technical detail: whatever layout of restriction lines there is, a widget will always receive its own messages. However, the if-else expression can remove `w?` out of `receivers?`. Hence, we explicitly add it to the resulting set of a message receivers.
\[
\text{PublishRest} \\
\quad \text{Publish}[\text{receivers}?/\text{receivers}!] \\
\quad \text{RetainRestrictionsFrame} \\
\quad \text{receivers}!: \forall \text{Widget} \\
\quad \text{receivers}! = \text{receivers}? \setminus \\
\quad \quad \text{(if } \exists w1: \text{widgets} \bullet (w?, w1) \in \text{restriction} \text{ then } \{w2: \text{receivers}? \mid (w?, w2) \notin \text{restriction}\} \text{ else } \{w3: \text{receivers}? \mid \exists w4: \text{widgets} \bullet (w3, w4) \in \text{restriction}\}) \\
\quad \quad \cup \{w?\}
\]
This turned out to be a complex and hard to understand invariant. This incomprehensibility is not caused by the modeling language or approach itself — it is brought about by the real OWF implementation. It is intrinsic for the logic behind this restriction line in Ozone. It is difficult to reason about how the operation \texttt{PublishRest} works, and it is even more difficult to reason about the real user orchestration without having a formula to work with.
### A.4 Simplifying Restriction
In the remainder of 4 a straightforward simplification of the restriction line is presented. It aims at modeling the eventing restriction through a simple way of creating a “whitelist” for the exchange of events. This approach wraps the complicated concept of restriction line with a simpler concept of permitted communications.
So the function introduced below transforms a restriction relation into a permission relation that expresses the same set of constraints on messaging. The definition of a permission relation is that it contains a pair of widgets if and only if these two widgets are permitted to communicate (through any channel). When can this happen? According to the definition of how restriction lines work, it happens only in three cases:
- Two widgets are a pair in \textit{restriction}
- Two widgets are not in any pair in \textit{restriction}
- Two widgets are the same widget
\begin{align*}
\text{restrictionToPermission} : \text{WidgetRel} \rightarrow \text{WidgetRel} \\
\text{RestrictionLineDefinition}
\end{align*}
\begin{align*}
\text{dom restrictionToPermission} &= \{ r : \text{WidgetRel} \mid r \in \text{allRestrictionLines} \} \\
\forall r : \text{WidgetRel} \bullet \text{restrictionToPermission}(r) = \\
\{ w_1, w_2 : \text{dom } r \mid (w_1, w_2) \in r \vee \\
(\forall w_3 : \text{Widget} \bullet (w_1, w_3) \notin r \wedge (w_2, w_3) \notin r) \vee \\
(w_1 = w_2) \}
\end{align*}
Having defined this \textit{restrictionToPermission} function, we can now rewrite the publishing operation in a more readable way. We simply demand that all widgets \( w \) prohibited from talking to \( w \) (according to the permission relation) be removed from the set of receivers.
\begin{align*}
\text{PublishRestSimple} \\
\text{Publish[receivers?/receivers!]} \\
\text{RetainRestrictionsFrame} \\
\text{receivers! : } \mathbb{P} \text{ Widget} \\
\text{receivers!} = \text{receivers?} \setminus \\
\{ w : \text{Widget} \mid (w?, w) \notin \text{restrictionToPermission}(\text{restriction}) \}
\end{align*}
This concludes the description of OWF in Z specification language.
B Ozone Acme Style Source
Below you find the source code of OWF compositions architectural style in the Acme language. It inherits the publish-subscribe style and specifies rules for correct Ozone compositions.
```acme
import $AS_GLOBAL_PATH/families/PubSubFam.acme;
// This Acme family describes the style of Ozone Widget Framework compositions
Family OzoneFam extends PubSubFam with {
// A component type that represents widgets placed on the dashboard
Component Type WidgetT extends PublisherCompT, SubscriberCompT with {
// Rule: a component that does not communicate might be alarming
rule OrphanedComponent = heuristic size(self.PORTS) > 0;
}
// A public channel connector represents widgets' communication in 'public domain', i.e. not constrained by restriction lines.
Connector Type PublicSubchannelT extends EventBusConnT with {
// Name of the corresponding OWF channel
// This property should be unchangeable
Property channelName : string;
// Rule: all roles are of types declared in PubSub
rule OnlyPubSubRoles = invariant forall r in self.ROLES | exists t in
{PublisherRoleT, SubscriberRoleT} | declaresType(r, t);
}
// A private channel connector represents widgets' communication that happens through a restriction line ('private').
Connector Type PrivateSubchannelT extends EventBusConnT with {
// Name of a channel that corresponds to the connector (not one-to-one)
// This property should be unchangeable
Property channelName : string;
// Rule: all roles are of types declared in PubSub
rule OnlyPubSubRoles = invariant forall r in self.ROLES | exists t in
{PublisherRoleT, SubscriberRoleT} | declaresType(r, t);
// Rule: a private subchannel shall have at least one role
rule AtLeastOneRole = invariant size(self.ROLES) > 0;
}
// Rule: a channel cannot have more than two public connectors representing it.
}
```
rule UniquePublicChannelInv = invariant for all c1, c2 : PublicSubchannelT in self.CONNECTORS |
declaresType(c1, PublicSubchannelT) and declaresType(c1,
PublicSubchannelT) and (c1 != c2)
-> (c1.channelName != c2.channelName);
// Rule: (property of restriction lines) if a channel is talking on a
// private channel, it cannot communicate over a public one.
// The fact ‘‘talking on a public -> cannot talk on private’’ can be
// inferred from this rule.
rule ConnectOnlyToPublicOrPrivateDomainInv = invariant for all w : WidgetT in self.COMPONENTS, c_pub : PublicSubchannelT in self.CONNECTORS,
c_priv : PrivateSubchannelT in self.CONNECTORS |
!attached(c_priv, w) or !attached(c_pub, w);
// Analysis: returns the connectors that are losing data (i.e. some
// components publish to them, but none subscribe to) in a given system.
analysis dataLossEventBuses(s : System): set{EventBusConnT} = {select eb:
EventBusConnT in s.CONNECTORS |
(exists pub:PublisherRoleT in eb.ROLES |
true) and (!exists sub:SubscriberRoleT in eb.ROLES | true)};
// Rule: there should be no data loss in any system.
rule noDataLoss = heuristic size(dataLossEventBuses(self)) == 0;
// Rule: usually, users don’t want to have an empty public connector
// representing a channel if we have a private one
// Because the information of this channel’s existence is already captured
// by the private connector
rule NoEmptyPublicIfHavePrivate = heuristic for all c_pub :
PublicSubchannelT in self.CONNECTORS, c_priv : PrivateSubchannelT in
self.CONNECTORS |
c_pub.channelName == c_priv.channelName -> size(c_pub.ROLES) >= 1;
|
{"Source-Url": "http://reports-archive.adm.cs.cmu.edu/anon/isr2014/CMU-ISR-14-108.pdf", "len_cl100k_base": 15949, "olmocr-version": "0.1.50", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 82526, "total-output-tokens": 18238, "length": "2e13", "weborganizer": {"__label__adult": 0.00023186206817626953, "__label__art_design": 0.0005822181701660156, "__label__crime_law": 0.0001537799835205078, "__label__education_jobs": 0.0004360675811767578, "__label__entertainment": 5.841255187988281e-05, "__label__fashion_beauty": 8.809566497802734e-05, "__label__finance_business": 0.00015437602996826172, "__label__food_dining": 0.0002009868621826172, "__label__games": 0.0004112720489501953, "__label__hardware": 0.00041961669921875, "__label__health": 0.00013315677642822266, "__label__history": 0.0001653432846069336, "__label__home_hobbies": 6.598234176635742e-05, "__label__industrial": 0.00020062923431396484, "__label__literature": 0.00017952919006347656, "__label__politics": 0.00016367435455322266, "__label__religion": 0.00023472309112548828, "__label__science_tech": 0.003644943237304687, "__label__social_life": 5.996227264404297e-05, "__label__software": 0.00827789306640625, "__label__software_dev": 0.9833984375, "__label__sports_fitness": 0.00015723705291748047, "__label__transportation": 0.00023305416107177737, "__label__travel": 0.00014925003051757812}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 77688, 0.01218]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 77688, 0.40679]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 77688, 0.90005]], "google_gemma-3-12b-it_contains_pii": [[0, 562, false], [562, 659, null], [659, 908, null], [908, 908, null], [908, 4720, null], [4720, 7615, null], [7615, 9351, null], [9351, 12666, null], [12666, 14513, null], [14513, 16423, null], [16423, 18899, null], [18899, 20483, null], [20483, 23444, null], [23444, 26210, null], [26210, 29284, null], [29284, 30206, null], [30206, 32835, null], [32835, 35166, null], [35166, 37109, null], [37109, 39265, null], [39265, 41042, null], [41042, 42850, null], [42850, 44434, null], [44434, 45098, null], [45098, 46563, null], [46563, 49426, null], [49426, 51887, null], [51887, 54790, null], [54790, 57338, null], [57338, 59937, null], [59937, 61729, null], [61729, 63004, null], [63004, 64214, null], [64214, 66581, null], [66581, 68703, null], [68703, 71443, null], [71443, 74042, null], [74042, 76060, null], [76060, 77688, null]], "google_gemma-3-12b-it_is_public_document": [[0, 562, true], [562, 659, null], [659, 908, null], [908, 908, null], [908, 4720, null], [4720, 7615, null], [7615, 9351, null], [9351, 12666, null], [12666, 14513, null], [14513, 16423, null], [16423, 18899, null], [18899, 20483, null], [20483, 23444, null], [23444, 26210, null], [26210, 29284, null], [29284, 30206, null], [30206, 32835, null], [32835, 35166, null], [35166, 37109, null], [37109, 39265, null], [39265, 41042, null], [41042, 42850, null], [42850, 44434, null], [44434, 45098, null], [45098, 46563, null], [46563, 49426, null], [49426, 51887, null], [51887, 54790, null], [54790, 57338, null], [57338, 59937, null], [59937, 61729, null], [61729, 63004, null], [63004, 64214, null], [64214, 66581, null], [66581, 68703, null], [68703, 71443, null], [71443, 74042, null], [74042, 76060, null], [76060, 77688, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 77688, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 77688, null]], "pdf_page_numbers": [[0, 562, 1], [562, 659, 2], [659, 908, 3], [908, 908, 4], [908, 4720, 5], [4720, 7615, 6], [7615, 9351, 7], [9351, 12666, 8], [12666, 14513, 9], [14513, 16423, 10], [16423, 18899, 11], [18899, 20483, 12], [20483, 23444, 13], [23444, 26210, 14], [26210, 29284, 15], [29284, 30206, 16], [30206, 32835, 17], [32835, 35166, 18], [35166, 37109, 19], [37109, 39265, 20], [39265, 41042, 21], [41042, 42850, 22], [42850, 44434, 23], [44434, 45098, 24], [45098, 46563, 25], [46563, 49426, 26], [49426, 51887, 27], [51887, 54790, 28], [54790, 57338, 29], [57338, 59937, 30], [59937, 61729, 31], [61729, 63004, 32], [63004, 64214, 33], [64214, 66581, 34], [66581, 68703, 35], [68703, 71443, 36], [71443, 74042, 37], [74042, 76060, 38], [76060, 77688, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 77688, 0.06762]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
86c8114c16f88faf0a77057cc6b6cd60e2c7c299
|
Assume-guarantee Verification of Source Code with Design-Level Assumptions
Dimitra Giannakopoulou Corina S. Păsăreanu Jamieson M. Cobleigh*
RIACS/USRA Kestrel Technology LLC Department of Computer Science
NASA Ames Research Center Moffett Field, CA 94035-1000, USA
University of Massachusetts Amherst, MA 01003-9264, USA
dimitra, pcorina@email.arc.nasa.gov jcobleig@cs.umass.edu
Abstract
Model checking is an automated technique that can be used to determine whether a system satisfies certain required properties. To address the "state explosion" problem associated with this technique, we propose to integrate assume-guarantee verification at different phases of system development. During design, developers build abstract behavioral models of the system components and use them to establish key properties of the system. To increase the scalability of model checking at this level, we have developed techniques that automatically decompose the verification task by generating component assumptions for the properties to hold. The design-level artifacts are subsequently used to guide the implementation of the system, but also to enable more efficient reasoning at the source code-level.
In particular, we propose to use design-level assumptions to similarly decompose the verification of the actual system implementation. We demonstrate our approach on a significant NASA application, where design-level models were used to identify and correct a safety property violation, and design-level assumptions allowed us to check successfully that the property was preserved by the implementation.
1. Introduction
Our work is motivated by an ongoing project at NASA Ames Research Center on the application of automated verification techniques to autonomous software. Autonomous systems involve complex concurrent behaviors for reacting to unpredicted environmental stimuli without human intervention. Extensive verification is a pre-requisite for the deployment of missions that involve autonomy.
Given some formal description of a system and of a required property, model checking automatically determines whether the property is satisfied by the system. The limitation of the approach, commonly known as the "state-explosion" problem, is the exponential relation of the number of states in the system under analysis to the number of components of which the state is made [28]. Model checking therefore does not scale, in general, to systems of realistic size.
The aim of our work is to increase the applicability and scalability of model checking by:
1. applying it at different phases of software development, and
2. using compositional (i.e. divide and conquer) verification techniques that decompose the verification of a software system into manageable subparts.
We believe that the verification of a safety critical system should be addressed as early as during its design, and should go hand in hand with later phases of software development. Our experience working closely with the developers of the control software for an experimental Mars Rover has been that several integration issues can be detected during system design. At that level, verification of the system is typically more manageable and errors are easier and cheaper to fix since the system has not yet been implemented. Although system verification at the design level is undoubtedly important, there is little guarantee that the implemented system indeed satisfies the properties established at design time. We therefore need to provide a means of establishing that system implementations preserve the properties that have been demonstrated at the design level.
During design, our work supports the verification of Labeled Transition Systems (LTSs) against safety properties expressed in terms of finite-state automata. LTSs are communicating finite-state machines that can be used to describe the behavioral interfaces of software or hardware components. Safety properties describe the legal (and illegal) sequences of actions that a system can perform.
In previous work, we developed novel techniques for performing automated assume-guarantee verification at the
design level [9, 16]. Assume-guarantee reasoning was originally aimed at enabling the stepwise development of concurrent processes, but has more recently been used to decompose the verification of large and complex systems. It is in the latter context that we use it in our work.
Assume-guarantee reasoning first checks whether a component \( M \) guarantees a property \( P \), when it is part of a system that satisfies an assumption \( A \). Intuitively, \( A \) characterizes all contexts in which the component is expected to operate correctly. To complete the proof, it must also be shown that the remaining components in the system (\( M \)'s environment), satisfy \( A \). In contrast with previous assume-guarantee frameworks [8, 19, 25, 30], our techniques do not require human input in defining assumptions, but rather generate assumptions automatically, thereby increasing the accessibility of this kind of reasoning.
The focus of the present work is to develop a methodology for using design artifacts to leverage the verification of the actual system implementation. To this aim, we propose to use the assumptions that are automatically generated during design-level verification to perform assume-guarantee reasoning at the implementation level. In general, we believe that design-level assumptions can be used both during component development as an adjunct to traditional unit testing approaches, and during program validation, to enable more efficient reasoning and to model non-software components, including the actual environment of a reactive system. For the latter, it may be the case that critical system properties can only be demonstrated under specific environmental assumptions that appear reasonable to the developer, but cannot be discharged because the environment is unknown (e.g. autonomous systems). These assumptions can then be used to monitor, during deployment, the behavior of the environment, and trigger recovery actions when this behavior falls outside the envelope defined by the assumption.
The work presented in this paper contributes:
1. a methodology for using the results of the modular analysis at the design level to improve the performance of verification tools at the code level;
2. a program instrumentation technique for supporting assume-guarantee reasoning of Java programs using the Java PathFinder (JPF) model checker developed at NASA Ames [32]; and
3. a significant case study demonstrating the applicability of our approach to a real NASA software system.
The case study has been performed in the context of an ongoing collaboration with the developers of the control software for an experimental Mars Rover. More specifically, we have used our techniques to verify several versions of the software both during its design, and during its implementation, often using the results of our work to influence the design decisions of the developers. In this paper we will present how design-level models were used to identify and correct a safety property violation, and how design-level assumptions allowed us to check successfully that the property was preserved by the system implementation.
Note that, even though our research to-date has focused on checking implementations using software model-checking tools, we are aware of the fact that for complex software, even components may be too complicated to analyze exhaustively. In such cases, we intend to sacrifice exhaustiveness for the sake of scalability by using lighter-weight analysis techniques such as stateless model checking [17] or runtime analysis [20].
The remainder of the paper is organized as follows. We first provide some background on our design-level verification techniques in Section 2, followed by a description of the methodology that we propose in Section 3. Section 4 presents our approach to model checking source code in an assume-guarantee style. Section 5 describes the experience and results obtained by the application of our methodology to a NASA system that was the focus of our case study. Finally, Section 6 presents related work and Section 7 concludes the paper.
2. Background: Assume-guarantee verification at the design level
In this section we give background on assume-guarantee reasoning and we describe the automated assume-guarantee frameworks that we have developed for reasoning about software systems at the design level.
2.1. Assume-guarantee reasoning
In the assume-guarantee paradigm a formula is a triple \( \langle A \rangle M \langle P \rangle \), where \( M \) is a component, \( P \) is a property, and \( A \) is an assumption about \( M \)'s environment. The formula is true if whenever \( M \) is part of a system satisfying \( A \), then the system must also guarantee \( P \).
Consider for simplicity a system that is made up of components \( M_1 \) and \( M_2 \). To check that the system satisfies a property \( P \) without composing \( M_1 \) with \( M_2 \), one can apply assume-guarantee reasoning as follows. The simplest assume-guarantee proof rule shows that if \( \langle A \rangle M_1 \langle P \rangle \) and \((true) M_2 \langle A \rangle \) hold, then \((true) M_1 || M_2 \langle P \rangle \) is true. This proof strategy can also be expressed as an inference rule:
\[
\frac{\langle A \rangle M_1 \langle P \rangle \quad (true) M_2 \langle A \rangle}{(true) M_1 || M_2 \langle P \rangle}
\]
Note that for the use of this rule to be justified, the assumption must be more abstract than \( M_2 \), but still reflect \( M_2 \)'s behavior. Additionally, an appropriate assumption for the rule needs to be strong enough for \( M_1 \) to satisfy \( P \).
Whether it doesn't hold, further analysis is required to identify the compositional rule guarantees that the premise is checked to discharge produced by checking premise 1. If premise 1 holds, premise two premises of the compositional rule are then checked. If premise 2 holds, then the compositional rule guarantees that the property is achieved at the design level. At that stage, our frameworks will have automatically generated an assumption $A$ that is strong enough for $M_1$ to satisfy $P$ but weak enough to be discharged by $M_2$ (i.e. $A \vdash M_1 (P)$ and $\text{true} \vdash M_2 (A)$ both hold).
### 2.2. Automated assume-guarantee frameworks
Several frameworks have been proposed [8, 19, 25, 30] to support assume-guarantee reasoning. However, their practical impact has been limited because they require non-trivial human input in defining assumptions. In previous work [9, 16] we developed novel frameworks to perform assume-guarantee reasoning in a fully automatic fashion. The work was done in the context of finite labeled transition systems with blocking communication and safety properties.
In [16], we present an approach to synthesizing the assumption that a component needs to make about its environment for a given property to hold. The assumption produced is the weakest, that is, it restricts the environment no more and no less than is necessary for the component to satisfy the property. The automatic generation of weakest assumptions has direct application to the assume-guarantee proof; it removes the burden of specifying assumptions manually thus automating this type of reasoning.
The algorithm presented in [16] does not compute partial results, meaning no assumption is obtained if the computation runs out of memory, which may happen if the state-space of the component is too large. We address this problem in [9], where we present a novel framework for performing assume-guarantee reasoning using the above rule in an incremental and fully automatic fashion. This framework is illustrated in Figure 1.
At each iteration, a learning algorithm is used to build approximate assumptions $A_i$, based on querying the system and on the results of the previous iteration. The two premises of the compositional rule are then checked. Premise 1 is checked to determine whether $M_1$ guarantees $P$ in environments that satisfy $A_i$. If the result is false, it means that this assumption is too weak, and therefore needs to be strengthened with the help of the counterexample produced by checking premise 1. If premise 1 holds, premise 2 is checked to discharge $A_i$ on $M_2$. If premise 2 holds, then the compositional rule guarantees that $P$ holds in $M_1 \parallel M_2$. If it doesn’t hold, further analysis is required to identify whether $P$ is indeed violated in $M_1 \parallel M_2$ or whether $A_i$ is stronger than necessary, in which case it needs to be weakened. The new assumption may of course be too weak, and therefore the entire process must be repeated. This process is guaranteed to terminate; in fact, it converges to an assumption that is necessary and sufficient for the property to hold in the specific system.
Recently, we have extended our frameworks to handle circular rules and more than two components. We have implemented the frameworks in the LTSA model-checking tool [26] and have applied them to the verification of several design models of NASA software systems.
### 3. Methodology
This section describes our methodology for using the artifacts of the design-level analysis in order to decompose the verification of the implementation of a software system.
To address the scalability issues associated with software model checking, our approach, illustrated in Figure 2, integrates assume-guarantee reasoning of concurrent systems at the design and at the implementation level. At the design level, the architecture of a system is described in terms of components and their behavioral interfaces modeled as LTSs. Design level models are intended to capture the design intentions of system developers, and allow early verification of key integration properties.
For example, consider a system that consists of two design level components $M_1$ and $M_2$, and a global safety property $P$ (describing the sequence of events that the system is allowed to produce, or equivalently the bad behaviors that the system must avoid). To check in a more scalable way that the composition $M_1 \parallel M_2$ satisfies $P$, we use the assume-guarantee frameworks described in the previous section. We expect that, with the feedback obtained by our verification tools, the developers of the system will correct their models until the property is achieved at the design level. At that stage, our frameworks will have automatically generated an assumption $A$ that is strong enough for $M_1$ to satisfy $P$ but weak enough to be discharged by $M_2$ (i.e. $A \vdash M_1 (P)$ and $\text{true} \vdash M_2 (A)$ both hold).
To then establish that the property is preserved by the actual implementation, our approach uses the automatically generated assumption \( A \) to perform assume-guarantee reasoning at the source code level. The implementation is decomposed as specified by the architecture at the design level (i.e., components \( I_1 \) and \( I_2 \) implementing \( M_1 \) and \( M_2 \), respectively; see Figure 2), and we establish that \((\text{true}) \ I_1 \parallel \ I_2 \ (P)\) holds by checking that \((\text{true}) \ I_1 \ (P)\) and \((\text{true}) \ I_2 \ (A)\). If the two premises are true then the correctness of the assume-guarantee rule guarantees that the property is preserved by the implementation. If any one of the two premises does not hold, then the counterexample(s) obtained expose some incompatibility between the models and the implementations, and are used to guide the developers in correcting the implementation, the model, or both.
Alternatively, one may wish to check preservation of properties by checking directly that each implemented component refines its model. In our experience, for well-designed systems, the interfaces between components are small, and the assumptions that we generate are much smaller than the component models. Moreover, the controllability information that we use to derive these assumptions, and the fact that we take the properties into account in building them, typically allow us to achieve further reduction than abstraction techniques that would merely simplify models based on component interfaces.
The software architecture of a system may not always provide the best decomposition for verification. However, we currently focus on this line of research because one of our target applications is the Mission Data Systems architecture (MDS) [12]. MDS allows adaptations to be constructed by configuring instantiations of components with an ADL. We are interested in enriching critical components of the MDS system with models describing their abstract behavioral interfaces, and relating the analysis of these models with analysis of the resulting implementation.
4. Assume-guarantee analysis of software
In this section, we describe the main challenges in extending the Java Pathfinder software model checker to perform assume-guarantee reasoning, with assumptions and properties expressed as finite-state machines. Although we make our presentation in the context of Java programs, our approach extends to other programming languages and model checkers.
4.1. Java PathFinder
For checking Java implementations, we use Java PathFinder (JPF) [32]. JPF is an explicit-state model checker that analyzes Java bytecode classes directly for deadlocks and assertion violations. JPF is built around a special-purpose Java Virtual Machine (JVM) that allows Java programs to be analyzed. JPF supports depth-first, breadth-first as well as heuristic search strategies to guide the model checker's search in cases where the state-explosion problem is too severe [18].
In addition to the standard language features of Java, JPF uses a special class Verify that allows users to annotate their programs so as 1) to express non-deterministic choice with methods Verify.random(n) and Verify.randomBool() and 2) to truncate the search of the state-space with method Verify.ignoreIf(condition), when the condition becomes true. Methods Verify.beginAtomic() and Verify.endAtomic() respectively indicate the start and end of a block of code that the model checker should treat as one atomic statement and not interfere its execution with any other threads.
4.2. Mapping and instrumentation
We instrument Java programs to perform assume-guarantee reasoning using Java PathFinder. In our framework, both assumptions and properties are expressed as deterministic finite-state machines. For example, consider a program that opens and closes files. The assumption illustrated in Figure 3 expresses the fact that the environment will always open a file before closing it, and will always perform these actions in alternation. Any different behavior with respect to these actions leads the assumption to the ignore state, which reflects the fact that such behavior will never be exercised in the context of the environment that the assumption represents. On the other hand, the property illustrated in Figure 4 expresses the fact that the system is required to always open a file before closing it, and to always perform these actions in alternation. Any behavior that does not conform to this pattern is violating, and will be trapped in the error state.
At the source code level, assumptions and properties will be used to examine the behavior of the system and check whether behaviors that are not ignored by the assumption may be trapped by the property, meaning that the property is violated under the specific assumption. A necessary step in our approach is therefore a mapping between actions that appear in the design-level assumptions and properties, and events that occur in the software. For simplicity, we are assuming that actions in our design models correspond in the software either to method calls or to the locking and unlocking of objects.
The software must then be instrumented so that each event that appears in the mapping gets trapped, and is used in examining its effects on the state of the assumption and property. Presently, this instrumentation is done by hand, but we are considering the use of automated tools such as
public static void event() {
1) Verify.beginAtomic()
2) String threadName = Thread.currentThread().getName();
3) Throwable throwable = new Throwable();
4) StackTraceElement st = (throwable.getStackTrace())[1];
5) String methodName = st.getMethodName();
6) String className = st.getClassName();
7) int eventID = getEvent(className, methodName, threadName);
8) AGAssumption.event(eventID);
9) AG-Property.event(eventID);
10) Verify.endAtomic();
}
Our instrumentation adds at each point where an event occurs, a method call AGMonitor.event(), which traps the event and calls methods of the assumption and the property. This method, shown in Figure 5, uses Java reflection to determine the name of the thread making the method call (line 2), the method being called (lines 3-5), and the class that contains the method (line 6). These three pieces of information are used as a key to look up the corresponding event from the design level model (line 7). Then, this event is passed on to the assumption (line 8) and to the property (line 9). The entire block is enclosed by JPF directives (lines 1 and 10) which instruct it to treat the method body as an atomic step and to interleave no other threads with the execution of this method.
If more information is needed to determine the mapping between the Java program and the events from the design level model, then the event method can be extended to allow parameters to be passed that contain this extra information. This was necessary in our case study to obtain information about parameters being passed into method calls, parameters being returned from method calls, and to trap locks and unlocks of objects.
Properties and assumptions are implemented by classes AGAssumption and AG-Property. An excerpt of the AGAssumption class is shown in Figure 6. This class has a static integer field that records the current state of the assumption automaton (line 1) and a transition table that stores the transitions (line 2). The ignore state of the assumption is represented by a state with an ID less than zero. The method event advances the assumption by looking up the next state in the transition table (line 3). If the state is less than 0, this represents that the current execution does not satisfy the assumption and that JPF should not continue exploring this path (line 4). The current path does not need to be further explored, since we are only interested in property violations that occur under the given assumption.
The AG-Property class is similar, except a state with an ID less than zero represents the error state and line 4 is replaced by assert(state >= 0). This instructs JPF to detect a property violation and produce a counterexample trace if the error state of the property is reached.
4.3. Environment modeling
The process-algebra based models that are supported by our design-level tools can be checked in a straightforward way both in isolation and in combination with other models. In contrast to these, software model checkers such as JPF analyze executable programs, and as such, expect com-
plete programs as input. Therefore, to analyze system components in isolation in an assume-guarantee style, one must provide for each component an appropriate abstract environment that will enable its analysis. In essence, such environments provide stubs for the methods called by the component that are implemented by other components, or drive the execution of a component by calling methods that the component provides to its environment.
In our experiments, we used universal environments, that may invoke any provided operation in a component’s interface or refuse any required operations in any order. Tools that build such environments for Java programs are presented in [31].
4.4. Analysis of implementations
For checking implementations, we instrument the source code to perform assume-guarantee reasoning (as described above) and we use off-the-shelf software model checking tools (i.e. Java PathFinder for the analysis of Java programs). Note that, for complex software, even components may be too large to analyze exhaustively; abstraction and slicing techniques (e.g. [10]) could be used to make analysis of software components more tractable. Alternatively, our approach could sacrifice exhaustiveness for the sake of scalability by using lighter-weight techniques such as stateless model checking [17] or runtime analysis [20].
5. Case study
Our case study is the planetary rover controller K9, and in particular its executive subsystem, developed at NASA Ames Research Center. It has been performed in the context of an ongoing collaboration with the developers of the Rover, where verification and development go hand-in-hand to increase the quality of the design and implementation of the system.
In this section we describe how we used our assume-guarantee frameworks to check a key property on the design models of the executive and to automatically generate an appropriate assumption. We show how this assumption was used to perform assume-guarantee model checking of source code with JPF and how this compares to the monolithic (i.e. non-compositional) analysis of the executive’s Java implementation.
5.1. System description
The executive receives flexible plans from a planner, which it executes according to the plan language semantics. A plan is a hierarchical structure of actions that the Rover must perform. Traditionally, plans are deterministic sequences of actions. However, increased Rover autonomy requires added flexibility. The plan language therefore allows for branching based on state or temporal conditions that need to be checked, and also for flexibility with respect to the starting time of an action.
The executive needs to monitor the state of the Rover and of the environment to take appropriate paths in a flexible plan that it executes. It has been implemented as a multi-threaded system (see Figure 7), made up of a main coordinating component named Executive, components for monitoring the state conditions ExecCondChecker, and temporal conditions ExecTimerChecker - each further decomposed into two threads - and finally an ActionExecution thread that is responsible for issuing the commands to the Rover. The executive has been implemented as 25K lines of C++ code, 10K of which is the main control code, and the rest defines data structures that are needed for the communication with the actual Rover. The software makes use of the POSIX thread library, and synchronization between threads is performed through mutexes and condition variables.
5.2. Design-level analysis
The developers provided their design documents that described the synchronization between components in an ad-hoc flowchart-style notation. These were in essence extended control-flow graphs of the threads, and focused on such things as method calls, (un-)locking mutexes and wait-for and signaling of condition variables. They looked very much like LTSs, which allowed us to translate them in a straightforward and systematic, albeit manual, way into about 700 lines of FSP code. FSP is the input language of the LTSA tool, in which we have implemented our assume-guarantee frameworks described in Section 2. To achieve a close correspondence between the FSP code and the design diagrams, we first built models for mutexes, condition variables, and their associated methods. These models provided an infrastructure on top of which the actual threads of the system were modeled.
Model checking of the design models uncovered a number of synchronization problems such as deadlocks and data races. Moreover, the models were used for quick experimentation with alternative solutions to existing defects. The
study that we present here focuses on the following property that was formulated by the developer.
**Property.** For the variable `savedWakeUpStruct` of the `ExecCondChecker` that is shared with the `Executive` (see Figure 7), the property states that: "if the `Executive` thread reads the value of the variable, then the `ExecCondChecker` should not read this value until the `Executive` clears it first". The property was represented in terms of two states corresponding to the shared variable being cleared or not cleared, and an error state as discussed in the previous section.
**Analysis.** The developer expected the property to be satisfied by the `ExecCondChecker` and the `Executive` irrespective of the behavior of other threads. Our analysis was therefore performed on these threads together with the mutexes they use, since mutexes are the way in which synchronization issues are resolved in the system. We applied assume-guarantee reasoning as supported by our techniques described in Section 2, where assumptions were generated for the `ExecCondChecker` (module $M_1$) and discharged by the `Executive` (module $M_2$).
The weakest assumption consists of 6 states and description an environment where "whenever the `Executive` reads the `savedWakeUpStruct` variable after acquiring mutex `exec`, it should hold on to the mutex until it clears the variable". This assumption could not be discharged on the `Executive`. The counter-example obtained describes the following scenario: if the `Executive` reads `savedWakeUpStruct` and decides that the variable points to an irrelevant condition, it performs a `wait` on a condition variable associated with the `exec` lock. The `wait` causes the `exec` lock to be released automatically. The problem was fixed by adding to the `Executive` a statement that clears `savedWakeUpStruct` before checking whether the condition contained there is relevant.
### 5.3. Implementation analysis
**Set-up.** We analyzed a Java translation of this code, which was used in a case-study described in [5]. The translation was done selectively and it focused on the core functionality of the executive (the rest of the components being stubbed). The translated Java version is approximately 7.2 Kloc and it contains all the components of Figure 7, where each component (except the `Database`) executes as a separate thread.
In our experiment, we concentrated on a subsystem consisting of the `Executive` and `ExecCondChecker` threads (all the other threads were not started), and we analyzed this system for a very simple input plan, that consists of one node and no time conditions (which are not relevant for the analysis of the subsystem). JPF was able explore exhaustively the state-space of this subsystem (any other configuration, i.e. starting more threads or more complex input plans would force JPF to run out of memory). This subsystem is small enough to be manageable by JPF, and thus to provide a baseline for comparison with modular verification, but it still contains enough details about the interactions between the `Executive` and the `ExecCondChecker` threads, which were the focus of the design-level analysis.
To evaluate the merits of assume-guarantee verification using the automatically generated design-level assumption, we broke up the system in two components $I_1$ and $I_2$ representing the `ExecCondChecker` and the `Executive` threads respectively, and we checked the two premises of the assume-guarantee rule.
**Environment modeling.** As was mentioned in Section 4, to check components $I_1$ and $I_2$ in isolation, we need to identify the interface between them so we can generate environment models to make them closed.
To check premise 1, we built a universal environment to drive $I_1$ (the `ExecCondChecker`), that invokes any sequence of operations in the class `ExecCondChecker`'s interface (see Figure 8).
This driver loops forever generating events (line 1). It begins by making a non-deterministic choice of whether or not to acquire the lock on the `Executive` object (line 2). If it acquires the lock (line 3), we then use a specialized form of the `AGMonitor.event` method to trap the lock event (line 4). The universal environment then makes a non-deterministic choice (line 5). Depending on the results of this choice, zero or more events are generated while the lock is held (lines 6-10). These events include method calls that access `savedWakeUpStruct` which is shared between the two threads (i.e. `condChecker.deleteSavedWakeUp()` and `condChecker.getSavedWakeUp()`) and methods that add and remove conditions to and from a list structure in `ExecCondChecker`. Once the universal environment is done generating events, it generates an event signaling that the lock is to be released (line 11) and then leaves the synchronized block. If the choice was made to not acquire the lock on line 2, then the universal environment generates a single event (lines 12-16).
To maintain a finite number of elements in the list of conditions, we added an annotation forcing JPF to backtrack if more than one call to `condChecker.addConditionCheck()` is made; this is a reasonable assumption, since we considered a configuration where the input plan has only one node (and only one condition could be added for it).
To check premise 2, we built stubs that implement the methods invoked in component $I_1$ by $I_2$. Some care needed to be taken when doing this. For example, the `getSavedWakeup()` method can either return null or an object. To simulate this, the method stub would non-deterministically choose which to return.
**Analysis.** We used JPF and the property $(P)$ and assump-
class Executive {
public void run() {
while (true) {
if (Verify.randomBool()) {
synchronized (exec) {
AGMonitor.event("Executive", "lock");
while (Verify.randomBool()) {
switch (Verify.random(4)) {
case 0: condChecker.deleteSavedWakeup(); break;
case 1: condChecker.getSavedWakeup(); break;
case 2: condChecker.addConditionCheck(id, ...); break;
case 3: condChecker.removeConditionCheck(id, ...); break;
}
}
AGMonitor.event("Executive", "unlock");
} else {
switch (Verify.random(4)) {
case 0: condChecker.deleteSavedWakeup(); break;
case 1: condChecker.getSavedWakeup(); break;
case 2: condChecker.addConditionCheck(id, ...); break;
case 3: condChecker.removeConditionCheck(id, ...); break;
}
}
}
}
}
}
Figure 8. Universal driver
...form the analysis.
The Whole System rows give the results for checking the property monolithically. The version marked bug corresponds to the original system in which the property does not hold while the other version has had the bug fixed so that the property does hold.
The Premise 1 lines report the results of verifying premise 1. As was mentioned previously, while performing the verification, we discovered that an additional assumption, $A'$, was needed to complete the verification. We looked at two ways of incorporating this assumption into the analysis. The first uses the universal environment shown in Figure 8 and uses an automaton representation of $A'$, as shown in the AGAssumption class in Figure 6. The second uses a modified universal assumption that directly encodes $A'$. This is done by replacing lines 12-16 of the universal assumption with code that makes a choice only between the two events on lines 15 and 16. The bug that caused a violation of the property in the monolithic analysis was in the Executive, not the ExecConditionChecker, so these analyses were not affected by the presence or absence of the bug.
The Premise 2 lines report the results for checking premise 2, in which the assumptions used in checking Premise 1 need to be discharged. We discharged the assumptions $A$ and $A'$ separately, on the system containing the bug and on the system in which the bug is fixed.
From Table 1, we can see that the compositional approach to verification does reduce the number of states that JPF needs to explore and the amount of memory necessary for the analysis in the version of the Rover that does not contain the bug. The results from checking Premise 1 show...
that the encoding of the assumption can affect the performance of the model checker. We plan to investigate this in the future.
This case study demonstrates that the use of design level assumptions has merits in improving the performance of source code model checking. Our experimental work is of course preliminary, and we are planning to carry out larger case studies to validate our approach.
6. Related work
It is well known that software defects are less costly the earlier they are removed in the development process. Towards this end, a number of researchers have worked on applying model checking to artifacts that appear throughout the software life-cycle, such as requirements [3, 21], architectures and designs [1, 27, 29] and source code [4, 6, 10, 13, 32]. Our work integrates the analysis performed at different levels, using assume-guarantee reasoning.
Assume-guarantee reasoning is based on the observation that large systems are being built from components and that this composition can be leveraged to improve the performance of analysis techniques. Formal techniques for support of component-based design are gaining prominence, see for example [11]. To reason formally about components in isolation, some form of assumption (either implicit or explicit) about the interaction with, or interference from, the environment has to be made. Even though we have sound and complete reasoning systems for assume-guarantee reasoning, see for example [8, 19, 25, 30], it is always a mental challenge to obtain the most appropriate assumption.
It is even more of a challenge to find automated techniques to support this style of reasoning. The thread modular reasoning underlying the Calvin tool [14] is one start in this direction. The Mocha toolkit [2] provides support for modular verification of components with requirement specifications based on the Alternating-time Temporal logic.
More recently, Henzinger et al. [22] have presented a framework for thread-modular abstraction refinement, in which assumptions and guarantees are both refined in an iterative fashion. The framework applies to programs that communicate through shared variables, and, unlike our approach where assumptions are controllers of the component that is being analyzed, the assumptions in [22] are abstractions of the environment components. The work of Flanagan and Qadeer also focuses on a shared-memory communication model [15], but does not address notions of abstractions as is done in [22]. Jeffords and Heitmeyer use an invariant generation tool to generate invariants for components that can be used to complete an assume-guarantee proof [24]. While their proof rules are sound and complete, their invariant generation algorithm is not guaranteed to produce invariants that will complete an assume-guarantee proof even if such invariants exist.
7. Conclusions
We presented an approach for integrating assume-guarantee verification at different phases of system development, to address the scalability issues associated with the verification of complex software systems. Our approach uses the results of modular analysis at the design level to improve the performance of verification at the code level. We gave a program instrumentation technique for supporting assume-guarantee reasoning of Java programs using the Java PathFinder model checker; our approach easily extends to other programming languages and model checkers. We also presented a significant case study demonstrating the applicability of our approach to a realistic NASA software system. To evaluate how useful our approach is in practice, we are planning its extensive application to other real systems. However, our early experiments provide strong evidence in favor of this line of research.
In the future, we plan to look at ways to better automate the process of code annotation and environment generation. Additionally, we plan to investigate lighter-weight techniques such as stateless model checking or run-time verification in the context of our methodology. Finally, we plan to evaluate the use of other design-level artifacts to improve the performance of verification at source-code level.
References
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20040068289.pdf", "len_cl100k_base": 8204, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 35472, "total-output-tokens": 10846, "length": "2e13", "weborganizer": {"__label__adult": 0.0003528594970703125, "__label__art_design": 0.0002849102020263672, "__label__crime_law": 0.0003523826599121094, "__label__education_jobs": 0.0005669593811035156, "__label__entertainment": 4.857778549194336e-05, "__label__fashion_beauty": 0.0001537799835205078, "__label__finance_business": 0.00013780593872070312, "__label__food_dining": 0.0003097057342529297, "__label__games": 0.0005178451538085938, "__label__hardware": 0.0007777214050292969, "__label__health": 0.00045943260192871094, "__label__history": 0.0002046823501586914, "__label__home_hobbies": 7.575750350952148e-05, "__label__industrial": 0.00034332275390625, "__label__literature": 0.00022470951080322263, "__label__politics": 0.0002460479736328125, "__label__religion": 0.0004346370697021485, "__label__science_tech": 0.0118560791015625, "__label__social_life": 7.647275924682617e-05, "__label__software": 0.003797531127929687, "__label__software_dev": 0.9775390625, "__label__sports_fitness": 0.00032639503479003906, "__label__transportation": 0.0005402565002441406, "__label__travel": 0.0001990795135498047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46731, 0.02301]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46731, 0.48427]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46731, 0.90308]], "google_gemma-3-12b-it_contains_pii": [[0, 4162, false], [4162, 9808, null], [9808, 14786, null], [14786, 20269, null], [20269, 23380, null], [23380, 28021, null], [28021, 33700, null], [33700, 36609, null], [36609, 40783, null], [40783, 46731, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4162, true], [4162, 9808, null], [9808, 14786, null], [14786, 20269, null], [20269, 23380, null], [23380, 28021, null], [28021, 33700, null], [33700, 36609, null], [36609, 40783, null], [40783, 46731, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46731, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46731, null]], "pdf_page_numbers": [[0, 4162, 1], [4162, 9808, 2], [9808, 14786, 3], [14786, 20269, 4], [20269, 23380, 5], [23380, 28021, 6], [28021, 33700, 7], [33700, 36609, 8], [36609, 40783, 9], [40783, 46731, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46731, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
fb4155ee066d29f9694977cdee8a10e83593d14a
|
Collaborative Platform for Analysis of Software Systems
Catarina Isabel Carvalho Santana
Instituto Superior Técnico
Email: catarina.santana@tecnico.ulisboa.pt
Abstract—The Software Architectures course at Instituto Superior Técnico teaches students the most important concepts on design and architecture of software systems and helps students to apply these concepts to real and complex software systems. Organizing knowledge and applying theory to practice is not an easy task, and students often need to ask questions and discuss. State-of-the-art on collaborative, social software and knowledge structuring was analyzed and a social platform was developed to help solving these problems.
Keywords—social software, knowledge structuring, collaborative platform, reputation systems, tagging systems, ontology, taxonomy.
I. INTRODUCTION
Analyzing and discussing big, real, open-source and highly complex software system is a very important part of the Software Architectures course at Instituto Superior Técnico. In the course context, students must apply concepts and techniques for design and analysis of software architectures to descriptions of real systems. However, applying these concepts and techniques is not a very easy task, and often students have questions and doubts regarding these descriptions. These questions sometimes require not only consulting the course bibliography, but also discussing with peers or asking questions to teachers. This thesis focuses on providing a solution for this problem with the use of social software and knowledge structuring strategies.
This document is organized as follows: Section II gives a more detailed description about the problem of applying theoretical concepts to practical examples in the context of the Software Architectures course. Section III elicits the main goals of this thesis. Section IV presents the state-of-the-art in the areas of Social Software and Knowledge Structuring. Section V gives a small description of the developed solution. Sections VI, VII and VIII describe the solution domain model, architectural details and implementation. Finally, Section IX will show the assessment of the developed solution and X will describe what can still be added to it.
II. PROBLEM DESCRIPTION
The course of Software Architectures teaches students the most important concepts in the field of software architectures and applies these concepts to real-life software systems. In the practical component of this course, software description articles are analyzed to identify the theoretical concepts in practical examples. This analysis is either done by students with the help of the teacher, during practical classes, or in work groups where they read, discuss and analyze software descriptions together and present their results to both the teacher and the rest of the class.
Understanding the analysis done and how it was done is very important, since it means students can apply the concepts learned not only in the written exam to pass the course, but also in the future, in other real-life software systems. However, there are several issues regarding the application of theory concepts in this course:
• The course has around one-hundred students per year. Each person is different, and while some students may quickly understand what is taught in theory lessons, others may need some more time to assimilate what was taught.
• The output of the analysis done to software descriptions (the scenarios, etc. extracted) is not available in a consistent way for everyone, it is usually limited to the student’s individual notes or the work done in groups.
• The case description is usually a fairly long document, and correlating the concepts learned in theory classes with the practical examples is not easy, as the parts of the text that map to concepts are not always evident.
• The architectural elements extracted from a single software description are usually scattered along the whole text, and it is not evident the connection between all the elements.
III. OBJECTIVES
To solve the problems mentioned in Section II, a collaborative platform was planned and developed, where students and teachers collaborate in the analysis and synthesis of the case descriptions, ending on a structured representation of the case descriptions, that is hooked on the concrete description.
The goal of the platform is to provide ways for annotating the text on the case descriptions, which will help students organizing their thoughts and creating the structure, and use elements of social software, as a way of promoting collaboration, mutual aid, learning and even some competition between students.
The existence of this collaborative should provide not only a way for students to discuss, ask questions and consolidate their knowledge, but also a unique place where their study materials are stored and organized, facilitating their studies.
IV. RELATED WORK
The platform to develop can be thought of a social software, where different people communicate and collaborate to provide a structured representation of a software description. The next
sections provide an overview on the state-of-the-art of two main aspects:
- **Collaborative work**, presenting the state-of-the-art on social and collaborative aspects of software. This includes literature on the **Honeycomb Framework**, a framework that generalizes the most important components of social software. **Persuasive Software**, systems that have impact on users behavior and thoughts, which is the case of the platform to develop, **Roles in Social Networks**, describing the types of users of social software and **Reputation Systems**, which is the attribution of scores to users to provide a motivational component on the platform.
- **Knowledge Structuring**, presenting the state-of-the-art on ways of structuring information. This includes literature on **Collaborative tagging** systems, which consists of assigning keywords to documents or parts of documents. **Semi-structured content**, which consists of providing a way for structuring knowledge without such strict rules as, for example, an ontology or a taxonomy and **Ontology Learning**, extracting knowledge from text.
### A. Honeycomb Framework
The definition of Social Software as “systems that allow people, in their particularities and diversity, to communicate (interact, collaborate, exchange ideas and information) mediating and facilitating any kind of social relationship and favoring the emergence of a collective wisdom and a bottom-up organization” [1] applies to our collaborative platform, as it should allow students with different personalities and opinions to participate by identifying architectural elements, asking questions, etc. in order to reach a complete and correct analysis of that system.
The Honeycomb Framework was proposed to illustrate the seven elements that give a functional definition for social software [2]: **Identity**, the unique identifier of a user within the system, which applies to the platform to develop in the sense that each student is a unique person and must have a unique identification in the platform; **Presence**, resources that allow knowing if certain identity is online, which are not strictly necessary in the platform; **Relationship**, way to determine how users can relate/are related to others, which applies to the platform as students are related to each other both as colleagues as and group elements, and to the teachers; **Reputation**, way of knowing the status of a user in the system, which could be used to assess the quality and relevance of the contributions to the platform; **Groups**, possibility to form communities of users that have common interests, which applies to the platform as students form work groups; **Conversation**, resources for communication among the users (synchronous and/or asynchronous). In the context of the platform, conversation should be done asynchronously with comments and discussions; **Sharing**, possibility of sharing objects that are important to the users (videos, images, etc), which applies to this context as students may want to share documentation or other media with their colleagues or their group;
### B. Persuasive Software Design Patterns
The term “persuasive technology” is used to describe computer systems that have an impact on user’s thoughts and may even lead to changes in their behavior [3], [4].
There are three different possible outcomes for a persuasive system: **Reinforcement**, making current attitudes resistant to change, **Changing Outcome**, changes in a person’s response to an issue, and **Shaping Outcome**, formulate a pattern for a situation where one did not exist before [5]. The most important outcome for this platform is the Changing Outcome: When a description of a system is presented, the students must not only read it, but also relate it to the concepts learned and use the platform to try and extract the correct scenarios and views from it.
The concept of social influence describes a change in one’s behavior (or attitudes or beliefs), caused by external pressures [6]. In our context, students may not contribute to the platform at first, but may feel compelled to when seeing their colleagues’ contributions. Four design patterns are proposed for persuasive systems, in order to introduce social influence in software features: Social Learning and Facilitation (SLF), Competition (COM), Cooperation (COO) and Recognition (REC) [7].
The **Social Learning and Facilitation** pattern has the main purpose of using software features that allow to visualize the presence of other people, with the motivation that it is easier for individuals to pursue their goals if there is a clear awareness of other people pursuing the same goals and facing the same issues [7]. In the context of our collaborative platform, students may not contribute at first, but may feel compelled to as they see their colleagues contributing.
The **Competition** pattern has the main purpose of using competitive elements, such as ranks, scores and levels, that allow users to compare their performance with others, and adjust their target goals based on these. Some people may see this competition as a source of anxiety, so participation must be voluntary [7]. Adding a score for each student and a rank hierarchy based on the range of scores will start a hopefully healthy competition between them. Anonymity should be an option in the platform, to remove sources of anxiety.
The **Cooperation** pattern has the main purpose of providing software features that allow users to engage in mutual goals and support each other. The motivation for this pattern is that it is easier to cooperate if people are engaged in mutual objectives. However, some people prefer to perform alone, so cooperation must not be forced [7]. The students in the platform will be working towards a main goal: correctly understanding and correlating what was learned in the Software Architectures classes with real examples of software systems. But there are several concepts and structures to identify on a single description and students may have difficulties in identifying them, so dividing the main goal in several smaller goals and have discussions around them would be useful.
The **Recognition** pattern has the purpose of providing software features that enable users to get recognition from their peers. The motivation for this pattern is that users sometimes need a reason to focus on reaching their goals. Having their efforts recognized may be a good reason to keep the good work[7]. As the system should have a score system, it could be used as a way of creating a weekly top ten of the students who achieved most points in that week. Recognition is then achieved when students see their names highlighted.
C. Roles in Social Networks
A role, in a social structure, is a set of expectations for an individual in a certain position. For example, the role of “secretary” is associated to what secretaries are expected to do [8], [9]. There are two categories of roles: Non-explicit roles, which are not defined a-priori but can be inferred, and Explicit roles, which are predefined types of actors in the social network, such as “experts” or “influencers”.
In the platform to develop, it is possible to define a priori the two main roles: the Students, which are the most active users in the platform as they contribute to the analysis of the software descriptions, and the Teachers which corresponds to a very small number of users in the platform. Their number of contributions is smaller and they are mostly for adding correction to the contents added by the students to the platform.
D. Reputation Systems
Reputation systems are of extreme importance for certain kinds of applications, namely e-commerce websites, where money transactions are executed and the reputation of a seller will denote the degree of trust that possible buyers will have in them [10].
For the platform to develop, reputation does not play such an important role, but will add a motivational component to the platform: Students rate their colleagues’ contributions and should try to get and keep a high reputation score. The motivation behind the importance of including a reputation system in the platform is the study conducted [11], concerning the lack of participation in Moknowpedia, a Wiki system. A reputation system was added to the wiki in order to solve these problems and improve both content quality and quantity [12], and results showed an increase of 62% in the number of article revisions and an increase of 42% in the number of viewed articles.
1) Requirements and Features of the Reputation System: A framework for analysis of reputation systems is proposed in [10], where the general requirements for reputation systems are elicited and the corresponding features needed for their fulfillment. Given the context of the platform, its reputation system requires that Ratings and Reputation should discriminate user behavior, as these scores should allow to identify students with few and/or less relevant contributions and students with many and/or very relevant ones, the reputation system should be able to discriminate “incorrect” ratings, as malicious users are present everywhere and can give intentionally inaccurate ratings. Users should not be able to modify ratings, reputation values and calculate their own reputation, as this data should not be accessible to them, and the score should be calculated by the reputation system.
To satisfy the identified requirements, the reputation system should feature a range of values to represent trust and distrust, where low values indicate students with few and/or less relevant contributions and high values indicate students with many and/or very relevant ones. Absolute reputation values, calculated independently for each user, and identification of origin and target of the ratings, to prevent self-ratings and identify potential malicious users
2) Components of a Reputation System: Reputation systems are divided in four components [13], [14], and each have a set of defined criteria for their evaluation: Input, the process of collecting reputation information from information sources, Processing, the procedure of computing and aggregating the reputation information, Output, the dissemination of the reputation information and the Feedback Loop, the collection of feedback of the output (review of the review), which does not apply to the context of the platform.
Concerning the Input component, ratings are collected in the platform and are given by the students that are logged in. Only a single property is collected, the rating assigned. Concerning the Processing component, a weighted average algorithm is the best choice to aggregate ratings in this simple system, and information should be updated as soon as the ratings are assigned. Both the algorithm and the system have a very low complexity. Concerning the Output component, the end users of the information are the students registered in the platform, and this information is only available inside the platform. The reputation information consists in the result of the weighted average algorithm.
E. Collaborative Tagging
Collaborative tagging is the practice of allowing anyone to freely attach keywords or tags to content [15]. Tagging-based systems contrast with taxonomies as they are neither exclusive nor hierarchical, and allow to identify content as being about a great variety of things simultaneously [15]. The tags added to content may describe the content itself, or describe the category in which the content falls [16]. It is possible to identify several functions for the tags, within the system that uses the tagging system [15].
In this platform we are aiming for using tags from a closed taxonomy as a way of identifying the main parts of a software system within a software description, namely stakeholders, scenarios and their parts, tactics, etc., and use the tagged text to create a structured description of the document.
F. Semi-Structured Content
Knowledge can be obtained from many different resources, ranging from unstructured (for example, language models obtained from plain text) to structured ones (for example, ontologies) [17]. However, unstructured resources do not allow for complex inference chains [18] and information is not ontologized [17], and structured resources require a huge amount of effort to create and maintain [17]. Semi-structured contents try to create a middle-ground between these two types. The most important example of their use is the Wikipedia, which is a repository of web pages, related with each other by links. Massive online collaboration allow for updated high quality and wide coverage of contents. To sum up, using semi-structured resources provides the best of both worlds: high quality information with wide coverage of almost all domains [17].
The main goal of this platform is to allow students to extract a semi-structured representation of a software system from a description in plain text, and have all the parts that constitute a software system described in a structure similar to a Wikipedia, instead of scattered along a ten or more pages article. This will be accomplished by creating templates for the concepts and associating information from the document to them. Student collaboration in the platform will lead to good quality structured descriptions of the articles.
G. Ontology Learning
Research on Ontology learning from text has evolved over the years and there are several open challenges for this field [19]. Ontologies are defined as “effectively formal and explicit specifications in the form of concepts and relations of shared conceptualizations” [20], and can be thought of as a directed graph, with concepts as nodes and relations as edges. Techniques for ontology learning can be classified in statistics-based, linguistics-based, logic-based or hybrid.
Regarding the context of the platform, all the concepts used to tag the document contents (the concepts of Software Architectures) and their will be defined a priori. Software description documents do not contain these concepts, but the students’ motivation is to find parts of the text that correspond to the concepts predefined and tag them accordingly. This facilitates the comprehension of the text contents and the creation of the semi-structure as mentioned previously.
V. Solution
To solve the problems elicited throughout this document, it was developed a Web Application to be used by students and teachers, both in class and home environments. This kind of application facilitates collaboration between its users, and therefore was the more adequate choice for the system to develop. The developed application features an authentication system, where users can login into the system, document management, only available for teachers, where software description articles can be added or removed, document parsing into a view, creation of annotations in the document text, which are parts of selected text annotated with tags, and templates for a set of Software Architectures concepts, which aggregate the corresponding annotations and describe the concepts.
The next sections will give an overview of the domain, and explain the architecture and implementation of the system.
VI. Domain Model
To understand the architectural and implementation decisions taken during the solution development, it is necessary to understand the Software Architectures Domain Model. Section VI-A lists and describes the concepts talked in the Software Architectures classes, Section VI-B presents an abstract domain model where it is possible to see how these concepts relate and Section VI-C gives an idea on how the information from the domain model can be represented in templates.
A. Concepts
Before describing the domain model of the developed solution, it is necessary to provide a small introduction to the most important concepts from the Software Architectures course.
A Scenario is used to capture and express the quality requirements of a system. The considered qualities are Availability, Interoperability, Modifiability, Performance, Security, Testability and Usability.
A scenario consists of six parts[21]: The Source of Stimulus, Stimulus, Environment, Artifact, Response and Response Measure. Each Scenario uses a set of Tactics, which achieve the quality requirements. Each quality requirement has a set of commonly used tactics.
A View is a representation of a set of system elements and the relationships associated with them [22]. This set of elements and relationships is constrained by viewtypes, which define the element types and relationship types used to describe the architecture of a software system from a particular perspective. Viewtypes refine into styles, which are specializations of element and relation types, together with a set of constraints on how they can be used. Views can fall into three viewtype categories: The Module Viewtype, which documents the system principal units of implementation, the Component & Connector Viewtype, which documents the system units of execution, and the Allocation Viewtype, which documents the relationships between a system’s software and its development and execution environments.
B. Model
Figure 1 shows the concepts and relations described in Section VI-A in a Domain Model Diagram. The scenario elements are associated to the Scenario, and each Scenario captures a single Quality Requirement and has a set of Tactics. A View is associated with a Viewtype, which refines into a style. The View contains a set of elements, which have relations with each other. The Scenario, View and Elements are considered the main concepts of the domain, and they have a dedicated template in the developed solution. These templates will contain information about the concept and how it is related with other concepts in the domain model.
C. Templates
The structured representation of the Software Architectures concepts described in Sections VI-A and VI-B is represented
in the developed solution by using specific templates for these concepts. It did not make sense to have a template for each concept, as it is easier to see how they relate if they are in the same template, for example, it is easier to see the Scenario elements if they are inside the Scenario template. Figure 2 shows a Schema example for the Scenario template. All the Scenario elements, the quality requirement and the tactics are present in the template.
The templates for the View and View Elements follow the same idea of the Scenario schema. The template for the elements represents the element information and also its relations with other elements. The View template has the particularity that, besides including information about the view, also includes the templates of the elements present in it.
VII. ARCHITECTURE ANALYSIS
Section VI introduced the domain model of the Software Architectures concepts present in the developed solution, and the templates in which they are included. In this section, it is shown how these templates are filled with information extracted from a software description article. The next subsections will present two main entities from the system: the Document and the Annotation.
A. Document
The Document entity in this system corresponds to a software system description article. Figure 3 shows the Document entity in the system.
Fig. 3. The Document Entity
As the main purpose of this application is to create a structured representation of the document using the templates described in Section VI-C, the instances of the main concepts are associated with the Document.
B. Annotation
An annotation is a portion of text from the article, enriched with a tag. Figure 4 shows the Annotation entity in the system. The “annotation” field saves a JSON representation of the annotation data. Annotations are added to the system by selecting a portion of text in the parsed document and setting it as an annotation. Therefore, they are always associated to the Document in which they were created and, as they describe partially or totally a Software Architectures concept, can be associated not only with the main concepts, but with all the concept entities of the domain model.
C. Interface Flow
The associations between the entities described in the previous sections are created after a set of interactions with the system. These interactions are the creation of an annotation by using the AnnotatorJS interface, the association of that annotation to a domain concept and the redirection to that concept template, where annotations can be moved or deleted and other information, including description text, can be added.
VIII. IMPLEMENTATION
The application developed follows a Model-View-Controller architecture. The next sections will describe the solution implementation based on these three elements.
A. Model
The Model of the implemented system is based on the Domain Model from Section VI and the domain model is specified in the Domain Modeling Language, which was created for the Fénix Framework[23], [24].
Regarding Annotations, similarly to what is described in VII-B, in the implemented model Annotations are associated with the Document in which they were created, and to the User that created it.
Scenarios are represented in the implemented model in a very similar way to what is shown in Figure 1. However, the Quality Requirement is not associated with the Tactic, as the set of Quality Requirements and Tactics are not predefined in the implemented database, they are added upon Scenario creation. The Scenario is associated with the respective Document and the Annotations that describe it. Scenario elements are also associated with their respective annotations.
The Modules are the elements of the Module Viewtype Views. The Module entity in the implemented domain model is associated with the corresponding document upon its creation, and with the set of Annotations that describe it, as described in Section VII.
Modules are related to each others, as seen in Figure 1. Instead of defining these relations in a separate entity, they are
relation moduleIsPartOfModule {
Module playsRole parent { multiplicity 0..1; }
Module playsRole child { multiplicity 0..*; }
}
Fig. 5. Is-Part-Of relation between Modules in the implemented model
relation portIsAttachedToRole {
Port playsRole port { multiplicity 0..1; }
Role playsRole role { multiplicity 0..1; }
}
Fig. 7. Attachment relation between Component Ports and Connector Roles in the implemented model
relation viewHasModules {
View playsRole view { multiplicity 0..*; }
Module playsRole module { multiplicity 0..*; }
}
Fig. 9. Relation between View and the view elements
represented in the implemented model with different associations from the Module entity to itself, as seen in Figure 5.
Components and Connectors are the elements of the Component & Connector Viewtype Views. A Component has a set of Ports, and a Connector as a set of Roles. Figure 6 shows how the Components, Connectors and their respective Ports and Roles are implemented.
The Component and Connector are main concepts of the system, and therefore are associated with the corresponding document upon creation. Both the Component and Connector entities and also the Port and Role are associated to a set of Annotations that describe them.
Components are related with Connectors by the Attachment relation, in which Component ports are attached to roles of Connectors. The Attachment relation was defined by creating an association between the Port and Role entities, as shown in Figure 7.
Regarding Views, a View is considered a main concept, and therefore has its own dedicated template. Figure 8 shows how it is represented in the implemented model.
The viewtype of a View is defined upon its creation and stored in the model and display it along with the annotations added to a document. A View is created by associating an Annotation with it and, as it is a main concept, it is associated with the respective Document.
B. Controller
This section describes the Controller part of the implemented system. The application developed uses the Spring\(^1\) Framework, which allows the definition of one or more Java classes to act as Controllers and handle requests.
The AnnotationController class provides a way to manage the annotations added to a document. It communicates with the Domain Model to create, remove or update Annotations. This controller is in fact a RestController, which means it provides a REST API, used to retrieve a JSON representation of the annotations stored in the model and display it along with the document text. The endpoints provided by this controller are described in Table I.
<table>
<thead>
<tr>
<th>Name</th>
<th>Request Method</th>
<th>Endpoint</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>INDEX</td>
<td>GET</td>
<td>/store/annotations</td>
<td>Returns the set of annotations associated with the document with id docId</td>
</tr>
<tr>
<td>READ</td>
<td>GET</td>
<td>/id/store/annotations/{id}</td>
<td>Returns the annotation with the specific id</td>
</tr>
<tr>
<td>CREATE</td>
<td>POST</td>
<td>/store/annotations</td>
<td>Creates a new annotation, stores it in the model associated with the document with id docId, and redirects to the READ endpoint</td>
</tr>
<tr>
<td>UPDATE</td>
<td>PUT</td>
<td>/id/store/annotations/{id}</td>
<td>Updates the annotation with the given id and redirects to the READ endpoint</td>
</tr>
<tr>
<td>DELETE</td>
<td>DELETE</td>
<td>/id/store/annotations/{id}</td>
<td>Removes the association between the annotation with the given id and the document with id docId. The response is a HTTP/1.0 204 NO CONTENT</td>
</tr>
</tbody>
</table>
Table I. REST API provided by the Annotation Controller
The DocumentController class handles the requests to view, add or remove a document from the system.
Adding and removing documents from the system is a feature that only Teachers are authorized to use. To add a new document, the controller checks if the database already contains a document with the given URL and then extracts the article contents from that URL to add to the database. When a teacher removes a Document from the system, all Annotations and Domain Model entities associated with that Document such as Scenarios or Views are removed from the system as well.
\(^1\)https://spring.io/
The ScenarioController provides means to add and remove Scenarios from the document and link or unlink annotations from a Scenario or its elements. A Scenario is created when a user wants to link an Annotation to a Scenario and is prompted the interface to add a new or choose an existing one. When the Controller receives the request to add a new Scenario, it does not only adds a new Scenario to the database, but also adds a new SrcOfStimulus, Stimulus, Artifact, Environment, Response and ResponseMeasure to the database, all associated with the newly created Scenario.
When the user chooses which Scenario to link the Annotation with, the controller verifies the tag associated with the Annotation, and add the Annotation either to the Scenario or to the corresponding element.
A Scenario is initially created without any tactics. Upon receiving the corresponding request, the controller adds a new “Tactic” to the database, associated with the corresponding Scenario. Inside the template, annotations can be associated with the specific tactics.
When user text is added to a Scenario or one of its elements, a request is sent to this Controller. It will then update the Model accordingly and show the updated Model in the corresponding View.
Similarly to the Scenario Controller, the ModuleController handles the creation and deletion of Modules. It also handles the linkage of Annotations to existent Modules and the addition of user text to a Module. The implementation of the methods that handle these operations is similar to the implementation done in the Scenario Controller.
As Modules are related to each other, the Module Controller handles adding and removing other Modules to/from the possible relations. The modules to associate are selected within the template.
The ComponentController and ConnectorController classes handle the creation and deletion of Components and Connectors from the system. The two classes have very similar methods.
A Component has a set of Ports, which can be attached to Connector Roles. Adding and removing Ports to a component is very similar to the methods implemented to adding and removing tactics from a Scenario. Initially a Component has no Ports, and these can be created inside the Component template. The implementation of the Connector Roles is similar to the implementation of the Ports.
As mentioned in Section VIII-A, component ports can be associated with the connector roles by a relation of attachment. Inside a Component template, it is possible to attach each of the ports to a Role from an existent Connector.
The ViewController class handles the creation and deletion of Views from two possible Viewtypes: Module and Component & Connector.
Similar to the other domain entities, a new View is created when the user wants to associate an annotation with the tag “View” with a domain entity. The ViewController distinguishes between two different templates when receiving a request to view the View’s template: One for Module Viewtype views and one for the Component & Connector Viewtype views, to which only Components and Connectors can be added.
When, inside the template, the user selects a set of Modules, Components or Connectors to add to a view, a request is sent to the ViewController, which handles the association of these elements with the respective view.
C. Views
This section describes how the information from the Model is displayed to the user. The developed application uses Thymeleaf², a Java template engine for displaying dynamic templates.
Thymeleaf allows the definition of template fragments, which are pieces of code that can be defined in a separate file and be included in any template as desired. Fragments are used in the developed application in the page header, which is included in all templates, and in the concept templates. Figure 11 shows how a fragment is defined. Each fragment must have a unique name and all HTML code of that fragment is then defined inside the section tags.
Including a predefined fragment in a template is as easy as Figure 12 shows.
---
2http://www.thymeleaf.org/
The templates use the information added by the Controllers to the Model Attributes and display it in a structured way. This information is actually Java objects from the Model. Thymeleaf allows to treat these attributes as Java objects, so it is possible to obtain the value of the class attributes, or call methods on that object. For example, in Figure 13, the quality requirement and the name of a Scenario object are accessed.
Thymeleaf also provides automatic binding of forms information to provided objects. For example, Figure 14 shows a form with checkboxes, to select Modules.
When the form is submitted, Thymeleaf will bind the selected values to an object passed, and send that object in the body of the POST request to the Controller.
IX. EVALUATION
The success of a software system is often dependent on the opinion of the people that will use it. Systems attractive and easy to use according to the target audience background are more likely to be highly used.
The developed system tries to make the task of reading, understanding and structuring a software description article into an easy one, providing a simple and clean interface.
As the main goal of the developed application is to be used by students and teachers, in both classroom and home environments, it was asked to the students enrolled in the Software Architectures course to test the application, namely the features for annotating text and structuring Scenarios from the annotations created.
The participating students were asked to fill a small survey afterwards to register their opinions. This survey consisted of a grid question to evaluate aspects of the application usability in a scale from one to ten, three questions asking to evaluate the usefulness of the application in a scale of one to ten, and three open and optional questions, asking what did the student like the most about the application, what improvements could be done to it, and to register any other feedback the student may had.
A total of eight students volunteered to test the application. From these eight, five answered the survey. Due to the small number of participants and little feedback, the results shown are merely indicative, as it is impossible to take valuable conclusions from such a small sample.
Regarding the usability of the application, Figure 15 shows the graph containing the ratings given by the students.

**Usability of the Application’s Features**
Overall students thought the application is easy to use regarding creating Scenarios and associating annotations with them. However, there were complaints about the AnnotatorJS interface, such as “I had trouble when trying annotate a sequence of letters when that sequence overlapped with another annotation”, which implies that it is not very intuitive when trying to create multiple annotations in the same piece of text.
Improvements suggested in the survey include “There should be a way to “view” the scenario itself, with the diagram that is showed in the lectures. Also, the system needs to be more intuitive, particularly when it comes to selecting sentences for the scenarios” and “Make multiple copies of the article to be only seen by each group so that one group doesn’t get confused or get influenced by others”. This reinforces the idea that the AnnotatorJS interface is not very intuitive sometimes, and the need of creating groups in the platform, which is explained in X.
When asked what did they like the most about the application, students pointed that “It is possible for different people to analyze the same document, and its easy to use” and “It provides a quick and convenient way of constructing scenarios”. These opinions help conclude that the platform satisfies the requirement of providing collaboration among students, and facilitates understanding the Software Architectures concepts.
Regarding the usefulness of the application, the survey asked to rate how much the application facilitates the application of theoretical concepts to practical examples, and how useful would it be in the context of the Group Assignments and Practical
Classes. Figure 16 shows the graph of the ratings given by the students.

**Fig. 16. Evaluation of the usefulness of the application**
Overall, students would like to use this application for both their Group Assignments and when discussing a description article in the Practical classes.
In conclusion, the evaluation of the platform, despite the small number of testers, provided positive feedback. The platform proved to provide collaboration, and students appreciated how the information from the text can be extracted into a single template.
X. **Future Work**
Developing a platform that provides structuring knowledge from an unstructured source and all the described social features was a very ambitious goal for the time span available.
The developed solution focused on the association of tags from a closed vocabulary to parts of text, and the creation of a semi-structured representation of the software description articles, which was the most important goal of this thesis.
There are still details of the developed solution that could be improved and new features that could be added in the future.
A. **Allocation Viewtype**
Allocation viewtype elements should be added to the platform in a future version, so Allocation Viewtype Views can be added to the structured representation of the article.
B. **Graphical Representation of Views**
It is easier to understand Views in a graphical representation, and it would be very useful for the platform to provide a way to create or upload these representations in the future.
C. **Social Elements**
Sections IV-A, IV-B and IV-D list a series of social features that could be useful in the future.
The developed platform contains social elements and allows for collaboration, as students are individually identified within the system and work together over a shared article. However, there are several other social software elements that could enrich the platform as a social system, such as Groups, so students can work on their group assignments, Discussion Forums to provide communication and cooperation, a Reputation System to motivate students to contribute, and a Spotlight with the students with highest reputation scores, to provide recognition of their efforts.
XI. **Conclusions**
The success of social software is very dependent on the people that use it, since it is focused on the interactions and collaboration between their users.
Developing a platform including not only a way to structure knowledge but also a set of social features is a very ambitious task, and the focus of this thesis was the knowledge structuring part, which is very important for the context of the Software Architectures course.
Although the main feature of the developed solution is the possibility of extracting structured information from an unstructured source, this is done by a set of users authenticated within the system, which can collaboratively read and work over the same text.
Despite its simplicity and the lack of volunteers to test it, overall the platform proved that it provides a way for students to work together. However, there are still many features that could be added to make it more collaborative and more social.
**References**
|
{"Source-Url": "https://fenix.tecnico.ulisboa.pt/downloadFile/1126295043834014/resumo.pdf", "len_cl100k_base": 8254, "olmocr-version": "0.1.50", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 32115, "total-output-tokens": 10204, "length": "2e13", "weborganizer": {"__label__adult": 0.0005984306335449219, "__label__art_design": 0.0012788772583007812, "__label__crime_law": 0.0005183219909667969, "__label__education_jobs": 0.0445556640625, "__label__entertainment": 0.00016939640045166016, "__label__fashion_beauty": 0.0003104209899902344, "__label__finance_business": 0.0003876686096191406, "__label__food_dining": 0.0006017684936523438, "__label__games": 0.0010738372802734375, "__label__hardware": 0.0008196830749511719, "__label__health": 0.0005245208740234375, "__label__history": 0.0005154609680175781, "__label__home_hobbies": 0.00016558170318603516, "__label__industrial": 0.0004258155822753906, "__label__literature": 0.0009307861328125, "__label__politics": 0.00034236907958984375, "__label__religion": 0.0007090568542480469, "__label__science_tech": 0.01306915283203125, "__label__social_life": 0.0003664493560791016, "__label__software": 0.01467132568359375, "__label__software_dev": 0.91650390625, "__label__sports_fitness": 0.0003972053527832031, "__label__transportation": 0.0007786750793457031, "__label__travel": 0.00031757354736328125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47392, 0.01207]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47392, 0.65072]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47392, 0.92469]], "google_gemma-3-12b-it_contains_pii": [[0, 5124, false], [5124, 11851, null], [11851, 18531, null], [18531, 23174, null], [23174, 27290, null], [27290, 31678, null], [31678, 35783, null], [35783, 39967, null], [39967, 45515, null], [45515, 47392, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5124, true], [5124, 11851, null], [11851, 18531, null], [18531, 23174, null], [23174, 27290, null], [27290, 31678, null], [31678, 35783, null], [35783, 39967, null], [39967, 45515, null], [45515, 47392, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47392, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47392, null]], "pdf_page_numbers": [[0, 5124, 1], [5124, 11851, 2], [11851, 18531, 3], [18531, 23174, 4], [23174, 27290, 5], [27290, 31678, 6], [31678, 35783, 7], [35783, 39967, 8], [39967, 45515, 9], [45515, 47392, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47392, 0.03431]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
aadca9f2cc95dca3f13738dd899bbcdd36e00dd2
|
[REMOVED]
|
{"Source-Url": "http://snir.cs.illinois.edu/listed/C30.pdf", "len_cl100k_base": 13346, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 37862, "total-output-tokens": 14873, "length": "2e13", "weborganizer": {"__label__adult": 0.00040221214294433594, "__label__art_design": 0.0004482269287109375, "__label__crime_law": 0.0005359649658203125, "__label__education_jobs": 0.0008087158203125, "__label__entertainment": 0.00013065338134765625, "__label__fashion_beauty": 0.0002155303955078125, "__label__finance_business": 0.0005273818969726562, "__label__food_dining": 0.0004963874816894531, "__label__games": 0.0012063980102539062, "__label__hardware": 0.003696441650390625, "__label__health": 0.0012636184692382812, "__label__history": 0.00043320655822753906, "__label__home_hobbies": 0.0002008676528930664, "__label__industrial": 0.0007758140563964844, "__label__literature": 0.0004758834838867187, "__label__politics": 0.0003371238708496094, "__label__religion": 0.0006766319274902344, "__label__science_tech": 0.30712890625, "__label__social_life": 8.040666580200195e-05, "__label__software": 0.01318359375, "__label__software_dev": 0.66552734375, "__label__sports_fitness": 0.0004227161407470703, "__label__transportation": 0.000766754150390625, "__label__travel": 0.00026035308837890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48258, 0.01605]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48258, 0.42391]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48258, 0.86874]], "google_gemma-3-12b-it_contains_pii": [[0, 2077, false], [2077, 5105, null], [5105, 8270, null], [8270, 10737, null], [10737, 13485, null], [13485, 16107, null], [16107, 19453, null], [19453, 22496, null], [22496, 25483, null], [25483, 27485, null], [27485, 30441, null], [30441, 33148, null], [33148, 36399, null], [36399, 39351, null], [39351, 42439, null], [42439, 45886, null], [45886, 48258, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2077, true], [2077, 5105, null], [5105, 8270, null], [8270, 10737, null], [10737, 13485, null], [13485, 16107, null], [16107, 19453, null], [19453, 22496, null], [22496, 25483, null], [25483, 27485, null], [27485, 30441, null], [30441, 33148, null], [33148, 36399, null], [36399, 39351, null], [39351, 42439, null], [42439, 45886, null], [45886, 48258, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48258, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48258, null]], "pdf_page_numbers": [[0, 2077, 1], [2077, 5105, 2], [5105, 8270, 3], [8270, 10737, 4], [10737, 13485, 5], [13485, 16107, 6], [16107, 19453, 7], [19453, 22496, 8], [22496, 25483, 9], [25483, 27485, 10], [27485, 30441, 11], [30441, 33148, 12], [33148, 36399, 13], [36399, 39351, 14], [39351, 42439, 15], [42439, 45886, 16], [45886, 48258, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48258, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
fb1a822e9913915a98ecaad780c0319f1b7c19dc
|
Charting Coordination Needs in Large-Scale Agile Organisations with Boundary Objects and Methodological Islands
Downloaded from: https://research.chalmers.se, 2022-11-09 21:27 UTC
Citation for the original published paper (version of record):
N.B. When citing this work, cite the original published paper.
ABSTRACT
Large-scale system development companies are increasingly adopting agile methods. While this adoption may improve lead-times, such companies need to balance two trade-offs: (i) the need to have a uniform, consistent development method on system level with the need for specialised methods for teams in different disciplines (e.g., hardware, software, mechanics, sales, support); (ii) the need for comprehensive documentation on system level with the need to have lightweight documentation enabling iterative and agile work. With specialised methods for teams, isolated teams work within larger ecosystems of plan-driven culture, i.e., teams become agile “islands”. At the boundaries, these teams share knowledge which needs to be managed well for a correct system to be developed. While it is useful to support diverse and specialised methods, it is important to understand which islands are repeatedly encountered, the reasons or factors triggering their existence, and how best to handle coordination between them. Based on a multiple case study, this work presents a catalogue of islands and the boundary objects that are constantly encountered in large-scale systems development. Through analysing communication and coordination challenges in large-scale development.
CCS CONCEPTS
- Software and its engineering → Agile software development; Collaboration in software development; Documentation;
- General and reference → Empirical studies;
KEYWORDS
large-scale systems development, boundary objects, coordination
Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies bear this notice and the full citation on the first page. Copyrights for components of this work owned by others than ACM must be honored. Abstracting with credit is permitted. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Request permissions from permissions@acm.org.
ACM Reference Format:
1 INTRODUCTION
Large-scale systems engineering companies are typically made of many teams that work together, commonly with plan-driven methods, to contribute to one product. With the recent digitisation trends, many such companies have adopted agile methods to help them address the ever-changing market needs and the growing competition [21, 28]. Given the challenges of introducing agility to large system companies [19], most adoptions start with the software development teams at the lower level in the companies [30]. These teams in turn tailor the agile methods to their contexts [7], thus creating companies that have pockets of agile teams within a larger ecosystem of plan-driven culture, also identified as “agile islands in a waterfall” [13].
As the combination of agile with traditional plan-driven development methods become reality [27], knowledge management and coordination challenges arise [28]. Inter-team coordination and knowledge sharing are key items on the research agenda on large-scale agile development [9]. Teams using varying methods and practices need to communicate to deliver the correct product. Artefacts shared at their boundaries, referred to as boundary objects, offer potential solutions to these knowledge and coordination challenges. Boundary objects have been proposed to help manage coordination between agile teams [32]. They can create a common understanding across sites, without compromising each team’s identity, and are therefore useful when establishing coordination mechanisms across team boundaries.
To this effect, and as a first step towards alleviating the coordination challenge, this study set out to understand and document the agile islands together with the boundary objects that are constantly encountered in large-scale systems development. Through an exploratory study with four large-scale system engineering companies, based on a focus group and two workshops, we explore the following research questions:
We believe that this study will benefit both researchers and practitioners who want to gain insights into inter-team coordination in large-scale development. In addition, we find concrete methodological islands, but also more abstract forces (or: drivers) that can contribute to the emergence of islands.
In answering our research questions, we provide a catalogue of methodological islands that are frequently relevant when introducing agility at scale, as well as the boundary objects between them.
twonon-agileteamscanhaveanimpactonlarge-scaleagilesystem
toanswerourquestionsandgivethedetailsoftheworkshopsand focus group. Section 4 presents our findings to RQ.1 and Section 5 describes the findings related to RQ.2. We discuss our findings and conclude the study in Section 6.
2 BACKGROUND
Agile methods with the promise of continuous delivery of quality software have changed the way software is developed since the launch of the agile manifesto in 2001 [3]. Originally meant for small co-located teams, agile methods are being adopted in large-scale systems development organisations [20]. Existing studies on agile adoption in large-scale systems show that companies successfully adopt these methods [19, 23] even though challenges remain, especially those related to coordination and mixed processes between different teams [9, 24]. This section gives the background of agile islands and boundary objects presented in this study.
2.1 Agile Islands
Many large-scale system engineering companies have not fully adopted agile methods since they are not fully applicable in their domains. Empirical researchers have recommended tailoring agile methods to the contexts of the specific organisation [19].
This means that organisations have to carefully choose practices that complement their values, culture, and norms [22]. Research on agile methods tailoring has covered diverse areas including methods used to tailor [7] and also the rationales and implications of tailoring [12]. Still, to satisfy the need to complement agile methods with traditional methods, many companies are using hybrid methods in their development process [27].
Hybrid methods typically combine agile and plan-driven practices in software development [14]. Existing research on this topic has confirmed that this is the trend in many organisations today [15, 27]. Studies have explored the challenges faced in such environments [16, 28] and others have gone a step ahead to propose solutions [17]. Tell et al. [26] have studied how different practices are combined to devise hybrid processes in an attempt to understand how to systematically construct synergies.
It should be noted that in large-scale organisations in practice, combinations start with the software development teams using agile methods while the rest of the organisation works with traditional methods [30]. This leaves teams as “agile islands” in a waterfall environment [13], also defined as pockets of agile within larger ecosystems with plan-driven culture.
Vijayasrathy and Butler reason that the choice of method used in the teams is associated with characteristics of the organisation, project, and team size [29]. This offers an explanation for the existence of agile islands, that differ from the surrounding organization, e.g., in terms of artefacts, iteration length, and delivery schedule. Bjarnason et al. refer to such differences as different forms of distances, for instance, geographical, organizational, or cognitive distance, distance related to artefacts (e.g., semantic distance), and distance related to activities (e.g., temporal distance) [4]. Such distances make it more difficult to coordinate between islands or between the non-agile part of the organisation and the agile islands.
2.2 Boundary Objects
Boundary objects are a sociological concept introduced by Star and Griesemer [25] who studied how a shared understanding between interdisciplinary stakeholders can be established. We refer to their definition of boundary objects as “objects which are both plastic enough to adapt to local needs and the constraints of the several parties employing them, yet robust enough to maintain a common identity across sites” [25]. In the context of agile development, the “parties [...] across sites” are individuals with potentially different backgrounds and disciplines, typically forming organisational units (e.g., teams or departments). These groups can flexibly interpret a boundary object and tailor it to their needs, while the group’s identity and existing practices can be preserved [1]. While boundary objects originate from the field of sociology, they have also been studied in agile development contexts (e.g., [5, 35]).
In these contexts, boundary objects are artefacts (e.g., design specifications or user stories) that create a common understanding between agile teams [5].
In large-scale agile systems engineering, boundary objects are used between individuals from several sub-disciplines of systems engineering, who refer to concepts with different terminologies and are often located at different geographic locations [32]. The groups using boundary objects need to be understood to enable knowledge management and inter-team coordination in an organisation. Some organisational groups might be agile islands, working in different ways than others parts of an organisation.
3 RESEARCH METHOD
Due to the exploratory nature of our research questions, we decided to conduct a multiple exploratory case study [34]. We collected data in a staged process, using a focus group with participants from several companies as a starting point and refining our data with
Develops telecommunications products. Hardware development is largely decoupled from the software development. New hardware becomes available with a regular, but low frequency. Thus, the software development sets the pace of system development, which can be seen as continuous and agile, in that it embraces agile values as much as possible.
Develops mechanical products, both for consumer markets and for industrial development and manufacturing. Their system development is decomposed into several system elements. Software development is mostly confined to two of these elements, both of which are characterised by agile methods and practices such as Scrum and Continuous Integration.
Is an automotive OEM whose agile methods have been successfully applied to in-house development of software components. There is a desire to scale up these fast-paced approaches from developing software components to developing complete functions, thus including agile development of hardware and mechatronics.
Is a manufacturing company that develops high-tech products for the medical domain. Agile principles and practices are considered on all levels, yet must be carefully considered due to regulatory requirements and the very large scale of the development effort. The software development is to a good extent independent from hardware development cycles.
In-depth workshops at two of the companies. Table 1 presents short descriptions of the participating companies. We report on our data collection, the way we analysed the information, as well as the threats to validity in the following.
### Focus Group
We base the findings of this study on a focus group in which we discussed agile islands and the boundary objects that connect them with four practitioners, one from each of the four participating companies. Three of those practitioners had prepared presentations based on our instructions to help us explore the following issues: (i) in terms of inventory, what knowledge is required on the island and what knowledge actually exists; (ii) in terms of infrastructure, what knowledge needs to be shared and what knowledge is actually shared; and (iii) in terms of process, how to facilitate learning, retrieving, capturing and applying knowledge.
The practitioners have high-level technical roles in the organisation (system architect, tooling and process specialist) and are thus accustomed to working with different islands within the organisation. They have also been working in these companies for several years and thus have a good grasp of the processes and the organisational structure. All four companies are large-scale systems engineering organisations with a predominantly agile software development approach and global distribution of developers.
The three presentations identified boundary objects commonly encountered in practice together with teams that use them. They provided a foundation for identifying common boundary objects and islands and were the starting point for discussions about the commonalities and differences between the organisations.
This information was collected by the researchers with extensive notes. One of the researchers also prepared an overview image of the boundary objects and the islands they connect and applied a rough clustering while the workshop was ongoing. This figure was continuously augmented with new insights during the presentations and updated during the discussion. At the conclusion of the focus group, the figure was presented and practitioners could comment on whether it represented their understanding.
### Individual Company Workshops
As a follow-up of the focus group, we conducted individual workshops of approximately three hours each with two of the companies that participated in the initial data collection. The workshops were conducted onsite at the companies and aimed to analyze concrete agile islands and boundary objects based on the inventory from the focus group. Two researchers were involved in each of the workshops and acted as moderators and facilitators. We prepared a workshop instrument (https://rebrand.ly/workshop_BOMI) to introduce the topic and guide through the workshops.
The workshops started with an introduction to boundary objects and agile islands and a statement of the goals. The participants were then asked to individually brainstorm the boundary objects and agile islands they encounter in their work. All input was recorded on post-it notes. Agile islands were then discussed and roughly organized on a wall. Once a picture of the relevant islands emerged, participants then located boundary objects between the identified islands creating a map. This map was then discussed and the practitioners reflected on the implications of the islands and how the boundary objects are currently being managed.
The first company workshop attracted a total of 13 practitioners who represented a number of roles: systems engineers, project managers, test specialists, digital transformation managers, and business developers. Representatives from the company first presented their current development process and the transformation
that they are undergoing. Afterwards, the two researchers introduced agile islands and boundary objects and defined the purpose of the workshop. We then followed the procedure outlined above. However, after the collection of islands and boundary objects and the initial discussion of the map, we focused on a specific boundary object (“Product Requirement Specification”) that was deemed highly critical by the practitioners. This provided additional insights into differences of governance processes within the organisation as well as the impact of organisational cultures in different parts of the company.
At the second workshop, three company participants attended, having the roles of Scrum master, architect, and systems engineer. The workshop procedure outlined above was followed, starting with an introduction of the concepts and goals, and ending with reflections on the implications of the findings. The focus lay on Interface Descriptions, Product Backlog, and Customer Service Requests, and collected relevant characteristics for them.
In each workshop, two researchers took detailed notes of what was being said as well as pictures of the post-it notes. Directly after the meeting, reflections were written down to allow for easier analysis.
3.3 Data Analysis
All collected data was discussed between the researchers in groups. We used coding [18] to identify common themes in the agile islands and boundary objects we collected and structure the information in our transcripts and notes, as well as in the documents we collected from the practitioners. Discussions continued until an agreement about the codes was reached within the group of researchers. All findings were then member checked [8] with the practitioners from whom the data was collected. The final results of these efforts provide the answers to the research questions outlined in Section 1 and are presented in the following. We collected the majority of our boundary objects and islands in the focus group. The follow-up company workshops confirmed the existence of many of these islands and boundary objects, adding only a few new elements, increasing our confidence in our findings as per this set of companies. We demonstrate this process by including our initial overview after the focus group (Fig. 1), a sample picture from the whiteboard after brainstorming with Company A (Fig. 2), and a mindmap with the first draft of results reported in this paper (Fig. 3). In Figure 3, it can be seen that our initial findings were classified as boundary objects and islands, as well as “technological drivers”, “process drivers”, and “organisational drivers”. These findings were refined in several steps to arrive at the final results reported in this paper.
3.4 Threats to Validity
We addressed threats to internal validity by including a number of practitioners in our workshops whenever possible and by allowing them to discuss different perspectives on the data we collected. This increases our confidence that the data which forms the foundation of our study corresponds to the reality at the organisations that participated in it. The positive outcome of member checking our results further compounds this.
In terms of external validity, we do not claim that our findings in terms of the concrete methodological islands and boundary objects we found are complete. By analysing data gathered from different companies with different characteristics, however, we believe that we have sketched out a framework that can be extended in the future and were able to identify relevant categories that are applicable in other contexts. It is our intention to extend the catalogue presented here and create a conceptual model of Boundary Objects and Methodological Islands (BOMI) with higher generalisability in the future.
To mitigate threats to construct validity, we began each workshop with presentations explaining the concept of boundary objects and provided examples to help understanding. The focus group targeted high-level experts from the respective companies. As reflected in their presentations, these experts understood the concepts well. Also, questions were asked and clarifications made throughout the workshops. Thus, all of our data collection tools focused on improving the understanding of the constructs under investigation, i.e., boundary objects and methodological islands. Evaluation apprehension or experimenter expectancies are potential threats to construct validity. Peer debriefing helped us to critically reflect on these potential factors and the impact on our findings. To address reliability, we combine a focus group with individual workshops at
Figure 3: First draft of results of Drivers, Islands and Boundary Objects
companies and combine the data collected in both to derive overall findings.
4 FREQUENTLY ENCOUNTERED AGILE ISLANDS (RQ.1)
In this section, we present our findings with respect to RQ.1 (Which agile islands are repeatedly encountered in large-scale agile contexts?). Overall, the discussion of agile islands resonated very well with our industry participants, both in cross-company workshops and in focus groups with individual companies. When analysing the collected data, we found a wide spectrum of relevant islands that we had to organize and categorize. This led us to two observations: (i) not all islands that were mentioned are in fact agile islands. Thus, there can be significant distance between two agile teams and even the distance between two non-agile teams can have an impact on large-scale agile system development. For this reason, we started to refer to the islands as methodological islands. Thus, there can be significant distance between two agile teams and even the distance between two non-agile teams can have an impact on large-scale agile system development. For this reason, we started to refer to the islands as methodological islands. (ii) not all islands mentioned were on the same level of abstraction. While some (e.g., individual teams) are very concrete, others (e.g., “software vs physical components”) are not very concrete agile islands, but can be seen as contextual factors that cause islands to emerge. We therefore started to refer to the latter as drivers of methodological islands.
We first start to describe concrete methodological islands, before we also share the abstracted drivers.
4.1 Methodological Islands
The islands derived occur on different levels in the organisations. In Table 2 we give an overview of levels and typical examples of islands.
4.1.1 Groups of teams. Two of our participants’ companies implemented the Scaled Agile Framework (SAFe). SAFe suggests the use of Agile Release Trains, i.e., of a team of agile teams that together develop and deliver a solution. Value streams exist on the highest level of SAFe. Within each value stream, there are multiple release trains. In one of the participating companies, there are about 50 release trains with 5 to 12 teams in total. Internally, these agile release trains require synchronisation and coordination, but externally, they can be perceived as a black box. These release trains develop different (sub-)systems that have interfaces with each other. When several release trains depend on each other, their differences in methodology become an obstacle. Officially, departments are not mentioned anymore in the SAFe-related documentation, but have traditionally existed in the companies. Release trains are orthogonal organisations to the former departmental structures and can span several departments in the company.
Product development typically spans several departments in an organisation. These departments, for example, marketing, hardware development, embedded system development, come from different contexts and thus different ways of working. As it was not yet clear how hardware can work in an agile way or if they even should, the hardware teams for instance maintained plan-driven methods and yet they have to interface with software teams that are already adopting agile methods. Hardware and software departments work using different timelines. It is also common for globally distributed companies to have departments spanning different locations that could spur different methods within the department due to the difference in cultures. Each department can have several teams with a common goal of contributing to a single component or feature of the product.
Table 2: Examples of Methodological Islands on different levels.
<table>
<thead>
<tr>
<th>Groups of teams</th>
<th>Agile release trains or scrum-of-scrum clusters may differ in methods.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Departments</td>
<td>Different methods and practices for SW development have emerged in different departments of large system companies (e.g., infotainment, powertrain in automotive)</td>
</tr>
<tr>
<td>Disciplines</td>
<td>Systems engineering needs to combine several disciplines, including hardware, mechanics, and software of different types, each with their own set of methods and practices.</td>
</tr>
</tbody>
</table>
Table 3: Different types of drivers for methodological islands.
<table>
<thead>
<tr>
<th>Drivers</th>
<th>Business-related drivers</th>
<th>Process-related drivers</th>
<th>Technology-related drivers</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Economic function, Characteristics of market or value-chain, global distribution</td>
<td>Mixture of development methods (SAFe, V-Model, Scrum, Kanban, LSD); focus on projects or products</td>
<td>Architectural decomposition, systems disciplines, platform and product-line strategy, time-scale of commitment</td>
</tr>
</tbody>
</table>
4.1 Teams (individual teams). Within an organisation, different teams can follow different agile approaches or even work in an agile way while the rest of the organisation follows a plan-driven approach. Teams in such large companies handle different parts of the architecture of the product. This means that each team works with different requirements and thus could use different approaches to get to the solution. Participants mentioned, for instance, continuous integration framework teams, integration testing teams, Web GUI teams, and software teams. All of these teams may contribute to the same product, but since the nature of their tasks differs significantly, they often tailor development processes to their needs. This leads to a set of methodological islands throughout the organization.
4.1.2 Organizations. Companies work with suppliers, customers and regulators all of which come with different ways of working from that of the corresponding company. The suppliers provide some components while others are developed in-house. When teams within an organisation rely on external suppliers for components, the supplier is often working in a waterfall way. For instance, contracts between both companies often imply a plan-driven approach since purchasing is based on clearly defined functionality to be delivered at a certain point in time. Regulators also rely on standards that do not explicitly specify the methods to use in development, but come with checkpoints that relate mostly to the plan-driven methods of working. This mismatch of the actual methods used versus the ‘unknown’ expectations becomes a hindrance in development.
4.2 Drivers of Methodological Islands
The methodological islands are triggered by certain factors that we derived upon analysis. We summarize these in Table 3 and describe them below.
4.2.1 Business-related drivers. Based on their history and business domain, companies have specialized organisational charts that describe the departments, e.g., for marketing, development, verification. These departments handle different parts of the product that in most cases imply varying needs for development methods. For instance, the sales department as opposed to development departments, have different needs and thus different ways of working. This difference, in turn sparks the need to adopt the agile practices to the context of the specific department, causing islands of methodology, for example, manifesting in different choices with respect to forming cross-functional component or feature teams.
Such business drivers can be the result of a particular culture in a market or value-chain. How is the relationship between customers and suppliers characterised in terms of contracts, time-lines, trust, and interaction? To what extent are customers willing or able to assess and give feedback on frequent deliveries? Is it possible to take end-user opinions into account and to what extent do they matter? All these aspects contribute to the mix of methods and how the other stakeholders are going to work to get the product they need.
Some of our participating companies are distributed over several countries and in some cases different areas in the same country. Developers of software or hardware do not work in the same buildings and are separated by location, time zones and culture. This separation in the end creates teams that have defined different methods of doing the same thing.
4.2.2 Process-related drivers. While teams exist in the organisation and have varying needs, the organisation in the end has to have one backbone process that defines the company. It is not uncommon that different teams within the same organisation use different flavours of agile methods. Apart from process customisation for each individual team, it is possible that some teams use a method such as SAFe while others employ Scrum, Kanban, XP, or
a form of lean development. These differences introduce islands where roles, artefacts, and schedules are difficult to coordinate.
A major driver of this category relates to whether a company mainly works based on projects, or whether significant work flows in the continuous development of a platform. While projects are adding features to a solution and are thus short-term, platforms are planned for the long-term. Platforms need to be more stable since other projects depend on them and changes in the platform can have a major impact on the depending projects. Thus, the particular setup of a company can create islands between different projects, or between customer projects and platform development.
4.2.3 Technology drivers. Complex systems are often developed by different teams that are responsible for individual parts of the architecture. That means that these teams not only address different sets of requirements, but also apply different technologies in their solutions. Teams working on software and on physical components work according to different timelines and according to different cultures. Hardware development often assumes stable requirements and development of a full solution, instead of development of slices of functionality and rapid response to changes.
Many companies with complex product lines, e.g., in the automotive domain, produce platforms as the foundation of their products. Platforms are often generational, i.e., they are used for a certain period of time before they are replaced by the next generation. Each platform has a unique technical solution and is usually not compatible with previous ones. At the same time, different teams working on different platform generations also often use different generation of processes.
The time scale of commitment is another technology-related driver. Agile methods usually imply short-term commitment in individual sprints. That means that requirements can change from sprint to sprint to react to a changing market situation or newly discovered opportunities. On the other hand, many methods require a longer-term commitment. Platforms, e.g., that are used by many other projects and thus need to be stable might be better served using a plan-driven approach and to constitute "waterfall islands" within the organisation.
5 BOUNDARY OBJECTS IN LARGE-SCALE AGILE (RQ.2)
In this section, we answer RQ2: Which boundary objects are repeatedly encountered in large-scale agile contexts?
Table 4 shows our findings for RQ2. Each row represents a type of boundary object with a description of how it facilitates coordination between islands. In total, 19 types of boundary objects were identified. We categorized them in different themes: Task, technology, regulation and standards, product description, process, planning boundary objects, and trace links. We refer to the descriptions of the boundary objects in Table 4 and briefly summarize the categories in the following.
Task boundary objects relate to tasks in the development effort in which boundary objects facilitate the creation of a common understanding across team borders. Concretely, these tasks are concerned with identifying development activities by creating a backlog and specifying requirements to define the functionality to be developed. Typical examples are user stories and other backlog items as well as related comments stored in issue trackers.
Technology boundary objects are concerned with technological aspects of the (software) system to be developed, including a system’s capabilities, tests, or architecture boundary objects. These boundary objects are commonly used between different islands and mostly by technical stakeholders.
Regulation and standards boundary objects are used to ensure that the company complies with regulations and standards. In our case companies, it relates mostly to safety standards, as with the safety assurance case. These regulations and standards are typically relevant across island borders and a common understanding of these concerns is required.
Product description boundary objects relate to the product as it will be sold to the customer. While the respective documentation is mostly created for customers, it can also be leveraged internally, for instance, to create a shared understanding of variability concerns or other technical aspects.
Process boundary objects are concerned with documentation regarding processes or frameworks. In two of our case companies, SAFe is used and tailored to each company’s needs. The created documentation can help to get a shared understanding of the processes and roles.
Planning boundary objects relate to contracts, roadmaps, plans, or budgets that are created before development. These boundary objects are commonly used between non-technical stakeholders like managers, but can also be relevant for development teams.
Trace links are a special category, as they represent the relationships between artefacts. Trace links typically have types that determine how other artefacts relate to each other. They can also serve as boundary objects between different methodological islands, capturing a mutual agreement about relatedness of other boundary objects.
6 DISCUSSION AND CONCLUSION
In this paper, we presented methodological islands and boundary objects related to large-scale systems development collected from two workshops and a focus group with four large organisations. We present a summary of our findings in Figure 4. As the first step towards addressing the coordination challenge in transforming organisations, we believe that this study adds significant value both to research and to other organisations customising agile. We discuss our main findings and implications of our work in this section.
6.1 Methodological Islands
We discuss RQ.1 (Which agile islands are repeatedly encountered in large-scale agile contexts?) in this section.
Our findings show that when embracing agile in large-scale system development, certain types of methodological islands frequently appear on the level of individual teams, groups of teams, or full organisations. Although not particular to large-scale, West et al. [30] found that water-scrum-fall is becoming a reality for most organisations, a claim confirmed by Theocharis et al. [27]. While terming them hybrid methods, Kuhmann et al. [14] find that such hybrid approaches are not limited to traditional and agile development but also allow combinations of different agile methods since agile
Backlog items, e.g., from a product backlog, can be representations of high-level requirements and are used by individual islands to define their own, local backlog items for their product or team backlogs. A user story is an upfront feature description focused on customer value. Backlog items can be formulated as user stories to clarify the value provided by delivering a piece of functionality. A set of high-level requirements can be represented by a feature or function description. These requirements need to be further broken down to allow individual islands to work on them. Different parts of a software architecture are connected by interfaces. The requirements for these interfaces define contracts between teams. For instance, timing requirements on an interface need to be adhered to by all islands using this interface.
The features of a product and the constraints between them (e.g., which ones are mutually exclusive or incompatible) can be shared between islands to avoid regressions, ensure customer value is jointly achieved, and to document the functionality provided in the system. The description of the interfaces between different parts of the solutions allow to modularise the development and different islands to reuse existing assets. A high-level description of the architecture both allows different islands to identify where a feature should be located and ensures that new additions to the solution follow the common guidelines of the organisation.
Integration, acceptance, and non-functional tests can be shared between islands to avoid regressions, ensure customer value is jointly achieved, and to document the functionality provided in the system. The description of the interfaces between different parts of the solutions allow to modularise the development and different islands to reuse existing assets. A high-level description of the architecture both allows different islands to identify where a feature should be located and ensures that new additions to the solution follow the common guidelines of the organisation.
### Table 4: Identified boundary objects and their categories.
<table>
<thead>
<tr>
<th>Task Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Backlog item</td>
<td>Backlog items, e.g., from a product backlog, can be representations of high-level requirements and are used by individual islands to define their own, local backlog items for their product or team backlogs.</td>
</tr>
<tr>
<td>(User) story</td>
<td>A user story is an upfront feature description focused on customer value. Backlog items can be formulated as user stories to clarify the value provided by delivering a piece of functionality.</td>
</tr>
<tr>
<td>Feature, function description, or high-level requirements</td>
<td>A set of high-level requirements can be represented by a feature or function description. These requirements need to be further broken down to allow individual islands to work on them.</td>
</tr>
<tr>
<td>Requirements on interfaces</td>
<td>Different parts of a software architecture are connected by interfaces. The requirements for these interfaces define contracts between teams. For instance, timing requirements on an interface need to be adhered to by all islands using this interface.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Technology Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Capabilities</td>
<td>A description of the capabilities provided by the system gives a high-level overview of the functionality. It allows individual teams to identify relevant reusable assets and required interfaces.</td>
</tr>
<tr>
<td>Automated tests</td>
<td>Integration, acceptance, and non-functional tests can be shared between islands to avoid regressions, ensure customer value is jointly achieved, and to document the functionality provided in the system.</td>
</tr>
<tr>
<td>API / Interface</td>
<td>The description of the interfaces between different parts of the solutions allow to modularise the development and different islands to reuse existing assets.</td>
</tr>
<tr>
<td>Reference architecture</td>
<td>A high-level description of the architecture both allows different islands to identify where a feature should be located and ensures that new additions to the solution follow the common guidelines of the organisation.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Regulation and Standards Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Standards</td>
<td>Safety standards such as ISO 26262, DO-178B, or IEC 62304, prescribe development practices and artefacts.</td>
</tr>
<tr>
<td>Regulations</td>
<td>Regulations take the role of standards and prescribe certain practices or artefacts (e.g., in the telecommunications domain).</td>
</tr>
<tr>
<td>Safety assurance case</td>
<td>Safety standards prescribe the creation of white box or black box safety assurance cases that describe how a product addresses risks during its operation. These cases can be used by different islands to understand the risks involved in the system and to develop common strategies to avoid them or deal with them.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Product Description Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Variability model</td>
<td>The features of a product and the constraints between them (e.g., which ones are mutually exclusive or incompatible) can be used by different islands to understand the interaction between their solutions and the rest of the product line.</td>
</tr>
<tr>
<td>Technical documentation for customer</td>
<td>Outwards-facing documentation can also be used internally to gain a common understanding of how different parts of a system are related.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Process Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>SAFe documentation</td>
<td>The Scaled Agile Framework (SAFe) has found widespread adoption in large development organisations. It provides detailed documentation and support for its adoption. This documentation can, together with a description of how SAFe was adapted, act as a boundary object between islands using SAFe and other parts of the organisation not using SAFe.</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Planning Boundary Objects</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Contracts</td>
<td>The interactions between parts of an organisation and the suppliers are often defined by contracts. Contracts can also bind an island within an organisation to external constraints. In any case, the content of the contract will define the scope or the time and resources the island has at its disposal.</td>
</tr>
<tr>
<td>Roadmaps</td>
<td>The long-term evolution of a product is often defined by one or several roadmaps. These boundary objects also link different products that co-evolve to each other. Therefore, they are used to coordinate between islands within an organisation.</td>
</tr>
<tr>
<td>Short-term plans</td>
<td>The development of individual features or smaller parts of a product is often bound to a shorter-term plan that is connected to the overall, long-term plan. As such, the scope of a short-term plan is also limited to a smaller number of islands.</td>
</tr>
<tr>
<td>Resource budgets</td>
<td>When developing systems in which software runs on dedicated hardware, individual islands need to work with a resource budget that determines how much computing power, memory, or bandwidth their specific functionality can consume.</td>
</tr>
<tr>
<td>Trace links</td>
<td>Artefacts created during development need to be connected to each other using trace links. They clarify the relationship between artefacts and enable change impact analysis and collaboration between the islands that created the artefacts.</td>
</tr>
</tbody>
</table>
is also not implemented as is. Tell et al. [26] go a step further and identify the agile methods and how they are combined in practice to form hybrid methods. Our findings on methodological islands confirm their findings as well as recognising that such combinations differ within the same organisation, causing methodological islands. Such islands are characterised by their relative distance in terms of methods and practices as well as culture and mindset.
In addition to the methodological islands, we found that certain drivers (business-, process-, and technology-related) can introduce such distance and lead to the formation of methodological islands. This finding concurs, to some extent, with the finding by
Figure 4: Summary of findings: Certain drivers introduce distance, which in turn frequently introduces methodological islands on different levels. Boundary objects of various types can be crucial to bridge between islands and support effective agile system development at scale.
Vijayasarathy and Butler [29] who found specific organisational, project and team characteristics had an effect on the choice of methodology. While we can confirm several of those characteristics, we come from the perspective of islands and classify the drivers as business-related, technology-related and process-related. Team characteristics could play a role but for the islands context, these are overtaken by e.g., the nature of (sub-)systems that different teams may be developing and thus we relate that driver to technology.
6.2 Boundary Objects
In this section, we discuss the findings of RQ2: Which boundary objects are repeatedly encountered in large-scale agile contexts?
In order to successfully introduce agile methods and to deliver a full product or system, we found that effectively bridging between such islands is crucial. We believe that it is beneficial to think about artefacts that support such bridging as boundary objects and provide in this paper an inventory of frequently encountered boundary objects. Many of the identified boundary objects have been confirmed by related studies. In an analysis of boundary objects in distributed agile teams including developers and user-centered design specialists, Blomkvist et al. identified the following boundary objects: (1) Personas, (2) Scenarios, (3) Effect maps, (4) Sketches, (5) Design Specifications, (6) Prototypes, (7) Evaluation summaries, and (8) User stories [5].
Our findings include a System Wiki boundary object, identified by company A. Similarly, Yang et al. [33] name the use of a wiki as a boundary object for requirements engineering. The accessibility and ability to simultaneously access and create information make wikis a suitable form for a boundary object.
In an analysis of boundary-spanning activities with a focus on requirements engineering practices for product families, examples boundary objects included traceability documentation, process models, vocabularies, user stories, product/process repositories, XP practices, feature models, the product backlog, the sprint backlog, and product prototypes [11].
In the area of requirements engineering, another study has focused on classification schemes as boundary objects, allowing stakeholders to categorise requirements in different ways (main users, functional vs. non-functional, level of abstraction) [10]. In fact, standardised forms and classification schemes have been examined in the context of boundary objects since their initial definition [6, 25]. The regulation and standards boundary objects that we identified in this study relate to this category. Moreover, process boundary objects potentially include classification schemes, for instance, by defining requirements information models that determine how stakeholders should work with requirements-related concerns and how they should be categorised [31].
Focusing on software development, project management documents and specifications have also been identified as boundary objects [2]. Thus our findings confirm many existing objects, and create a more integrated, industry-driven view of such objects in a large-scale agile context.
6.3 Implications for practitioners
We found our inventory of methodological islands and related boundary objects useful when discussing potential process improvements with companies. Already the focus group and company workshops showed that this facilitates a useful mindset, where artefacts are discussed as a means to satisfy coordination needs between methodological islands. By making the islands explicit and by discussing their particular context, mindset, and preference with respect to methods and practices, we believe that such boundary objects can be established in a better way than if they would emerge in an unplanned way, e.g., by re-using non-agile artefacts. Future work should investigate if this can be used constructively, when defining or improving processes, methods, and tools.
6.4 Implications for research
Similarly, we hope that charting the landscape of methodological islands and boundary objects in large-scale agile system development will create a useful model to scope and prioritize future research. Future research could refine the classifications in our inventory and provide a suitable conceptual model or taxonomy. We are currently working with our participating companies to derive possible recommendations and best practices for boundary objects based on their properties. In addition, a quantitative study could provide additional information on which boundary objects and methodological islands are most frequent.
ACKNOWLEDGMENTS
This work is partially funded by Software Center, Project #27 “RE for Large-Scale Agile System Development” www.software-center.se and the Sida/BRIGHT project 317 under the Makerere-Sida bilateral research programme 2015-2020. We thank our industry partners for their enthusiasm and support.
REFERENCES
|
{"Source-Url": "https://research.chalmers.se/publication/523184/file/523184_Fulltext.pdf", "len_cl100k_base": 9192, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 33024, "total-output-tokens": 12292, "length": "2e13", "weborganizer": {"__label__adult": 0.0003292560577392578, "__label__art_design": 0.00033545494079589844, "__label__crime_law": 0.0002560615539550781, "__label__education_jobs": 0.0022296905517578125, "__label__entertainment": 5.358457565307617e-05, "__label__fashion_beauty": 0.0001665353775024414, "__label__finance_business": 0.0008149147033691406, "__label__food_dining": 0.0003006458282470703, "__label__games": 0.00045943260192871094, "__label__hardware": 0.0006480216979980469, "__label__health": 0.0004346370697021485, "__label__history": 0.00031757354736328125, "__label__home_hobbies": 8.845329284667969e-05, "__label__industrial": 0.0004379749298095703, "__label__literature": 0.0002770423889160156, "__label__politics": 0.00026488304138183594, "__label__religion": 0.0003414154052734375, "__label__science_tech": 0.01482391357421875, "__label__social_life": 0.00010526180267333984, "__label__software": 0.005977630615234375, "__label__software_dev": 0.97021484375, "__label__sports_fitness": 0.0002665519714355469, "__label__transportation": 0.0005283355712890625, "__label__travel": 0.0002112388610839844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57913, 0.02393]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57913, 0.3475]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57913, 0.93222]], "google_gemma-3-12b-it_contains_pii": [[0, 608, false], [608, 5051, null], [5051, 10716, null], [10716, 15856, null], [15856, 20519, null], [20519, 24294, null], [24294, 29441, null], [29441, 35949, null], [35949, 44219, null], [44219, 48463, null], [48463, 57913, null]], "google_gemma-3-12b-it_is_public_document": [[0, 608, true], [608, 5051, null], [5051, 10716, null], [10716, 15856, null], [15856, 20519, null], [20519, 24294, null], [24294, 29441, null], [29441, 35949, null], [35949, 44219, null], [44219, 48463, null], [48463, 57913, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57913, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57913, null]], "pdf_page_numbers": [[0, 608, 1], [608, 5051, 2], [5051, 10716, 3], [10716, 15856, 4], [15856, 20519, 5], [20519, 24294, 6], [24294, 29441, 7], [29441, 35949, 8], [35949, 44219, 9], [44219, 48463, 10], [48463, 57913, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57913, 0.19588]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
2c5e25a1e4dc4198cbf036326688fcaf688eb4ce
|
Fast Formal Analysis of Requirements via “Topoi Diagrams”
Tim Menzies
Dept. Electrical & Computer Eng.
University of British Columbia,
2356 Main Mall, Vancouver, B.C.
Canada, V6T 1Z4
tim@menzies.com
John Powell
Averstar Inc.
NASA IV&V Facility
100 University Drive,
Fairmont WV, USA, 26554
john.powell@ivv.nasa.gov
Michael E. Houle
Basser Dept. of Computer Science
Madsen Building F09
The University of Sydney
Sydney, NSW, Australia, 2006
meh@cs.usyd.edu.au
ABSTRACT
Early testing of requirements can decrease the cost of removing errors in software projects. However, unless done carefully, that testing process can significantly add to the cost of requirements analysis. We show here that requirements expressed as topoi diagrams can be built and tested cheaply - using our SP2 algorithm, the formal temporal properties of a large class of topoi can be proven very quickly, in time nearly linear in the number of nodes and edges in the diagram. There are two limitations to our approach. Firstly, topoi diagrams cannot express certain complex concepts such as iteration and sub-routine calls. Hence, our approach is more useful for requirements engineering than for traditional model checking domains. Secondly, our approach is better for exploring the temporal occurrence of properties than the temporal ordering of properties. Within these restrictions, we can express a useful range of concepts currently seen in requirements engineering, and a wide range of interesting temporal properties.
Keywords
Formal methods, requirements engineering, model checking, SP2.
1 INTRODUCTION
The case for more formality in requirements engineering is overwhelming. Many errors in software can be traced back to errors in the requirements [32]. Often, the conception of a system is improved as a direct result of the discovery of inadequacies in the current conception. The earlier such inadequacies are found, the better, since the cost of removing errors at the requirements stage can be orders of magnitude cheaper than the cost of removing errors in the final system [33].
The benefit of formally checking a system is that formal proofs can find more errors than standard testing. A single formal first-order query is equivalent to many white-box or black-box test inputs [19].
The cost of rigorous requirements engineering may be impractically high. These costs include:
The modeling cost: Analysts must create a systems model and a properties model. Both models are in some machine-readable form. The properties model is often much smaller than the systems model and contains a formal temporal logic1 description of the invariants that must be proved in the systems model.
The execution cost: A rigorous analysis of formal properties implies a full-scale search through the systems model. For example, if a given systems model has n variables each of which may take on a finite number of unique values m, then the size of the state space associated with that model is \( m^n \). This space can be too large to explore, even on today’s fast machines. Despite extensive research into speeding up this search (see our Related Work section), analysts often have to painstakingly rework the systems and properties models into more abstract and succinct forms that are small enough to permit formal analysis.
The personnel cost: Analysts skilled in formal methods must be recruited or trained. Such analysts are generally hard to find and retain.
The development brake: The above costs can be so high that the requirements must be frozen for some time while we perform the formal analysis. Hence, one of the costs of formal analysis is that it can slow the requirements process. Slowing down the requirements process is unacceptable for fast moving software companies, such as the start-up dot.coms.
Ideally, a method for reducing the cost of testing requirements would eliminate the execution cost and reduce the cost and skill involved in building the properties and systems models. If achievable, such a method would also reduce the personnel cost, since it would not require such highly-skilled analysts. Having reduced the personnel, modeling, and execution costs, this hypothetical method would inevitably decrease the development brake.
Some progress has already been made in reducing the cost of properties modeling using temporal logic patterns. Dwyer et.al. [9, 10] have identified patterns within the temporal logic
\[ \Box X \text{ (always } X \text{ is true)}, \; \Diamond X \text{ (eventually } X \text{ is true)}, \; \bigcirc X \text{ (} X \text{ is true at the next time point)}, \; X \cup Y \text{ (} X \text{ is true until } Y \text{ is true)} \]
The formal semantics for topoi is described below. Informally, we say that + approximates “encourages” while − approximates “discourages”.
formulae seen in many real-world properties models. For each pattern, they have defined an expansion from the intuitive pseudo-English form of the pattern to a formal temporal logic formulae. In this way, analysts are shielded from the complexity of formal logics. For example, the simple pseudo-English statement
always (brake = on) between (danger = seen) and (car = stop)
can be automatically expanded into the more arcane formal statement:
\[ \Box ((\text{danger} = \text{seen}) \land \neg (\text{car} = \text{stop}) \land \Diamond (\text{car} = \text{stop})) \rightarrow (\text{brake} = \text{on} \lor (\text{car} = \text{stop})) \]
One drawback with temporal logic patterns is that while complex temporal formulae can be automatically generated from intuitive pseudo-English, the execution cost remains. That is, even though we can quickly build the properties model, we may not be able to execute all of that properties model.
In this article, we argue that we can greatly reduce the execution cost for a class of systems models seen in the requirements stage, and for a large class of temporal logic properties. In our approach, we use temporal logic patterns to reduce the cost of properties modeling, and optimization to reduce the execution cost. The key to this reduction is SP2, a new algorithm for testing temporal properties of topoi, which are statements of gradual influences between variables. Topoi can represented graphically by topoi diagrams, an example of which is shown in Figure 1. Topoi are quick to sketch, and so (for requirements that are topoi-compatible) our approach also reduces the systems modeling cost.
These cost-reduction benefits can only be realized if we accept certain restrictions:
- Our approach limits the kinds of properties that can be tested.
- The systems model must be expressed as topoi diagrams. Topoi are not very expressive and excludes statement such as first-order assertions, iteration, subroutine calls, and assignment.
- Due to these language limitations, our approach is not suitable to domains that need the excluded statements; e.g. complex protocols seen in concurrent processes.
These restrictions are not fatal to the modeling process, at least at the requirements stage:
- We will describe how to quickly recognize inadmissible properties statements. Further, we will use the Dwyer et.al. survey to show that within the limits to the properties language, we can represent a wide range of useful temporal logic properties.
- We will show that topoi diagrams are sufficient to represent diagrams seen in certain approaches to requirements engineering and recording design rationales. Hence, when we say that this approach is practical and useful, we really mean practical and useful for early life cycle requirements discussions only.
This worked is based on Feldman & Compton’s study of the validation of topoi [11, 12] (which they called qualitative compartmental models). Menzies tried to optimize that validation process and offered an implementation that was orders of magnitude faster than the validation engine built by Feldman & Compton. However, he could not reduce the exponential upper-bound on the runtimes [21–23]. Assuming a certain restriction on topoi edge types, Cohen, Menzies, Waugh and Goss showed that the cost of checking temporal properties of topoi-based simulation is a function of the
number of time-ticks in the query [24, 25]. This paper improves significantly on the Menzies et.al. result. We assume the same restriction as Menzies et.al. and introduce SP2, a nearly linear-time algorithm for checking a large class of interesting temporal properties (for space reasons, we describe the full details of that algorithm elsewhere [27]). Also, we describe an implementation of SP2 which, in at least one domain, out-performs a state-of-the-art temporal logic model checker (SPIN [15]).
2 About Topoi
Our approach assumes that requirements systems models are expressed in the form of topoi; i.e. statements of gradual statements such as (i) the more X, the more Y; (ii) the less X the less Y; (iii) the more X, the less Y; or (iv) the less X the less Y. Dieng et.al. name such statements “topoi” and give numerous examples from their records of interviews with experts [7]. For example:
The more there is water infiltration in the roadway body, the worse the foundation risks to be.
The higher the speed of the vehicles, the more important the measure of importance relative to the roadway comfort.
When the geometry increases, the mass increases and the frequency decreases.
If there is a punctual undressing and if the roadway is between five and fifteen years old, then the causes "too old coating" is all the more certain since the roadway is older.
Our experience has always been that the systems modeling cost with topoi is very low. Topoi graphs can be quickly generated in the requirements stage. Two feuding stakeholders with two marker pens and one whiteboard can generate many, many topoi in just a few hours.
Topoi graphs can be found in many domains. Figure 1 showed a topoi from an insurance domain using the graphical notation of Dieng’s 3DKAT tool. Figure 2 show some Mylopoulos-style soft-goal graphs [28,29]. Soft-goal graphs represent gradual knowledge about non-functional requirements. In Figure 2, an expert describes how to increase business flexibility. Figure 3 shows a “questions-options-criteria” (QOC) graph from the design rationale community [34]. In such QOC graphs, questions suggest options and deciding on a certain option can raise other questions. Options shown in a box denote selected options. Options are assessed by criteria and criteria are gradual knowledge; i.e. they tend to support or tend to reject options. QOCs can succinctly summarize lengthy debates; e.g. 480 sentences uttered in a debate between two analysts on interface options can be displayed in a QOC graph on a single page [20]. Figure 5 shows topoi generated from the requirements of a rule-based legal system, shown in Figure 4. This translation assumes that propositions in the rule base are modeled as a belief/strength pair where the strength is some continuous number.
When collected from multiple stakeholders, gradual statements can be quite complex, quite large, and contain feedback loops. Smythe extracted a list of gradual influences...
Figure 4: Rule-based requirements from a legal system.
age<7
+
infant
-
legally
responsible
touch
Figure 5: Topoi from Figure 4.
coldSwim
+
nna
dex
temp
Figure 6: The Smythe '87 theory. From [35]. The diagram shows statements of gradual knowledge relating to laboratory experiments on mammals.
from a set of articles from different authors relating to human internal physiology. The resulting network contains loops; see Figure 6. The experiments described later in the paper are based on the large topoi of Figure 7.
A pre-experimental concern is that informal topoi are so under-defined that we could use them to infer any properties at all. This turns out not to always be the case. Recall Figure 2 and the fragment:
usability → flexibility ← performance
Note that there is no way to explain the output of \{flexibility \} from the input of \{usability \, performance \}. That is, while topoi are over-generalized, they may still be restrictive enough to demonstrate what cannot be proved. We describe below experiments which show that large real-world topoi can be restrictive enough to block an interesting number of temporal properties.
**Topoi: Formal Semantics**
Formally, we say that a topoi is a directed, possibly cyclic graph \( G \) containing vertices and edges \( < V, E > \). \( E \) are the connectors between variables and are one of a set of pre-
defined types; e.g. \( \vdash \) or \( \rightarrow \). That is:
\[
E_i = V_i \vdash V_j \text{ or } V_i \rightarrow V_j
\]
\[
G = < V, E >
\]
The vertices of a toposi can be assigned a finite number of values; e.g.\( \uparrow \), \( \downarrow \) or steady. These values model the sign of the first derivative of these variables (i.e. the rate of change in each value). \( X \vdash Y \) denotes that \( Y \) being \( \uparrow \) or \( \downarrow \) could be explained by \( X \) being \( \uparrow \) or \( \downarrow \) respectively.
That is:
\[
V_i \vdash V_j \equiv \{ V_i \uparrow \implies V_j \uparrow \}
\]
(1)
(\text{where } \uparrow \text{ and } \downarrow \text{ denote up and down respectively.)}
\( X \rightarrow Y \) denotes that \( Y \) being \( \uparrow \) or \( \downarrow \) could be explained by \( X \) being \( \uparrow \) or \( \downarrow \) respectively.
That is:
\[
V_i \rightarrow V_j \equiv \{ V_i \uparrow \implies V_j \downarrow \}
\]
(2)
Tacit in our toposi diagrams are conjunctions of influences. We can view toposi as influences splashing around pipes that connect tubs. Pairs of competing influences can cancel out. That is, we can explain the level of water in a tub remaining steady via conjunction of competing upstream influences; e.g.
\[
\left( (V_i \uparrow \implies V_j \uparrow) \text{ and } (V_k \downarrow \implies V_j \downarrow) \right) \implies (V_j \text{ is steady})
\]
(3)
This formal semantics is sufficient to guide the translation of toposi for a formal model checker such as SPIN. Figure 8 shows the results of such a translation of Figure 6. In this figure, all the nodes have the values \( \uparrow \), \( \downarrow \), steady and unknown (which is a placeholder for the initial conditions). Also, for convenience, all systems model inputs \( X \) are declared to be \( X_{\text{chg}} \) variables with values \( \text{arrived, left} \) denoting the differences between these variables in different experiments. For example, if we increase the injections of \( \text{dex} \), then we also say that \( \text{dex}_X = \text{arrived} \).
Proving Formal Properties in Toposi
We can test toposi using libraries of expected or desired behavior. Such libraries can be quickly built via interviews with users. We have found it useful to structure these interviews in an OO framework. After generating use cases and particular scenarios [18], we ask our users to clarify exactly what are the expected inputs and required outputs for each scenario. This generates two artifacts. Firstly, it leads to toposi graph describing how they think influences should propagate around a systems model. Secondly, it leads to the formulation of properties models of the form:
\begin{quote}
When I do this, I expect to see that.
\end{quote}
Figure 8: Figure 6 expressed in the PROMELA language used in SPIN model checker [15].
or, in the language of temporal logic used in (e.g.) SPIN:
\[
\Box (\text{Inputs} \rightarrow \Diamond \text{ Outputs})
\]
(4)
i.e. always the \text{inputs} lead, eventually, to the \text{outputs}.
We encounter problems if we use Equation 4 to check large toposi using standard model checkers. While SPIN checks Equation 4 against Figure 8 in less than a second, it can fail to terminate for larger systems models. In one study, we offered 40 properties of the form of Equation 4 to SPIN along with Figure 7 expressed in the same format as Figure 8. Given 100MB of maximum RAM, SPIN ran out of memory for most of the properties. We suspected that the search space was too big. Figure 7 contains 80 variables, each of which has at least the values \( \uparrow \), \( \downarrow \), steady, \( \text{undef} \); i.e. total space of options at least of size \( (4^{30} \approx 10^{48}) \). In a second study, we reduced the size of the system by removing the steady values. This shrank the options to \( (3^{30} \approx 10^{38}) \). However, even in this reduced system, SPIN ran out of memory and failed to prove anything for 29 of the 40 proper-
ties [31].
In summary, while theoretically we can assess topoi using standard model checkers, in practice, this may not be feasible.
3 SP2: A Model Checker for Topoi
While general topoi defeat general-purpose model checkers, specialized model checkers can quickly check the temporal properties of a restricted class of topoi. Consider a topoi containing two-valued nodes connected by the “+” and “-” edges defined in Equation 1 and Equation 2. Such a topoi has symmetric edges; i.e., each edge comments on a connection of every upstream node’s value to every downstream node’s value. Menzies et. al. showed that when every edge of a symmetric topoi comments on all the values of its downstream vertices, then the state space rapidly saturates [24, 25]. That is, the granularity of the time axis reduces to the number of variables in that theory. For example, in a systems model where every variable has only two values, everything that is reachable can be reached in two time ticks.
Using the result of Cohen et. al we have defined SP2, a specialized model checker for symmetric topoi [27, 31]. SP2 is a variant of Dijkstra’s shortest path algorithm [6, 8]. The algorithm inputs a symmetric topoi with edge set E, node set V, and an initial set S ⊆ V. S contains some value assignments to some nodes and represents the initial conditions of the system. The algorithm outputs a set of edges Z with the following properties:
- Z is a collection of trees spanning all the nodes reachable from the inputs.
- For any reachable node z, Z contains the shortest topoi path from the inputs to z.
- The nodes of V spanned by Z are partitioned into two sets S' and T', where:
- No edge of Z passes from T' to S'.
- Each set is consistent; that is, will not contain both x ⊢ and x ⊣.
Elsewhere, we have proved that SP2 generates S' and T' correctly, and runs in O(|V| + |E| log |V|) time in the worst case [27]. SP2 is efficient due to its exploitation of saturation. While spreading out over the topoi, it maintains two sets of nodes: the now set (S') and the later set (T'). If the algorithm reaches a node that contradicts something else in the now, it moves the new node into the later set. The repeated application of this rule on a 2-paced symmetric topoi results in a fast division of the nodes reachable from the initial conditions into the two sets S' and T'.
Using SP2, we can very quickly explore temporal properties that can be proved in two time ticks. A large range of interesting queries can be executed in two time ticks (but see below for a discussion on the properties that require more than two time ticks). Once S' and T' are generated, we can convert our temporal properties into set membership tests of these sets. Figure 9 and Figure 10 show conversion rules for common temporal properties.
SP2 offers two major other advantages over standard temporal reasoning:
1. SP2 runs, terminates, returns Z, and then we perform set membership of Z to prove our properties. That is, we do not test for properties till after SP2 terminates. Hence, the inference time is not much affected by the complexity of the properties to be tested.
2. SP2 uses a shortest-paths tree to build its proofs. That is, when explaining how properties were reached, SP2 will generate the shortest explanation possible. Hence, a user of SP2 need not wade through mountains of trace files in order to understand how the properties were proved.
Experiments with SP2
Figure 11 shows a comparison of SPIN vs SP2 using properties of the form of Equation 4 and the systems model of Figure 7. Of the 40 properties which were analyzed by both SPIN and SP2, SPIN was able to return a verification result in only 11 out of 40 cases (27.5%) before running out of memory. In every case where SPIN did return a verification result, SP2’s result was in agreement.
Regarding computer resources, SP2 used less than 1% of the RAM required by SPIN. Also, in the case of the unprovable properties, SP2 terminated in less than a second CPU time while SPIN took much longer.
Figure 10: Common temporal logic queries converted into set membership tests of SP2's $S', T'$. This table was generated by applying the re-write rules of Figure 9 to a survey of common temporal logic queries [9, 10]. From [31].
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$\Box (p)$</td>
<td>$p \in S' \land p \in T'$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$\Box R \rightarrow (p \cup [l</td>
<td>R])$</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Box (p)$</td>
<td>$(Q \in S' \land (Q \in T' \land p \in S' \land p \in T') \land (Q \in S' \land p \in T') \land (Q \in T' \land p \in S')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (p \cup [l</td>
<td>R])) \lor (Q \land R \land Q \rightarrow (p \cup [l</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Box R \rightarrow (p \cup [l</td>
<td>R])$</td>
</tr>
</tbody>
</table>
Figure 10.A: Absence properties: $p$ is false
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$\Diamond (p)$</td>
<td>$p \in S' \land p \in T'$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$I R \rightarrow (\neg p \cup [l</td>
<td>R])$</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Diamond (p)$</td>
<td>$R \in S' \land (R \in T' \land p \in S' \land p \in T')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (\neg p \cup [l</td>
<td>R])) \lor (Q \land R \land Q \rightarrow (\neg p \cup [l</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Diamond R \rightarrow (\neg p \cup [l</td>
<td>R])$</td>
</tr>
</tbody>
</table>
Figure 10.B: Existence properties: $p$ becomes true
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$p$</td>
<td>$p \in S' \land p \in T'$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$I R \rightarrow (p \cup [l</td>
<td>R])$</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Diamond (p)$</td>
<td>$R \in S' \land (R \in T' \land p \in S' \land p \in T')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (p \cup [l</td>
<td>R])) \lor (Q \land R \land Q \rightarrow (p \cup [l</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Diamond R \rightarrow (p \cup [l</td>
<td>R])$</td>
</tr>
</tbody>
</table>
Figure 10.C: Universality: $p$ always true
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$\Diamond (p)$</td>
<td>$p \in S' \land p \in T'$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$I R \rightarrow (\neg p \cup [l</td>
<td>R])$</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Diamond (p)$</td>
<td>$R \in S' \land (R \in T' \land p \in S' \land p \in T')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (\neg p \cup [l</td>
<td>R])) \lor (Q \land R \land Q \rightarrow (\neg p \cup [l</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Diamond R \rightarrow (\neg p \cup [l</td>
<td>R])$</td>
</tr>
</tbody>
</table>
Figure 10.D: Precedence: $S$ precedes $p$
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$p S$</td>
<td>$p \in S' \land p \in T'$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$I R \rightarrow (p \cup [l</td>
<td>S</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Diamond (p)$</td>
<td>$R \in S' \land (R \in T' \land p \in S' \land p \in T')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (p \cup [l</td>
<td>S</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Diamond R \rightarrow (p \cup [l</td>
<td>S</td>
</tr>
</tbody>
</table>
Figure 10.E: Response: $S$ responds to $p$
<table>
<thead>
<tr>
<th>Property</th>
<th>LTL</th>
<th>SP2</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Globally</strong></td>
<td>$p \rightarrow (\circ S)$</td>
<td>$\circ S \rightarrow (p \circ T \land p \circ S)$</td>
</tr>
<tr>
<td><strong>Before R</strong></td>
<td>$I R \rightarrow (p \rightarrow (\circ R \cup [l</td>
<td>S</td>
</tr>
<tr>
<td><strong>After Q</strong></td>
<td>$Q \rightarrow \Diamond (p)$</td>
<td>$R \in S' \land (R \in T' \land p \in S' \land p \in T')$</td>
</tr>
<tr>
<td><strong>Between Q and R</strong></td>
<td>$((Q \land R \land Q \rightarrow (p \rightarrow (\circ R \cup [l</td>
<td>S</td>
</tr>
<tr>
<td><strong>After Q until R</strong></td>
<td>$Q \rightarrow \Diamond R \rightarrow (p \rightarrow (\circ R \cup [l</td>
<td>S</td>
</tr>
</tbody>
</table>
We mentioned earlier that one pre-experimental concern with informal topoi is that they are so under-defined that we could use them to infer any set of properties at all. Figure 11 shows that this is not always true. In the case of 8 of the 40 properties, SP2 could not prove them across the large under-defined topoi of Figure 7.
Limits to SP2
What are the practical implications of SP2's restrictions? We discuss below two important implications: restrictions of the property that can be proved and the need for special tools to handle conjunctions.
Inadmissible Properties
Figure 12 shows Dwyer et.al.'s classification of over five hundred linear temporal logic (LTL) properties [9,10]. Those properties divide into eight groups and each group contains the five temporal scopes seen in Figure 10; i.e. globally; before event $R$; after event $Q$; events $Q$ and $R$; and after event $22$ of these scopes are expressible in terms $Q$ until event $R$. $22$ of these scopes are expressible in terms of two time ticks [31]. The inexpressible scopes all require proving some ordering of $>2$ events. By definition, such an ordering cannot be expressed using merely the two time intervals of $S'$ and $T'$ generated by SP2.
Figure 12 shows us that SP2-style inference on symmetric topoi can say more about the occurrence of a given event/state during system execution than about the ordering in which multiple events/states occur. It is a simple matter to detect the temporal properties that are inadmissible for SP2. All such properties require more than two time ticks; e.g.
Flexibility is required to ensure the symmetry properties upon which SP2 is dependent. However, they are just nonsense symbols that should never appear in any explanation of how certain inputs lead to certain properties. That is, pathways from inputs to properties should never include these nonsense symbols. Hence, if possible, SP2 should be 'coaxed' into producing shortest path trees in which these spurious nodes appear at the leaves.
SP2 contains a mechanism to implement such coaxing: each edge in the topoi is augmented with an edge weight, which SP2 uses to compute shortest paths—the length of a path is simply the sum of the weights of the edges along the path. At the core of SP2 is a priority queue. At runtime, the next edge to be explored is one of the edges with lowest weight within the queue. This means that by adjusting weights and re-running the algorithm, we can choose to explore edges at some earlier time or later time. Hence, to coax usability↑ and performance↓ into S', we can adjust the weights upstream of those nodes. In coaxing, the weights can be adjusted arbitrarily, provided that the any symmetric pair of edges receives the same weight for both edges. Elsewhere [27] we define a set of minimal edge adjustment heuristics which input SP2's shortest path tree Z, the cut set C containing the edges that connect S' to T' and which outputs changes to the edge weights.
A major pre-experimental concern was that the nearly linear-time processing of SP2 could be followed by an indefinitely long coaxing process. After much experimentation, we can report that we have never seen this worst-case behavior in practice. In those experiments we used SP2 to explore randomly generated properties of the form of Equation 4 over dozens of randomly generated topoi graphs. We varied topoi fanout (2 to 6 edges per node) and the frequency of and-nodes (from 5% to 75%). Each experiment was terminated when the % of provable properties reached some plateau. In all the experiments, the plateau was reached after < 5 iterations of SP2+coaxing. Also, the plateau reached after 10 coaxes barely changed in up to 100 coaxes. Further, SP2 never used more than 1MB of memory or one minute of runtime. Our conclusion from these experiments is that the need for heuristic coaxing does not diminish the time and space efficiency of SP2.
4 Related Work
We are hardly the first to explore formal methods for requirements engineering. For example:
- In the KAOS system [36], analysts generate a properties model by incrementally augmenting object-oriented scenario diagrams with temporal logic statements. Potentially, this research reduces the costs of formal requirements analysis by integrating the generation of the properties model into the rest of the system development. Our reading of the KAOS work is that while the resulting model may be more formal, the level of skill
\[
\text{usability} \rightarrow \text{flexibility} \leftarrow \text{performance}
\]
where \( \text{usability} \uparrow \rightarrow \text{and001} \), \( \text{performance} \downarrow \rightarrow \text{and001} \), and \( \text{and001} \rightarrow \text{flexibility} = \text{steady} \) (5)
Another case where we want to coax edge weights is the bad-and situation. The rules of symmetric topoi require that if we create the edges shown in Equation 5, then we must also create the following complementary rules:
\[
\text{usability} \downarrow \rightarrow \text{and001}
\]
\[
\text{performance} \uparrow \rightarrow \text{and001}
\]
\[
\text{and001} \rightarrow \text{flexibility} = \text{steady}
\] (6)
where \( \overline{X} \) is an invented node representing "all the other values of X". The addition of the nodes \text{and001} and
Figure 12: Coverage of the Dwyer corpus of temporal properties by SP2. Each right-hand-side group of properties contains five scopes. Fractions denote how many of those scopes can be handled by SP2, as seen in Figure 10. Adapted from [31].
until operators nested to a depth greater than two such as:
\[
(\text{day} = \text{Sunday}) \cup (\text{day} = \text{Monday}) \cup \text{day} = \text{Tuesday})
\]
Handling Conjunctions
Another problem is that symmetric topoi have no special knowledge of and-nodes. This can lead to some less-than-desirable results. Consider the following topoi:
\[
\text{usability} \rightarrow \text{flexibility} \leftarrow \text{performance}
\]
Equation 3 says that the conjunction of competing upstream influence can result in a steady value in a downstream variable; i.e.
\[
\text{usability} \uparrow \rightarrow \text{and001}
\]
\[
\text{performance} \downarrow \rightarrow \text{and001}
\]
\[
\text{and001} \rightarrow \text{flexibility} = \text{steady}
\] (5)
where \( \text{and001} \) is an and-node especially created for this conjunction. A reasonable temporal interpretation of and-nodes is that all pre-conditions must appear before or at the same time as the post-conditions. Suppose we seek to
\[
\text{flexibility} = \text{steady} \in S', \text{but SP2 computes a node partition}
\]
in which \( \text{usability} \uparrow \in T' \) and \( \text{performance} \downarrow \in T' \). We would like to be able to coax these pre-conditions back in time to \( S' \) such that they do not occur at a time that is later than
\[
\text{flexibility} = \text{steady} \in S'.
\]
Another case where we want to coax edge weights is the bad-and situation. The rules of symmetric topoi require that if we create the edges shown in Equation 5, then we must also create the following complementary rules:
\[
\text{usability} \downarrow \rightarrow \text{and001}
\]
\[
\text{performance} \uparrow \rightarrow \text{and001}
\]
\[
\text{and001} \rightarrow \text{flexibility} = \text{steady}
\] (6)
where \( \overline{X} \) is an invented node representing "all the other values of X". The addition of the nodes \text{and001} and
\[
\text{flexibility} = \text{steady}
\]
is required to ensure the symmetry properties upon which SP2 is dependent. However, they are just nonsense symbols that should never appear in any explanation of how certain inputs lead to certain properties. That is, pathways from inputs to properties should never include these nonsense symbols. Hence, if possible, SP2 should be 'coaxed' into producing shortest path trees in which these spurious nodes appear at the leaves.
SP2 contains a mechanism to implement such coaxing: each edge in the topoi is augmented with an edge weight, which SP2 uses to compute shortest paths—the length of a path is simply the sum of the weights of the edges along the path. At the core of SP2 is a priority queue. At runtime, the next edge to be explored is one of the edges with lowest weight within the queue. This means that by adjusting weights and re-running the algorithm, we can choose to explore edges at some earlier time or later time. Hence, to coax usability↑ and performance↓ into S', we can adjust the weights upstream of those nodes. In coaxing, the weights can be adjusted arbitrarily, provided that the any symmetric pair of edges receives the same weight for both edges. Elsewhere [27] we define a set of minimal edge adjustment heuristics which input SP2's shortest path tree Z, the cut set C containing the edges that connect S' to T' and which outputs changes to the edge weights.
A major pre-experimental concern was that the nearly linear-time processing of SP2 could be followed by an indefinitely long coaxing process. After much experimentation, we can report that we have never seen this worst-case behavior in practice. In those experiments we used SP2 to explore randomly generated properties of the form of Equation 4 over dozens of randomly generated topoi graphs. We varied topoi fanout (2 to 6 edges per node) and the frequency of and-nodes (from 5% to 75%). Each experiment was terminated when the % of provable properties reached some plateau. In all the experiments, the plateau was reached after < 5 iterations of SP2+coaxing. Also, the plateau reached after 10 coaxes barely changed in up to 100 coaxes. Further, SP2 never used more than 1MB of memory or one minute of runtime. Our conclusion from these experiments is that the need for heuristic coaxing does not diminish the time and space efficiency of SP2.
4 Related Work
We are hardly the first to explore formal methods for requirements engineering. For example:
- In the KAOS system [36], analysts generate a properties model by incrementally augmenting object-oriented scenario diagrams with temporal logic statements. Potentially, this research reduces the costs of formal requirements analysis by integrating the generation of the properties model into the rest of the system development. Our reading of the KAOS work is that while the resulting model may be more formal, the level of skill
required to write the temporal logic can significantly increase the personnel cost. Further, the extra time required for the augmentation could increase the effect of the development brake.
- Schneider et al. [33] explored reducing the manual modeling costs using lightweight formal methods. In the lightweight approach, only partial descriptions of the systems and properties models were constructed using the SPIN formal analysis tool [15]. Despite their incomplete nature, Schneider et al. found that such partial models could still detect significant systems errors. While exciting research, this approach still incurs the personnel cost since scarce expertise is required to drive tools like SPIN.
Nor are we the first to explore optimizing temporal logic model checking. Elaborate tools have been developed to tame the state space explosion problem including:
**Abstraction or partial ordering:** Only use the part of the space required for a particular proof. Implementations exploiting this technique can restrain how the space is traversed [14, 26], or constructed in the first place [13, 33].
**Clustering:** Divide the systems model into sub-systems which can be reasoned about separately [2, 4, 30, 37].
**Meta-knowledge:** Avoid studying the entire space. Instead, only study succinct meta-knowledge of the space. One example used an eigenvector analysis of the long-term properties of the systems model under study [17].
**Exploiting symmetry:** Prove properties in some part of the systems model, then reuse those proofs if ever those parts are found elsewhere in the systems model [3].
**Semantic minimization:** Replace the space with some smaller, equivalent space [16] or ordered binary decision diagrams [1]. For example, the BANDERA system [5] reduces both the systems modeling cost and the execution cost via automatically extracting (slicing) the minimum portions of a JAVA program's bytecodes which are relevant to particular properties models.
While the above tools have all proved useful in their test domains, they may not be universally applicable.
- Certain optimizations require expensive pre-processing, such as [17].
- These methods may rely on certain topological features of the system being studied. Exploiting symmetry is only useful if the system under study is highly symmetric. Clustering generally fails for tightly connected models.
Also, for requirements engineering, systems like BANDERA are not suitable. BANDERA only works on implemented systems; that is, not until long after the requirements phase has ended.
Hence, in the general case, only small models can be tested. Further, these models must be precisely specified. In contrast, this work describes methods for quickly proving properties in large models that have been hastily sketched.
**5 Conclusion**
We need better formal testing for our requirements. Applying formal methods can lead to an unacceptable brake on the development process. Cost-effective formal methods have to reduce the cost and skill involved in modeling systems and their properties. The cost of properties modeling can be reduced via temporal logic patterns. However, the execution cost of the resulting properties model may require expensive rework of the properties generated from the patterns.
In the specific case of requirements that can be mapped into symmetric topoi, we have shown that the systems modeling cost is reduced (since the topoi can be sketched quickly). For such symmetric topoi, we can reduce the execution cost for proving formal properties to time that is nearly linear on the number of edges and nodes in the topoi.
The combination of easy specification of properties and systems models implies that the personnel cost of formal modeling is reduced. This cost-reduction can only be achieved in domains were the systems model can be expressed as topoi and the properties model refers more to temporal occurrence properties than temporal ordering properties. We have argued that requirements engineering is one such domain.
Having built the SP2 engine, our next goal is the construction of a shell that exploits this engine. Our current research goal is the construction of the RAPTURE shell. RAPTURE exploits SP2 to enable the fast formal analysis of topoi-compliant descriptions of software systems.
**ACKNOWLEDGEMENTS**
This work was partially supported NASA through cooperative agreement #NCC 2-979.
**REFERENCES**
|
{"Source-Url": "https://ntrs.nasa.gov/api/citations/20010106110/downloads/20010106110.pdf", "len_cl100k_base": 9876, "olmocr-version": "0.1.50", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 36590, "total-output-tokens": 13156, "length": "2e13", "weborganizer": {"__label__adult": 0.0003843307495117187, "__label__art_design": 0.000598907470703125, "__label__crime_law": 0.0004096031188964844, "__label__education_jobs": 0.0018177032470703125, "__label__entertainment": 0.00011682510375976562, "__label__fashion_beauty": 0.00023567676544189453, "__label__finance_business": 0.0006513595581054688, "__label__food_dining": 0.0004203319549560547, "__label__games": 0.0007243156433105469, "__label__hardware": 0.001071929931640625, "__label__health": 0.0006742477416992188, "__label__history": 0.0004148483276367187, "__label__home_hobbies": 0.0001456737518310547, "__label__industrial": 0.0006737709045410156, "__label__literature": 0.000553131103515625, "__label__politics": 0.0003390312194824219, "__label__religion": 0.0005402565002441406, "__label__science_tech": 0.1473388671875, "__label__social_life": 0.00014400482177734375, "__label__software": 0.01020050048828125, "__label__software_dev": 0.8310546875, "__label__sports_fitness": 0.00029921531677246094, "__label__transportation": 0.0008115768432617188, "__label__travel": 0.00023031234741210935}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47388, 0.02522]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47388, 0.53795]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47388, 0.84953]], "google_gemma-3-12b-it_contains_pii": [[0, 4703, false], [4703, 8228, null], [8228, 11207, null], [11207, 12600, null], [12600, 16624, null], [16624, 20675, null], [20675, 27691, null], [27691, 36510, null], [36510, 41805, null], [41805, 47388, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4703, true], [4703, 8228, null], [8228, 11207, null], [11207, 12600, null], [12600, 16624, null], [16624, 20675, null], [20675, 27691, null], [27691, 36510, null], [36510, 41805, null], [41805, 47388, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47388, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47388, null]], "pdf_page_numbers": [[0, 4703, 1], [4703, 8228, 2], [8228, 11207, 3], [11207, 12600, 4], [12600, 16624, 5], [16624, 20675, 6], [20675, 27691, 7], [27691, 36510, 8], [36510, 41805, 9], [41805, 47388, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47388, 0.13208]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
959354080d910259a9cbefc7753a15ea08890431
|
Distributed Semantic Wiki: Kolflow Project - Task 5 - State of the art (D5.1)
Hala Skaf-Molli, Pascal Molli
To cite this version:
Hala Skaf-Molli, Pascal Molli. Distributed Semantic Wiki: Kolflow Project - Task 5 - State of the art (D5.1). 2012. hal-00707185
HAL Id: hal-00707185
https://hal.archives-ouvertes.fr/hal-00707185
Submitted on 12 Jun 2012
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Distributed Semantic Wiki: Kolflow Project
-Task 5- State of the art (D5.1)
Hala Skaf-Molli and Pascal Molli,
GDD Team, Nantes University
Hala.Skaf@univ-nantes.fr, Pasca.Molli@univ-nantes.fr
June 12, 2012
Abstract
This paper presents the state of the art on Distributed Semantic Wikis. This work is part of the Kolflow project, more precisely it is part of the task 5, D(5.1).
1 Semantic Wikis
Wikis are the most popular tools of Web 2.0, they provide an easy to share and contribute to global knowledge. The encyclopedia Wikipedia is a famous example of a wiki system. In spite of their fast success, wiki systems have some drawbacks. They suffer from search and navigation [6], it is not easy to find information in wikis [2]. They have also scalability, availability and performance problems [19, 8] and they do not support offline works and atomic changes [3]. To overcome these limitations, wiki systems have evolved in two different ways: semantic wikis and peer-to-peer wikis.
Semantic wikis such as Sematic MediaWiki [6], IkeWiki [14], SweetWiki [2] and SWooki [17] are a new generation of collaborative editing tools, they allow users to add semantic annotations in the wiki pages. These semantic annotations can then be used to find pertinent answers to complex queries. Semantic wikis can be viewed as an efficient way to better structure wikis by providing a means to navigate and answer questions or reason, based on annotations. Semantic wikis are an extension of wiki systems that preserve the same principles of wikis such as simplicity in creating and editing wiki pages. Semantic wikis embed semantic annotations in the wiki content by using Semantic Web technologies such as RDF and SPARQL. In semantic wikis, users collaborate not only for writing the wiki pages but also for writing semantic annotations. Traditionally, authoring semantics and creation ontologies has mainly been in the hand of “ontologists” and knowledge management experts. Semantic wikis allow mass collaboration for creating and emerging ontologies. Some existing semantic wikis allows the emergence of the ontology, MediaWiki(SMW) [6] and SweetWiki [2].
Others use the wikis as a collaborative ontologies editors. IkeWiki [14] aims to create an instance of existing ontologies, while OntoWiki [1] aims the creation of ontology schema. In a semantic wiki, users add semantic annotations to wiki page text to represent relations and properties on this page. In SMW users choose their own vocabularies to type links. For instance, a link between the wiki pages “France” and “Paris” may be annotated by a user as “capital”.
<table>
<thead>
<tr>
<th>Content of wiki page of “France”</th>
<th>Content of semantic wiki page of “France”</th>
</tr>
</thead>
<tbody>
<tr>
<td>France is located in [Europe]</td>
<td>France is located in [locatedIn::Europe]</td>
</tr>
<tr>
<td>The capital of France is [Paris]</td>
<td>The capital of France is [hasCapital:: Paris]</td>
</tr>
</tbody>
</table>
These annotations express semantic relationships between wikis pages. Semantic annotations are usually written in a formal syntax so they are processed automatically by machines and they are exploited by semantic queries. There are two approaches of semantic wikis [2]:
- **The use of ontologies for wikis**: requires the load of an existing ontology. The advantage is to build controlled vocabularies [14] but it can be too rigid for emergent domains where ontologies are not clearly defined.
- **The use of wikis for ontologies**: semantic wikis let users choose their own vocabularies [6]. Semantic annotations are integrated directly in the wiki text. Semantic data appear in their context. The main advantage is to allow the emergence of an ontology.
In spite of their success, semantic wikis do not support a multi-synchronous work mode. Their current model provides only one copy of a semantic wiki page. The state of a semantic wiki page is always the current visible one on the server, intermediate inconsistent states are always visible. Consequently, transactional changes are not be supported neither the isolated work mode nor off-line editing mode.
### 2 P2P wikis
The basic idea of peer-to-peer wikis is to replicate wiki pages on the peers of a P2P network.
The main problem is to ensure the consistency of copies. Strong consistency of copies such as sequential consistency or 1-copy serializability cannot be currently ensured on P2P networks. P2P wikis rely on algorithms with high communication complexity or on algorithms that do not support dynamicity of P2P networks [13]. All existing P2P wikis are using an optimistic replication algorithm that ensures only a weaker consistency such as causal consistency, eventual consistency or CCI consistency (causality, convergence, intentions). A wiki deployed on a P2P network takes natural advantages of a P2P network i.e. faults-tolerance, better scalability, infrastructure cost sharing and better performances. P2P wikis can be divided into two categories:
**Partial replication.** The replication is “partial” if a single page has a fixed number of copies [8], [3] and [10]. Partial replication is generally implemented
on Distributed Hash tables (DHT). The main advantages of partial replication are: (i) a virtual infinite storage i.e. adding a peer in the network increases storage capacity, (ii) a less traffic generation than the total replication approach (iii) a cheap join of a new site to the P2P network.
Total replication. The replication is “total” if all pages are replicated on all servers [19], [5], [4]. The main advantages of total replication compared to partial replication are: (i) off-line editing i.e. even when disconnected, a peer can continue editing, this is mandatory for mobile work, (ii) transactional changes i.e. by allowing off-line work, it is possible to generate a change that concerns multiple wiki pages (iii) local requests execution i.e. as all data are local, all requests can be processed locally.
Compared to partial replication, total replication has some drawbacks: (i) total replication generates more traffic for write operations i.e. when a change is made on a copy, it is propagated to all copies and not to a fixed number of copies, (ii) when a peer is joining the network, it requires transferring the complete state of the wiki not just the range of wiki pages that the peer is responsible to.
In this paper, we focus on the state of the art of distributed semantic wiki. Such a system combines advantages of P2P wikis and Semantic wikis. We will
detail two systems: SWOOKI and DSMW. Both of these systems are based on the use of wikis for ontologies approach such as Semantic MediaWiki. However, Swooki is peer-to-peer wiki based on total replication and CCI consistency and DSMW is a peer-to-peer wiki based on partial replication and CCI consistency.
3 SWooki : A peer-to-peer Semantic Wiki
A P2P semantic wiki is a P2P network of autonomous semantic wiki servers (called also peers or nodes) that can dynamically join and leave the network. Every peer hosts a copy of all semantic wiki pages and an RDF store for the semantic data. Every peer can autonomously offer all the services of a semantic wiki server. When a peer updates its local copy of data, it generates a corresponding operation. This operation is processed in four steps:
1. It is executed immediately against the local replica of the peer,
2. it is broadcasted through the P2P network to all other peers,
3. it is received by the other peers,
4. it is integrated to their local replica. If needed, the integration process merges this modification with concurrent ones, generated either locally or received from a remote server.
The system is correct if it ensures the CCI consistency model (see section ??).
3.1 Data Model
The data model is an extension of Wooki [19] data model to take in consideration semantic data. Every semantic wiki peer is assigned a global unique identifier named NodeID. These identifiers are totally ordered. As in any wiki system, the basic element is a semantic wiki page and every semantic wiki page is assigned a unique identifier PageID, which is the name of the page. The name is set at the creation of the page. If several servers create concurrently pages with the same name, their content will be directly merged by the synchronization algorithm. Notice that a URI can be used to unambiguously identify the concept described in the page. The URI must be global and location independent in order to ensure load balancing. For simplicity, in this paper, we use a string as page identifier.
Definition 1 A semantic wiki page Page is an ordered sequence of lines $L_BL_1, L_2, \ldots L_nL_E$ where $L_B$ and $L_E$ are special lines. $L_B$ indicates the beginning of the page and $L_E$ indicates the ending of the page.
Definition 2 A semantic wiki line $L$ is a four-tuple $< LineID, content, degree, visibility >$ where
- $LineID$ is the line identifier, it is a pair of (NodeID, logicalclock) where NodeID is the identifier of the semantic wiki server and logicalclock is a logical clock of that server. Every semantic wiki server maintains a logical clock, this
clock is incremented when an operation is generated. Lines identifiers are totally ordered so if LineID₁ and LineID₂ are two different lines with the values (NodeID₁, LineID₁) and (NodeID₂, LineID₂) then LineID₁ < LineID₂ if and only if (1) NodeID₁ < NodeID₂ or (2) NodeID₁ = NodeID₂ and LineID₁ < LineID₂.
- content is a string representing text and the semantic data embedded in the line.
- degree is an integer used by the synchronization algorithm, the degree of a line is fixed when the line is generated, it represents a kind of loose hierarchical relation between lines. Lines with a lower degree are more likely generated earlier than lines with a higher degree. By definition the degree of L_E and L_B is zero.
- visibility is a boolean representing if the line is visible or not. Lines are never really deleted they are just marked as invisible. For instance, suppose there are two lines in a semantic wiki page about "France", "France" is the identifier of the page.
Suppose these two lines are generated on the server with NodeID = 1 in the above order and there are no invisible lines, so the semantic wiki page will be internally stored as.
<table>
<thead>
<tr>
<th>L_B</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>((1,1), France is located in [locatedIn::Europe], 1, true)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>((1,2), The capital of France is [hasCapital::Paris], 2, true)</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
```
L_E
```
Text and semantic data are stored in separate persistent storages. Text can be stored in files and semantic data can be stored in RDF repositories, as described in the next section.
**Semantic data storage model** RDF is the standard data model for encoding semantic data. In P2P semantic wikis, every peer has a local RDF repository that contains a set of RDF statements extracted from its wikis pages. A statement is defined as a triple (Subject, Predicate, Object) where the subject is the name of the page and the predicates (or properties) and the objects are related to that concept. For instance, the local RDF repository of the above server contains: \( R = \{ ("France", "locatedIn", "Europe"), ("France", "hasCapital", "Paris") \} \). As for the page identifier, a global URI can be assigned to predicates and objects of a concept, for simplicity, we use a string. We define two operations on the RDF repositories:
- insertRDF(R, t): adds a statement t to the local RDF repository R. • deleteRDF(R, t): deletes a statement t from the local RDF repository R.
These operations are not manipulated directly by the end user, they are called implicitly by the editing operations as shown later.
3.2 Editing operations
A user of a P2P semantic wiki does not edit directly the data model. Instead, she uses traditional wiki editing operations, when she opens a semantic wiki page, she sees a view of the model. In this view, only visible lines are displayed. As in a traditional semantic wiki, she makes modifications i.e. adds new lines or deletes existing ones and she saves the page(s). To detect user operations, a diff algorithm is used to compute the difference between the initial requested page and the saved one. Then these operations are transformed into model editing operations. A delete of the line number \( n \) is transformed into a delete of the \( n^{th} \) visible line and an insert at the position \( n \) is transformed into insert between the \((n-1)^{th}\) and the \( n^{th} \) visible lines. These operations are integrated locally and then broadcasted to the other servers to be integrated. There are two editing operations for editing the wiki text: insert and delete. An update is considered as a delete of old value followed by an insert of a new value. There are no special operations for editing semantic data. Since semantic data are embedded in the text, the RDF repositories are updated as a side effect of text replication and synchronization. (1) \( \text{Insert}(\text{PageID}, \text{line}, l_P, l_N) \) where \( \text{PageID} \) is the identifier of the page of the inserted line. \( \text{line} \) is the line to be inserted. It is a tuple containing \(<\text{LineID}, \text{content}, \text{degree}, \text{visibility}>\). \( l_P \) is the identifier of the line that precedes the inserted line. \( l_N \) is the identifier of the line that follows the inserted line. During the insert operation, the semantic data embedded in the line are extracted, RDF statements are built with the page name as a subject and then they are added to the local RDF repository thanks to the function \( \text{insertRDF}(R, t) \). (2) The \( \text{delete}(\text{PageID}, \text{LineID}) \) operation sets the visibility of the line identified by \( \text{LineID} \) of the page \( \text{PageID} \) to false. The line is not deleted physically, it is just marked as deleted. The identifiers of deleted lines must be kept as tombstones. During the delete operation, the set of RDF statements contained in the deleted line is deleted from the local RDF repository thanks to the \( \text{deleteRDF}(R, t) \).
3.3 Correction Model
This section defines causal relationships and intentions of the editing operations for our P2P semantic wiki data model.
3.4 Causality preservation
The causality property ensures that operations ordered by a precedence relation will be executed in the same order on every server. In WOOT, the precedence relation relies on the semantic causal dependency. This dependency is explicitly declared as preconditions of the operations. Therefore, operations are executed on a state where they are legal i.e. preconditions are verified. We define causality for editing operations that manipulate text and RDF data model as:
**Definition 3** \( \text{insert Preconditions} \) Let \( \text{Page} \) be the page identified by \( \text{PageID}, \) let the operation \( \text{op}=\text{Insert}(\text{PageID}, \text{newline}, p, n) \), \( \text{newline}=<\text{LineID}, c, \)
Definition 4 **Preconditions of delete operation** Let Page be the page identified by PageID, let \( \text{op} = \text{Delete}(\text{PageID}, \text{dl}) \) generated at a server NodeID with local RDF repository \( R \), the line identified by \( \text{dl} \) can be deleted (marked as invisible), if its \( \text{dl} \) exists in the page.
\[ \exists j \text{LineID}(\text{Page}[i]) = p \land \text{LineID}(\text{Page}[j]) = n \]
When a server receives an operation, the operation is integrated immediately if its pre-conditions are evaluated to true else the operation is added to a waiting queue, it is integrated later when its pre-conditions become true.
---
**3.5 Intentions and Intentions preservation**
The intention of an operation is the visible effect observed when a change is generated at one peer, the intention preservation means that the intention of the operation will be observable on all peers, in spite of any sequence of concurrent operations. We can have a naive definition of intention for **insert** and **delete**:
- The intention of an insert operation \( \text{op} = \text{Insert}(\text{PageID}, \text{newline}, p, n) \) when generated at site NodeID, where \( \text{newline} = < \text{nid}, c, d, v> \) is defined as:
1. The content is inserted between the previous and the next lines and
2. The semantic data in the line content are added to the RDF repository of the server.
---

The intention of a delete operation \( op = \text{delete}(\text{pid}, l) \) when generated at site \( S \) is defined as: (1) the line content of the operation is set to invisible and (2) the semantic data in the line content are deleted from the RDF repository of the server.
Unfortunately, it is not possible to preserve the previous intention definitions. We illustrate a scenario of violation of these intentions in figure 2. Assume that three P2P semantic wiki servers, \( \text{peer}_1, \text{peer}_2 \) and \( \text{peer}_3 \) share a semantic wiki page about "France". Every server has its copy of shared data and has its own persistence storage repository. At the beginning, the local text and the RDF repositories are empty. At \( \text{peer}_1 \), \( \text{user}_1 \) inserts the line "France is located [located In::Europe]" at the position 1 in her copy of the "France" page. Concurrently, at \( \text{peer}_2 \) \( \text{user}_2 \) inserts a new line "France is a country in [located In::Europe]" in her local copy of "France" page at the same position and finally at \( \text{peer}_3 \) \( \text{user}_3 \) deletes the line added by \( \text{user}_1 \). When \( op_2 \) is integrated at \( \text{peer}_1 \), the semantic annotation is present two times in the text and just one time in the RDF repository. In fact, the RDF repository cannot store twice the same triple. When \( op_3 \) is finally integrated on \( \text{peer}_1 \), it deletes the corresponding line and the semantic entry in the RDF repository. In this state, the text and the RDF repository are inconsistent. Concurrently, \( \text{peer}_3 \) has integrated the sequence \([op_1; op_3; op_2]\). This sequence leads to a state different than the state on \( \text{peer}_1 \). Copies are not identical, convergence is violated.
The above intentions cannot be preserved because the effect of executing \( op_3 \) changes the effect of \( op_2 \) which is independent, of \( op_3 \) i.e. \( op_3 \) deletes the statement inserted by \( op_2 \), but \( op_3 \) has not seen \( op_2 \) at generation time.
### 3.6 Model for Intention preservation
It is not possible to preserve intentions if the RDF store is defined as a set of statements. However, if we transform the RDF store into multi-set of statements, it becomes possible to define intentions that can be preserved.
**Definition 5 RDF repository** is the storage container for RDF statements, each container is a multi-set of RDF statements. Each RDF repository is defined as a pair \((T, m)\) where \( T \) is a set of RDF statements and \( m \) is the multiplicity function \( m : T \rightarrow \mathbb{N} \) where \( \mathbb{N} = 1, 2, ... \).
For instance, the multi-set \( R = \{ ("France", "LocatedIn", "Europe"),("France", "LocatedIn", "Europe"),("France", "hasCapital", "Paris") \} \) can be presented by \( R = \{ ("France", "LocatedIn", "Europe")^2, ("France", "hasCapital", "Paris")^1 \} \) where 2 is the number of occurrence of the first statement and 1 is this of the second one.
**Definition 6 Intention of insert operation** Let \( S \) be a P2P semantic wiki server, \( R \) is its local RDF repository and \( Page \) is a semantic wiki page. The intention of an insert operation \( op = \text{Insert}(\text{PageID}, \text{newline}, p, n) \) when generated at site \( S \), where \( \text{newline} = \langle \text{nid}, c, d, v \rangle \) and \( T \) is the set (or multi-set) of RDF statements in the inserted line, is defined as: (1) The content is...
inserted between the previous and the next lines and (2) the semantic data in
the line content are added to $R$.
\[
\exists i \land \exists i' < i \text{ LineID}(\text{Page}[i]) = p \quad (1)
\]
\[
\land \exists i \leq i_N \text{ LineID}(\text{Page}[i_N]) = n \quad (2)
\]
\[
\land \text{Page'}[i] = \text{newline} \quad (3)
\]
\[
\land \forall j < i \text{ Page'}[j] = \text{Page}[j] \quad (4)
\]
\[
\land \forall j \geq i \text{ Page'}[j] = \text{Page}[j-1] \quad (5)
\]
\[
\land R' \leftarrow R \cup T \quad (6)
\]
Where $\text{Page'}$ and $R'$ are the new values of the page and the RDF repository respectively after the application of the insert operation at the server $S$ and $\cup$ is the union operator of multi-sets. If a statement in $T$ already exists in $R$ so its multiplicity is incremented else it is added to $R$ with multiplicity one.
**Definition 7 Intention of delete operation** Let $S$ be a P2P semantic wiki server, $R$ is the local RDF repository and $\text{Page}$ is a semantic wiki page. The intention of a delete operation $\text{op} = \text{delete}(\text{PageID}, \text{ld})$ where $T$ is the set (or multi-set) of RDF statements in the deleted line, is defined as: (1) the line $\text{ld}$ is set to invisible and (2) the number of occurrence of the semantic data embedded in $\text{ld}$ is decreased by one, if this occurrence is equal to zero which means these semantic data are no more referenced in the page then they are physically deleted from the $R$.
\[
\exists i \land \text{PageID}(\text{Page'}[i]) = \text{ld} \quad (7)
\]
\[
\land \text{visibility}(\text{Page'}[i]) \leftarrow \text{false} \quad (8)
\]
\[
\land R' \leftarrow R - T \quad (9)
\]
Where $\text{Page'}$ and $R'$ are the new values of the page and the RDF repository respectively after the application of the delete operation at the server $S$ and $-$ is the difference of multi-sets. If statement(s) in $T$ exists already in $R$ so its multiplicity is decremented and deleted from the repository if it is equal to zero.
Let us consider again the scenario of the figure 2. When $\text{op}_2$ is integrated on $\text{peer}_1$, the multiplicity of the statement (“France”, “locatedIn”, “Europe”) is incremented to 2. When $\text{op}_3$ is integrated on $\text{peer}_1$, the multiplicity of the corresponding statement is decreased and the consistency between text and RDF repository is ensured. We can observe that $\text{Peer}_1$ and $\text{Peer}_3$ now converge and that intentions are preserved.
### 3.7 Algorithms
As any wiki server, a P2P semantic server defines a $\text{Save}$ operation which describes what happens when a semantic wiki page is saved. In addition, it defines $\text{Receive}$ and $\text{Integrate}$ operations. The first describes what happens upon receiving a remote operation and the second integrates the operation locally.
Save operation During saving a wiki page, a Diff algorithm computes the difference between the saved and the previous version of the page and generates a patch. A patch is the set of delete and insert operations on the page $(Op = Insert(PageID, line, lp, l_N)$ or $Op = Delete(PageID, LineID))$. These operations are integrated locally and then broadcasted to other sites in order to be executed as shown below.
Upon $Save(page, oldPage)$ :
let $P ← Diff(page, oldPage)$
for each $op ∈ P$ do
Receive($op$)
endfor
Broadcast($P$)
At this level of description, we just make the hypothesis that $Broadcast(P)$ will eventually deliver the patch $P$ to all sites. More details are given in section ??.
Delivery Operation When an operation is received (cf figure 4) its preconditions are checked (cf figure 5). If they are not satisfied, the operation is added to the waiting log of the server, else according to the type of the operations some steps are executed.
The waiting log is visited after the integration and the operations that satisfy their preconditions are removed from the log and integrated. The function $ContainsL(PageID, id)$ tests the existence of the line in the page, it returns true if this is the case. The function $isVisible(LineID)$ tests the visibility of
Upon Receive(op) :
if isExecutable(op) then
if type(op) = insert then
IntegrateIns(op)
if type(op) = delete then
IntegrateDel(op)
else
waitingLog ← waitingLog ∪ {op}
endif
Figure 4: Receive operation
isExecutable(op) :
if type(op) = del then
return containsL(PageID,LineID)
and isVisible(LineID)
else
return ContainsL(PageID,lP)
and ContainsL(PageID, lN)
endif
Figure 5: isExecutable Operation
IntegrateDel(LineID) :
IntegrateDelT(LineID)
IntegrateDelRDF(LineID)
Figure 6: IntegrateDel operation
IntegrateDelT(LineID) :
Page[LineID]. visibility ← false
Figure 7: IntegrateDelT Operation
Integrate operation The integration of an operation is processed in two steps (cf figure 6): (1) text integration and (2) RDF statements integration. To integrate a text delete operation (cf. figure 7), the visibility flag of the line is set to false whatever is its content. To integrate RDF statements (cf figure 8), a counter is used to implement a multi-set RDF repository. A counter is attached to every RDF triple, the value of the counter corresponds to the number of occurrence of the triple in the repository. During the delete operation, the counter of the deleted statements is decreased, if the counter is zero the statements are physically deleted from the repository.
To integrate an insert operation (cf figure 9) the line has to be placed among all the lines between lP and lN, some of these lines can be previously deleted or inserted concurrently and the inserted semantic data are integrated. To
IntegrateDelRDF(LineID) :
let S ← ExtractRDF(LineID)
if S ≠ ∅ then
for each triple ∈ S do
triple . counter --
if triple . counter = 0 then
deleteRDF(R, triple)
endif
endif
Figure 8: IntegrateDelRDF operation
IntegrateIns(PageID, line, lP , lN) :
IntegratedInsT(PageID, line, lP , lN)
IntegrateInsRDF(line)
Figure 9: IntegrateIns Operation
integrate a line in a wiki page, we use the integration algorithm defined in [19]. This algorithm (cf. figure 10) selects the sub-sequence $S'$ of lines between the previous and the next lines, in case of an empty result, the line is inserted before the next line. Else, the sub-sequence $S'$ is filtered by keeping only lines with the minimum degree of $S'$. The remaining lines are sorted according to the line identifiers order relation $<_id$ [9], therefore, line will be integrated in its place among remaining lines, the procedure is called recursively to place line among lines with higher degree in $S'$. To integrate the semantic data (cf figure 11), the RDF statements of the inserted line are extracted and added to the local RDF repository. If the statements exist already in the repository, their counter is incremented, otherwise, they are inserted into the RDF repository with a counter value equals to one as shown below.
To summarize, causality as defined in section 3.4 is ensured by the Receive algorithm. Convergence for text is already ensured by the WOOT algorithm [9]. Convergence for semantic data is trivially ensured by the multi-set extension of the RDF repository. The intention preservation for a text is demonstrated in [9]. Here, we are concerned with the intention of semantic data as defined in 3.5. The intention of an insert operation is trivially preserved by the algorithm IntegrateInsRDF. Since a possible way to implement a multi-set is to associate a counter to every element. In the same way, the algorithm IntegrateDelRDF preserves the intention of the delete operation. The basic idea behind all these algorithms is to reach convergence and preserve intentions whatever is the order of reception of operations. This implies that these algorithms “force” commutativity of operations. If operations are commuting then all concurrent executions are equivalent to a serial one. In our system, users can start a transaction just by switching to the offline mode and end a transaction by switching to online mode. We chose this way to interact with users in order to keep the system simple. If a user produces a consistent change, as all operations of any transaction are commuting and ensure the same effects, then all concurrent execution
of transactions generate a correct state.
The SWOOKI prototype has been implemented in Java as servlets in a Tomcat Server and demonstrated in [11]. This prototype is available with a GPL license on sourceforge at http://sourceforge.net/projects/wooki and it is also available online at: http://wooki.loria.fr/wooki1.
3.8 Synthesis
SWooki is a peer-to-peer semantic wikis combines both advantages of semantic wikis and P2P wikis. The fundamental problem is to develop an optimistic replication algorithm that ensures an adequate level of consistency, supports P2P constraints and manages semantic wiki page data type.
SWooki is based on total replication this allows to query, access, reason and retrieve data locally from any peer without the need for search mechanisms nor transfer of the semantic data between peers to resolve queries. Therefore, "querying the network" [18] becomes querying any peer. (ii) Total replication enables transactional changes i.e. atomic changes across multiple pages. Supporting transactional changes is a very important feature in the context of semantic wiki. In semantic wiki, a wiki page presents a concept of an ontology, so a modification of one concept may requires atomic changes to other concepts. If the change is not atomic, it means that intermediate changes will be visible to others users and to concurrent requests. This can lead to confusion for other users and to false results for requests.
SWooki [17] combines the advantages of P2P wikis and semantic wikis. It is based on an optimistic replication algorithm that ensures the CCI consistency model. It supports the off-line work mode and transactional changes. Its main limitations are the total replication and the collaboration model. Every peer of the network hosts a replica of wiki pages and a replica of the semantic store. Users cannot choose the pages that they want to replicate neither the period of synchronization. Modifications are propagated on page saving. The collaborative community is implicit. Users cannot choose to whom propagate modifications. Changes propagation is under the control of system and not the users. All connected peers receive and integrate changes. A disconnected peer will receive the modifications of the others at reconnection thanks to the anti-entropy algorithm.
4 Multi-synchronous Semantic Wiki Approach (DSMW)
Multi-synchronous semantic wikis allow users to build their own cooperation networks. The construction of the collaborative community is declarative, in the sense, every user declares explicitly with whom he would like to cooperate. Every user can have a multi-synchronous semantic wiki server installed on her machine. She can create and edit her own semantic wiki pages as in a normal
semantic wiki system. Later, she can decide to share or not these semantic wiki pages and decide with whom to share.
### 4.1 Multi-synchronous Collaboration Model
The replication of data and the communication between servers is made through *channels* (feeds). The channel usage is restricted to few servers with simple security mechanisms that require no login and complex access control. Capabilities fit perfectly these requirements [7]. The key point is that channels are read-only for consumers and can be hosted on hardware of users. When a semantic wiki page is updated on a multi-synchronous semantic wiki server, it generates a corresponding operation. This operation is processed in four steps: (1) It is executed immediately against page, (2) it is published to the corresponding *channels*, (3) it is pulled by the authorized servers, and (4) it is integrated to their local replica of the page. If needed, the integration process merges this modification with concurrent ones, generated either locally or received from a remote server.
The system is correct if it ensures the CCI (Causality, Convergence and Intention Preservation) consistency model. Multi-synchronous semantic wikis use the Logoot synchronization algorithm [20] to integrate modifications. Logoot ensures the CCI consistency model. More precisely, Logoot ensures convergence and preserves the intentions of operations if the causality of the operations is preserved.
### 4.2 Collaboration Scenarios
This section presents two scenarios of collaboration in multi-synchronous semantic wikis. We suppose several professors collaborate together through a semantic wiki to prepare lectures, exercises and exams. Later, they want to make lectures available for students and they want to integrate relevant feedbacks from students.

Scenario 1: Collaboration among professors
For simplicity, we suppose there are two professors $prof_1$ and $prof_2$ (see figure 12). Every professor has her own multi-synchronous semantic wiki, $site_1$ for $prof_1$ and $site_2$ for $prof_2$, respectively.
1. $prof_1$ edits three semantic wiki pages $lesson_1$, $exercises_1$ and $exam_1$ on her site $site_1$. For instance, the page $lesson_1$ edited by $prof_1$ has three lines:
Introduction:
In "multi-synchronous" work, parties work independently in parallel.
[Category::Lesson] [forYear:2009]
2. $prof_1$ wants to publish her modifications on $lesson_1$ to $prof_2$. Therefore, she creates a feed $url_1$ that contains change set. Finally, she communicates the address of the feed to $prof_2$.
3. $prof_2$ subscribes to this channel and creates a feed $url_2$ to pull modifications. The result is a local semantic wiki page $lesson_1$ that has the same content as $lesson_1$ of $prof_1$.
4. $prof_2$ edits his local copy of the $lesson_1$ page. $lesson_1$ has now five lines:
Introduction:
In "multi-synchronous" work mode, parties work independently in parallel.
[Category::Lesson] [forYear:2009]. This mode is based on divergence and synchronization phases.
5. In her turn, $prof_2$ shares his modifications on $lesson_1$ with $prof_1$. He creates a feed and publishes his modifications. $prof_1$ subscribes to the feed and pulls the modifications published by $prof_2$ and finally integrates these modifications on her local copy of $lesson_1$. The integration process merges the remote modifications with concurrent ones, if any, generated locally by $prof_1$. The integration process has to ensure the convergence of all copies on $lesson_1$ if all generated operations on $site_1$ and $site_2$ are integrated on both sites.
The advantages of this collaboration model are, on the one hand, there is no need for centralized server to cooperate. On the other hand, every professor works on her or his own copy in isolation, publishes and pulls changes whenever she wants, i.e. the changes propagation is under the control of the user. This collaboration process is not supported in classical semantic wikis. The table 1 represents a part of the scenario.
Scenario 2: Collaboration among professors and students
In this scenario, $prof_1$ wants to make $lesson_1$ available for her students while she continues to make corrections and minor modifications on $lesson_1$. In order to provide her students with the courses, $prof_1$ publishes them on a public site $pubSite$ that can be either her proper public wiki site or the site of the university. $pubSite$ is accessible by the students for read only to
Table 1: Multi-synchronous collaboration scenario
<table>
<thead>
<tr>
<th>Site1</th>
<th>Site2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Edit(lesson₁)</td>
<td></td>
</tr>
<tr>
<td>Edit(exercises₁)</td>
<td></td>
</tr>
<tr>
<td>Edit(exam₁)</td>
<td></td>
</tr>
<tr>
<td>CreatePushFeed(f₁,q₁)</td>
<td>CreatePullFeed(f₁, f₂)</td>
</tr>
<tr>
<td>Edit(lesson₁)</td>
<td>Edit(lesson₁)</td>
</tr>
<tr>
<td>Push(f₁)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>CreatePushFeed(f₃,q₂)</td>
</tr>
</tbody>
</table>
Maintain the courses consistency. However, prof₁ manages to integrate relevant feedbacks from students provided by the students sites.
Professor can make continuous improvement of the lessons and can make continuous integration of the modifications and make only consistent modifications visible. Without multi-synchronous support all incremental changes will be visible to both end users and to semantic request engines. Every participant professor and student want to control the visibility of their modifications and want to control the integration of others’ modifications.
5 Multi-synchronous Semantic Wiki System
This section presents the data model and the algorithms for multi-synchronous Semantic Wiki systems (M2SW). The data model is defined an ontology. Therefore, it is possible to querying and reasoning on the model itself and make future extension. For instance, it is possible to make queries like: (1) “list all unpublished changes”, (2) “list all published changes on a given channel”, (3) “list unpublished change set of a given semantic wiki page”, (4) ”list all pulled change sets”, etc.
5.1 DSMW Ontology
The M2SW ontology is defined as an extension of existing ontologies of semantic wikis [2]. In this section, we present the M2SW ontology and detail only its new vocabulary and their properties.
- **WikiSite**: this concept corresponds to a semantic wiki server. A site has the following properties:
- `siteID`: this attribute contains the URL of the site.
- `logicalClock`: this attribute has a numeric value. Every semantic wiki server maintains a logical clock, this clock is used to identify patches and operations in an unique way in the whole network.
- `hasPush`, `hasPull` and `hasPage`: the range of these properties are respectively a push feed, a pull feed and a semantic wiki page. A wiki site has several push feeds, pull feeds and several pages.
- **SemanticWikiPage**: this concept corresponds to a normal semantic wiki page. It has the following properties:
- `pageID`: this attribute contains the URL of the page.
- `hasContent` the range of this property is a String, it contains text and the semantic data embedded in the semantic wiki page.
• Operation: this concept represents a change in a line of a wiki page. In our model, there are two editing operations: insert and delete. An update is considered as a delete of old value followed by an insert of a new value. An operation has the following properties:
- operationID: this attribute contains the unique identifier of the operation. operationID is calculated by: operationID = concat(Site.siteID, Site.logicalClock + +), the concat function concatenates two strings.
- opType: this attribute contains the type of the operation, it can be either an insert or a delete.
- positionID: denotes the position of the line in the wiki page. This identifier is calculated by the Logoot algorithm[20].
- lineContent: is a string representing text and the semantic data embedded in the line.
• Patch: a patch is a set of operations. A patch is calculated during the save of the modified semantic wiki page using the Logoot algorithm. A patch has the following properties:
- patchID: is a unique identifier of the patch. Its value is calculated by:
patchID = concat(Site.siteID, Site.logicalClock + +)
- onPage: the range of this property is the page where the patch was applied.
- hasOperation: this property points to the operations generated during the save of the page.
Figure 13: Multi-synchronous ontology
- head: this property points to the last patch applied to the page.
• **ChangeSet**: a change set contains a set of patches. This concept is important in order to support transactional changes. It allows to regroup patches generated on multiple semantic wiki pages. Therefore, it is possible to push modifications on multiple pages. ChangeSet has the following properties:
– changSetID: is a unique identifier of a change set. Its value is calculated as: changSetID = concat(Site.siteID, Site.logicalClock + 1)
– hasPatch property points to the patches generated since the last push.
– previousChangeSet: points to the precedent change set.
– inPushFeed: the range of this property is PushFeed. This property indicates the PushFeed that publishes a ChangeSet.
– inPullFeed: the range of this property is PullFeed. This property indicates the PullFeed that pulls a ChangeSet.
• **PushFeed**: this concept is used to publish changes of a WikiSite. It is a special semantic wiki page. It inherits the properties of the SemanticWikiPage concept and defines its own properties:
– hasPushHead: this property points to the last published changeSet.
– hasSemanticQuery: this property contains a semantic query. This query determines the content of the push feed. For instance, the query can be “find all Lessons”, this will return all the pages in the class (category) Lessons. To answer hasSemanticQuery, reasoning and querying capabilities of semantic wikis are used.
• **Pull Feed**: this concept is used to pull changes from a remote WikiSite. A pull feed is related to one push feed. In the sense that it is impossible to pull unpublished data. A pull feed is also a special semantic wiki page. It inherits the properties of the Semantic Wiki Page concepts and defines its own properties:
– hasPullHead: this property points to the last pulled change set pulled.
– relatedPushFeed: this property relates a pull feed to the URL of its associated push feed.
We can extend and build on MS2W ontology. The MS2W ontology is maintained by the MS2W developers. It is defined in OWL DL allowing to querying and reasoning on the patches, ChangeSet, PushFeed, etc. SPARQL can be used to query the MS2W data. For instance, it is possible to list all published patches on a push feed:
\[ Published \equiv \exists (hasPatch^{-1}) . \exists (inPushFeed^{-1}) . PushFeed \]
### 5.2 Algorithms
As any semantic wiki server, a multi-synchronous semantic wiki server defines a Save operation which describes what happens when a semantic wiki page is saved. In addition, we define special operations: CreatePushFeed, Push, CreatePullFeed, Pull and Integrate for the multi-synchronous semantic wiki. We use the Logoot algorithm [20] for the generation and the integration of the insert and delete operations. In the following, detail these operations for a semantic wiki server called site.
**Save Operation** During the saving of a wiki page, the Logoot algorithm computes the difference between the saved and the previous version of the page and generates a patch. A patch is a set of delete and insert operations on the page \((\text{Op} = (\text{opType}, \text{operationID}, \text{positionID}, \text{lineContent}))\). Logoot calculates the positionID, lineContent and the opType of the operation. These operations are integrated locally and then eventually published on a push feed.
```plaintext
On Save(page : String, previous: String):
Patch(pid=concat(site.siteID, site.logicalClock++))
foreach op ∈ Logoot(page, previous) do
Operation(opid=concat(site.siteID,site.logicalClock++))
hasOperation(pid,opid)
endfor;
previous(pid,page.head)
head(page,pid)
onPage(pid,page)
```
**CreatePushFeed Operation** The communication between multi-synchronous semantic wiki servers is made through feeds. The CreatePushFeed operation creates a push feed. A push feed is a special semantic wiki page that contains a query that specifies the pushed data. It is used to publish changes of a wiki server. Authorized sites can access the published data. CreatePushFeed operation calls the Push operation.
```plaintext
On CreatePushFeed(name:String,request:String):
PushFeed(name)
hasSemanticQuery(name,request)
hasPush(site,name)
call Push(name)
```
**Push Operation** This operation creates a change set corresponding to the pages returned by the semantic query and adds it to the push feed. Firstly, the semantic query is executed, then the patches of the pages returned by the query are extracted. These patches are added to the change set if they have not been published on this push feed yet.
```plaintext
On Push(name:String):
ChangeSet(csid=concat(site.siteID,site.logicalClock++))
inPushFeed(csid, name)
let published ← { ∃x ∃y ∧ inPushFeed(y,name) ∧ hasPatch(y,x) }
let patches ← { ∃x ∀p ∈ execQuery(name.hasSemanticQuery) ∧ onPage(x,p)}
foreach patch ∈ {patches − published} do
hasPatch(csid, patch)
endfor
previousChangeSet(csid, name.hasPushHead)
hasPushHead(name,csid)
```
**CreatePullFeed Operation** As the replication of data and the communication between multi-synchronous semantic wiki servers are made through feeds, pull feeds are created to pull changes from push feeds on remote peers to the local peer (cf figure 14). A pull feed is related to a push feed. In the sense that it is impossible to pull unpublished data.
19
On CreatePullFeed(name:String, url:URL)
PullFeed(name);
relatedPushFeed(name, url)
call Pull(name);
Figure 14: CreatePullFeed operation
On Pull(name:String):
while ((cs ← get(name.headPullFeed, name.relatedPushFeed) ≠ null)
let p ← {∃x ∧ inPushFeed(x, name)}
if cs ∉ {p} then
inPullFeed(cs, name)
call Integrate(cs)
endif
hasPullHead(name, cs)
endwhile
Figure 16: Pull Operation
On ChangeSet get(cs : ChangeSetId ,url)
if ∃x previousChangeSet(cs, x)
return x
else return null;
Figure 15: get a ChangeSet operation
Integrate(cs:ChangeSet):
foreach patch ∈ cs do
previous(patch.patch.onPage.head)
head(patch.onPage.patch)
foreach op ∈ hasOperation.patch
do call logootIntegrate(op)
endfor
endfor
Figure 17: IntegrateOperation
**Pull Operation** This operation fetches for published change sets that have not pulled yet (cf figure16). It adds these change sets to the pull feed and integrate them to the concerned pages on the pulled site.
**get Function** This function allows to retrieve a ChangeSet (cf figure 15).
**Integration operation** The integration of a change set is processed as follows (cf figure 17). First all the patches of the change set are extracted. Every operation in the patch is integrated in the corresponding semantic wiki page thanks to the Logoot algorithm.
DSMW algorithms ensure the causality and the CCI model (Causality, Convergence, Intention) as demonstrated in [12].
DSMW is implemented as an extension of Semantic MediaWiki [6]. Feeds, ChangeSets and Patches are represented as special semantic wiki pages. They stored in a special namespace to prevent user modification. The Logoot algorithm has been implemented in PHP and integrated in Mediawiki relying on the hook mechanism. The push, pull, createPushFeed and createPullFeed operations are available in special administration pages of MediaWiki. This extension is designed to respect the simplicity of the wikis while supporting the MS2W model and the result is an easy way to construct a P2P network of semantic wikis based on Semantic MediaWiki. DSMW was demonstrated in different conference [15, 16].
6 Conclusion
DSMW extends a semantic wiki with multi-synchronous capabilities. Multi-synchronous semantic wikis allow users to build their own cooperation networks. The construction of the collaborative community is declarative. Every user declares explicitly with whom he would like to cooperate. The replication of the wiki pages on semantic wikis servers and the synchronization periods are variant and under the control of the users. The MS2W model enhances the existing semantic wikis by supporting transactional changes and the off-line work mode. Hence, multiple dataflow oriented workflows can be supported. In addition, the model takes natural advantages of a P2P network, i.e. faults-tolerance, better scalability, infrastructure cost sharing and better performance.
References
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-00707185/file/main.pdf", "len_cl100k_base": 11475, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 61105, "total-output-tokens": 13755, "length": "2e13", "weborganizer": {"__label__adult": 0.00044608116149902344, "__label__art_design": 0.0011510848999023438, "__label__crime_law": 0.0006361007690429688, "__label__education_jobs": 0.017730712890625, "__label__entertainment": 0.00037217140197753906, "__label__fashion_beauty": 0.0002741813659667969, "__label__finance_business": 0.0012826919555664062, "__label__food_dining": 0.00049591064453125, "__label__games": 0.001476287841796875, "__label__hardware": 0.0008969306945800781, "__label__health": 0.0006394386291503906, "__label__history": 0.0010852813720703125, "__label__home_hobbies": 0.00020968914031982425, "__label__industrial": 0.0005354881286621094, "__label__literature": 0.0017728805541992188, "__label__politics": 0.0006852149963378906, "__label__religion": 0.0007419586181640625, "__label__science_tech": 0.309326171875, "__label__social_life": 0.0006570816040039062, "__label__software": 0.12164306640625, "__label__software_dev": 0.53662109375, "__label__sports_fitness": 0.0002818107604980469, "__label__transportation": 0.000640869140625, "__label__travel": 0.000392913818359375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52641, 0.02157]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52641, 0.2841]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52641, 0.84886]], "google_gemma-3-12b-it_contains_pii": [[0, 897, false], [897, 3057, null], [3057, 6049, null], [6049, 7430, null], [7430, 10058, null], [10058, 12765, null], [12765, 16082, null], [16082, 17592, null], [17592, 21105, null], [21105, 23965, null], [23965, 25253, null], [25253, 27219, null], [27219, 29498, null], [29498, 32251, null], [32251, 34129, null], [34129, 36824, null], [36824, 39507, null], [39507, 40911, null], [40911, 43743, null], [43743, 46292, null], [46292, 48460, null], [48460, 50799, null], [50799, 52641, null]], "google_gemma-3-12b-it_is_public_document": [[0, 897, true], [897, 3057, null], [3057, 6049, null], [6049, 7430, null], [7430, 10058, null], [10058, 12765, null], [12765, 16082, null], [16082, 17592, null], [17592, 21105, null], [21105, 23965, null], [23965, 25253, null], [25253, 27219, null], [27219, 29498, null], [29498, 32251, null], [32251, 34129, null], [34129, 36824, null], [36824, 39507, null], [39507, 40911, null], [40911, 43743, null], [43743, 46292, null], [46292, 48460, null], [48460, 50799, null], [50799, 52641, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52641, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52641, null]], "pdf_page_numbers": [[0, 897, 1], [897, 3057, 2], [3057, 6049, 3], [6049, 7430, 4], [7430, 10058, 5], [10058, 12765, 6], [12765, 16082, 7], [16082, 17592, 8], [17592, 21105, 9], [21105, 23965, 10], [23965, 25253, 11], [25253, 27219, 12], [27219, 29498, 13], [29498, 32251, 14], [32251, 34129, 15], [34129, 36824, 16], [36824, 39507, 17], [39507, 40911, 18], [40911, 43743, 19], [43743, 46292, 20], [46292, 48460, 21], [48460, 50799, 22], [50799, 52641, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52641, 0.04789]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
f749725adf15eb0b8995189844a137609b08921c
|
DOI
Link to record in KAR
https://kar.kent.ac.uk/21347/
Document Version
UNSPECIFIED
Copyright & reuse
Content in the Kent Academic Repository is made available for research purposes. Unless otherwise stated all content is protected by copyright and in the absence of an open licence (e.g. Creative Commons), permissions for further reuse of content should be sought from the publisher, author or other copyright holder.
Versions of research
The version in the Kent Academic Repository may differ from the final published version. Users are advised to check http://kar.kent.ac.uk for the status of the paper. Users should always cite the published version of record.
Enquiries
For any further enquiries regarding the licence status of this document, please contact: researchsupport@kent.ac.uk
If you believe this document infringes copyright then please contact the KAR admin team with the take-down information provided at http://kar.kent.ac.uk/contact.html
A Mechanisation of Computability Theory in
HOL
Vincent Zammit
Computer Laboratory, University of Kent, United Kingdom
Abstract. This paper describes a mechanisation of computability theory in HOL using the Unlimited Register Machine (URM) model of computation. The URM model is first specified as a rudimentary machine language and then the notion of a computable function is derived. This is followed by an illustration of the proof of a number of basic results of computability which include various closure properties of computable functions. These are used in the implementation of a mechanism which partly automates the proof of the computability of functions and a number of functions are then proved to be computable. This work forms part of a comparative study of different theorem proving approaches and a brief discussion regarding theorem proving in HOL follows the description of the mechanism.
1 Introduction
The theory of computation is a field which has been widely explored in mathematical and computer science literature [4, 12, 13] and several approaches to a standard model of computation have been attempted. However, each exposition of the theory centres on the basic notion of a computable function, and as such, one of the main objectives of a mechanisation of computability in a theorem prover is the formal definition of such functions. The mechanisation illustrated in this paper includes also the proof of a number of basic results of the theory and the implementation of conversions and other verification tools which simplify further development of the mechanisation.
This work is part of a comparative study of an LCF [9] style theorem proving assistant (namely the HOL system [5, 6]), and a non-LCF style theorem proving environment based on constructive type theory (such as the ALF system [1, 7] and the Coq proof assistant [3]). The definitions and proofs of even the most trivial results of computability tend to be of a very technical nature much similar to the proofs of theorems one finds in mathematical texts, and thus this theory offers an extensive case study for the analysis of the two approaches of mechanical verification. The verification styles are also compared to the way proofs of mathematical results are represented in texts. It is expected that this comparative study will contribute to the identification of possible enhancements to the theorem proving styles. Although it is not the scope of this paper to give full details of this comparative study, a brief discussion regarding theorem proving in HOL is given after the description of the implementation.
This particular mechanisation of the theory is based on the URM model [11] of computation and much of the implementation is based on the definitions and results described in [4]. The next section gives a brief discussion on URM computability, however it is strongly suggested that the interested reader consults the literature ([4, 12, 13]). The rest of the paper illustrates the actual mechanisation and includes the specification of the notion of a computable function in HOL, the proof of a number of results of computability and a mechanism for constructing and proving the computability of functions.
2 The URM Model of Computation
An Unlimited Register Machine (URM) consists of a countably infinite set of registers, usually referred to as the memory or store, each containing a natural number. The registers are numbered $R_0, R_1, \ldots, R_n, \ldots$, and the value stored in $R_n$ is specified by $r_n$. A URM executes a finite program constructed from the following four different types of instructions:
- **Zero:** $ZR_n$ sets $r_n$ to 0.
- **Successor:** $SC_n$ increments $r_n$.
- **Transfer:** $TF_n m$ copies $r_n$ to $R_m$.
- **Jump:** $JP_n m p$ jumps to the $p$th instruction (starting from 0) of the program if $r_n = r_m$.
A program counter keeps track of the current point in program execution, and the configuration of a URM is given by a pair $(p, r)$ consisting of the program counter and the current store. A configuration is said to be **initial** if the program counter is set to the index of the first instruction, and it is said to be **final** if the program counter exceeds the index of the last instruction.
Given a program $P$ and an initial configuration $c_0$, a computation is achieved by executing the instructions of the program one by one altering the URM configuration at each step. An execution step of a URM with a final configuration has no effect on the current configuration. A computation is thus an infinite sequence of configurations $(c_0, c_1, c_2, \ldots)$ and is denoted by $P(c_0)$, or simply by $P(r)$ where $c_0 = (0, r)$. The store $r$ is usually represented by a sequence of register values $(r_0, r_1, \ldots)$ and a finite sequence $(r_0, r_1, \ldots, r_n)$ represents the store where the first $n + 1$ registers are given by the sequence and the rest contain the value 0, which is the initial value held in each register. We use the notation $P(c) \rightarrow_n c'$ to express that $P$ alters the URM state from $c$ to $c'$ in $n$ steps.
A computation is said to **converge** if it reaches a final configuration, otherwise it is said to **diverge**. The **value** of a convergent computation is given by the contents of the first Register $R_0$ of the final configuration.
The computation of a program can be used to define an $n$-ary partial function by placing the parameters in the first $n$ registers of a cleared¹ URM store and then executing the program returning the contents of the first register as the function value. Formally, a program $P$ is said to compute an $n$-ary function $f$
¹ all registers containing 0.
if, for every \(a_0, \ldots, a_{n-1}\) and \(\nu\), \(P(a_0, \ldots, a_{n-1})\) converges to \(\nu\) if and only if \(f(a_0, \ldots, a_{n-1}) = \nu\). This definition implies that \(P(a_0, \ldots, a_{n-1})\) diverges if and only if \(f(a_0, \ldots, a_{n-1})\) is undefined. A function is said to be \(URM\)-computable if there is a program which computes it.
The \(URM\) model of computation is proved to be equivalent to the numerous alternative models such as the Turing machine model, the Gödel-Kleene partial recursive functions model, and Church’s lambda calculus \([4, 11]\) in the sense that the set of \(URM\) computable functions is identical to the set of the functions computed by any other model.
3 Mechanisation of \(URM\) Computability
An Unlimited Register Machine can be regarded as a simple machine language and as such its formal specification in HOL is similar to that of real world architectures \([14]\).
3.1 The \(URM\) Instruction Set
A \(URM\) store can be represented as a function from natural numbers to natural numbers and configurations as pairs consisting of a natural number signifying the program counter and a store,
\[
\begin{align*}
\text{store} &= :\text{num} \to \text{num} \\
\text{config} &= :\text{num} \times \text{store}
\end{align*}
\]
The syntax of the \(URM\) instruction set is specified through the definition of the type :
\[
\text{instruction} ::= \text{ZR num} \\
| \text{SC num} \\
| \text{TF num \to num} \\
| \text{JP num \to num \to num}
\]
and programs are defined as lists of instructions.
The semantics of the instruction set is then specified through the definition of a function \(\text{exec}\_\text{instruction} : \text{instruction} \to \text{config} \to \text{config}\) such that given an instruction \(i\) and a configuration \(c\), \(\text{exec}\_\text{instruction} \ i \ c\) returns the configuration achieved by executing \(i\) in configuration \(c\).
\[
\begin{align*}
\vdash_{\text{def}} (\forall n \ c. \ \text{exec}\_\text{instruction} ((\text{ZR} \ n) \ c) \\
&= (\text{SUC} \ (\text{FST} \ c), (\lambda x. \ (x = n) \to 0 \mid (\text{SND} \ c \ x))) \land \\
(\forall n \ c. \ \text{exec}\_\text{instruction} ((\text{SC} \ n) \ c) \\
&= (\text{SUC} \ (\text{FST} \ c), \ (\lambda x. \ (x = n) \to (\text{SUC} \ (\text{SND} \ c \ n)) \mid (\text{SND} c x))) \land \\
(\forall m \ c. \ \text{exec}\_\text{instruction} ((\text{TF} m m) \ c) \\
&= (\text{SUC} \ (\text{FST} \ c), (\lambda x. \ (x = m) \to (\text{SND} c n) \mid (\text{SND} c x))) \land \\
(\forall m \ p' \ c. \ \text{exec}\_\text{instruction} ((\text{JP} n m p') \ c \\
&= (((\text{SND} c n = \text{SND} c m) \to p' \mid (\text{SUC} \ (\text{FST} c))),\text{SND} c))
\end{align*}
\]
The execution of a number of steps of a URM program is then given by the primitive recursive function \( \text{EXEC\_STEPS}: \text{num} \to \text{program} \to \text{config} \to \text{config} \), such that \( \text{EXEC\_STEPS}\ n\ P\ c_0 = c_1 \) if and only if \( P(c_0) \rightarrow n\ c_1 \)
\[
\vdash \text{def } (\forall P\ c. \ \text{EXEC\_STEPS}\ 0\ P\ c = c) \land \\
(\forall n\ P\ c. \ \text{EXEC\_STEPS}\ (\text{SUC}\ n)\ P\ c \equiv \text{EXEC\_STEPS}\ n\ P\ (\text{EXEC\_STEP}\ P\ c))
\]
where \( \text{EXEC\_STEP}: \text{program} \to \text{config} \to \text{config} \) represents one step execution of a given program,
\[
\vdash \text{def } \forall P\ c. \ \text{EXEC\_STEP}\ P\ c = ((\text{Final}\ P\ c) \to c \land (\text{exec\_instruction}\ (\text{EL}\ (\text{FST}\ c)\ P)\ c))
\]
and the predicate \( \text{Final}: \text{program} \to \text{config} \to \text{bool} \) holds for final configurations.
3.2 Computations
A finite list of natural numbers is transformed into an initial URM configuration by the function \( \text{set\_init\_conf}: (\text{num\ list}) \to \text{config} \), and \( \text{CONVERGES}: \text{program} \to (\text{num\ list}) \to \text{num} \to \text{bool} \) and \( \text{DIVERGES}: \text{program} \to (\text{num\ list}) \to \text{bool} \) represent converging and diverging computations respectively. It is shown that a program converges to a unique value unless it diverges.
\[
\vdash \forall P\ 1. (\exists! v. \ \text{CONVERGES}\ P\ 1\ v) \lor \text{DIVERGES}\ P\ 1
\]
3.3 Computable Functions
Since the functions which are considered are not necessarily total, a polymorphic type of \emph{possibly undefined values} is defined. Elements of this type are either undefined or have a single value:
\[
'a\ PP := \text{Undef} \lor \text{Value } 'a
\]
The domain of functions is then chosen to be the type of possibly partial numbers. Since the functions have different arities, the codomain is chosen to be the type of lists of numbers, where the length of the list represents the function’s arity:
\[
\text{pfunc} == :\text{num\ list} \to \text{num\ PP}
\]
A program computes a function if and only if it converges to the value of the application of the function whenever this is defined,
\[
\vdash \text{def } \forall n\ P\ f. \ \text{COMPUTES}\ n\ P\ f = (\forall l\ v. (\text{LENGTH}\ l = n) \Rightarrow (\text{CONVERGES}\ P\ 1\ v = (f\ l = \text{Value}\ v)))
\]
such that \( \text{COMPUTES}\ n\ P\ f \) holds if \( P \) computes the \( n \)-ary function \( f \). Finally, a function is computable if there is a program which computes it.
\[
\vdash \text{def } \forall f. \ \text{COMPUTABLE}\ n\ f = (\exists P. \ \text{COMPUTES}\ n\ P\ f)
\]
3.4 Manipulating URM Programs
The proof that a particular function is computable usually involves the construction of a URM program which computes it. The URM instruction set is rudimentary and it would be impractical as a general purpose programming language without a mechanism for concatenating program segments, and without a number of program modules performing simple but often used tasks.
An operator $\oplus$ can be defined such that, given two programs $P_1$ and $P_2$, the computation of $P_1 \oplus P_2$ is given by the individual computation of the two programs. This is achieved by first adding the length of $P_1$ to the destination of the jumps in $P_2$ and then appending the two programs together using the normal list concatenation function. The destination of the jumps in $P_2$ need to be altered since URM jump instructions are absolute, rather than relative. However, in order that the required property is achieved, the programs must be in standard form, in the sense that the destinations of all their jumps are less than or equal to the length of the program. This is required so that the program counter of any final configuration is equal to the length of the program; in particular the program counter of a final configuration of $P_1$ is equal to its length and thus the next instruction executed in the combined computation of $P_1 \oplus P_2$ is the first one in $P_2$. This does not constitute any restrictions since it is proved that any program can be transformed into standard form by setting the destination of out of range jumps to the length of the program. Moreover, it can be proved that $P_1 \oplus P_2$ diverges if one of the component programs diverges.
The transformation of programs into standard form is given by the function $\text{SF}: \text{program} \rightarrow \text{program}$ and the proof that for any program $P$, its behaviour is equivalent to $\text{SF } P$ is done by first showing that after a single step of the execution of both programs the resulting configurations are equivalent. Two configurations are equivalent either if they are the same, or both are final and have the same store. This result is then extended for any number of execution steps and finally it is proved that
$$\vdash \forall P \, \forall v. \text{CONVERGE (SF } P \text{) } l \, v = \text{CONVERGE } P \, l \, v$$
by showing that if one program converges in a number of steps then the other converges in the same number of steps.
The concatenation operator $\oplus$ is defined in HOL as the function $\text{SAPP}: \text{program} \rightarrow \text{program} \rightarrow \text{program}$, and since it is often required to concatenate more than two programs, a function $\text{SAPPL}: \text{program list} \rightarrow \text{program}$ which concatenates a given list of programs is defined as well.
The following three simple program modules which are used quite often in the construction of general URM programs:
- $\text{SET\_FST\_ZERO } n$ stores the value 0 in the registers $(R_0, R_1, \ldots, R_n)$.
- $\text{TRANSFER\_FROM } p \, n$ stores $(r_p, r_{p+1}, \ldots, r_{p+n-1})$ into $(R_0, R_1, \ldots, R_{n-1})$.
- $\text{TRANSFER\_TO } p \, n$ store $(r_0, r_1, \ldots, r_{n-1})$ into $(R_p, R_{p+1}, \ldots R_{p+n-1})$.
are defined as follows:
\[ \vdash \text{def } \forall n. \text{SET\_FST\_ZERO } n = \text{GENLIST } ZR (\text{SUC } n) \]
\[ \vdash \text{def } \forall n. \text{TRANSFER\_FROM } p n = \text{GENLIST } (\lambda x. \text{TF } (p + x) x) n \]
\[ \vdash \text{def } \forall n. \text{TRANSFER\_TO } p n \\
\quad = \text{REVERSE } (\text{GENLIST } (\lambda x. \text{TF } x (p + x)) n) \]
where \text{GENLIST} and \text{REVERSE} are defined in the List theory of HOL. The programs yielded by these functions are proved to converge and to convey their expected behaviour by induction on the number of steps of execution of the programs.
Another program module, which is given by \([P p_n p_v]\), or by the term \text{PSHIFT } P p_n p_v, is defined. This program module executes \(P\), taking its \(n\) parameters from the memory segment at offset \(p_s\) rather than from the first \(n\) registers. Also, this program stores the value of the computation in \(R_{p_v}\) rather than the first register. This is defined by:
\[ \vdash \text{def } \forall p s n p v. \text{PSHIFT } P p s n p v \\
\quad = \text{SAPPL } [\text{SET\_FST\_ZERO } (\text{MAXREG } P); \\
\quad \text{TRANSFER\_FROM } p n; \\
\quad P; \\
\quad [\text{TF } 0 p v]] \]
where \text{MAXREG } \(P\) is the maximum register used by \(P\) and is denoted by \(\rho(P)\).
The proofs that \([P p_s p_v]\) diverges if and only if \(P\) diverges, and that if the former converges it yields the expected configuration, are done by applying the result that the computation of programs constructed by \(\oplus\) is made up from the computations of the constructing programs.
### 4 Constructing Computable Functions
In this section we show that a number of basic functions are computable and that the family of computable functions is closed under the operations of substitution, recursion and minimalisation. These results yield a mechanism for constructing computable functions and automatically proving their computability. Moreover, the set of functions which are constructed by the above operations, which is called the set of partial recursive functions, is equal to the set of computable functions \([4,10]\). Thus particular functions can be proved to be computable by proving their equality to some partial recursive function. However this process is not decidable; nevertheless a number of symbolic animation tactics \([2]\) have been implemented which simplify the proof of theorems stating such an equality.
The verification of the closure properties involves the construction of a URM program which is proved to compute the function constructed by the particular operation being considered. Due to space limitations, only the proof of the closure under recursion is illustrated in detail.
4.1 The Basic Functions
The following three basic functions are considered:
1. The zero functions (each of different arity) which return 0 for any input:
\[ \forall n, x_0, \ldots, x_{n-1}. Z(x_0, \ldots, x_{n-1}) = 0, \]
2. the successor function which increments its input by one:
\[ \forall x_0. S(x_0) = x_0 + 1, \]
3. and projections, which return a particular component from a given vector:
\[ \forall n, i < n, x_0, \ldots, x_{n-1}. \Pi_i^n(x_0, \ldots, x_{n-1}) = x_i. \]
These functions are defined in HOL as follows:
\[ \def \text{def} \quad \forall l. \ \text{ZERO} \ l \ = \ \text{Value} \ 0 \]
\[ \def \text{def} \quad \forall l. \ \text{SUCC} \ l \ = (\text{LENGTH} \ l \ = \ 1) \to (\text{Value} \ (\text{SUC} \ (\text{HD} \ l))) \ | \ \text{Undef} \]
\[ \def \text{def} \quad \forall i \in \ l. \ \text{PROJ} \ i \in \ l \ = ((i < n) \to (\text{Value} \ (\Pi_i^n \ l))) \ | \ \text{Undef} \]
and are proved to be computable by showing that the programs [ZRF0] and [SFC0] compute \( Z \) and \( S \) respectively; and that the projection \( \Pi_i^n \) is computed by [TIF0] for \( i < n \) and since it is undefined for \( i \geq n \) it is computed by [JP000]. The function \( \Pi_i^n \) returns the \((i + 1)\)th element of \( l \) if \( i \) is less than the length of \( l \); otherwise it returns 0.
4.2 Substitution
The substitution of \( k \)-ary functions \( g = (g_0, \ldots, g_{k-1}) \) into a \( k \)-ary function \( f \) gives the \( n \)-ary function produced by applying \( f \) on the results of the applications of \( g \). That is,
\[ f^g(x_0, \ldots, x_{n-1}) = f(g_0(x_0, \ldots, x_{n-1}), \ldots, g_{k-1}(x_0, \ldots, x_{n-1})). \]
This is defined in HOL as the function \( \text{FSUBS}: \text{pfunc} \to \text{pfunc list} \to \text{pfunc} \).
\[ \def \text{def} \quad \forall f \ l. \ \text{APPLY} \ f \ l \ = ((\text{ALL_EL DEFINED} \ l) \to (f \ (\text{MAP} \ \text{VALUE} \ l))) \ | \ \text{Undef} \]
\[ \def \text{def} \quad \forall f \ gl \ l. \ \text{FSUBS} \ f \ gl \ l \ = \ \text{APPLY} \ f \ (\text{MAP} \ (\lambda g. \ g) \ gl) \]
In order to prove that computable functions are closed under substitution, it is required to show that given the programs \( P_f, P_{g_0}, \ldots, P_{g_{k-1}} \) which compute the functions \( f, g_0, \ldots, g_{k-1} \) respectively, a program \( P_{f^g} \) can be constructed which computes \( f^g \). Such a program is shown in Fig. 1. The program parameters are first transferred to some memory location at offset \( p_e \). The programs \( P_{g_i} \) for \( i < k \) are then executed one at a time storing their results into another memory segment starting at \( p_v \), and finally \( P_f \) is executed on the results. The value of \( p_s \) is chosen to be \( \max(n, k, \rho(P_f) + 1, \max(\rho(P_{g_0}), \ldots, \rho(P_{g_{k-1}})) + 1) \) so that the contents of this memory segment is not altered during the program execution. Similarly, \( p_v \) is set to \( p_s + n \).
start: TRANSFER_TO $p_s$ n store parameters in $(r_{p_s}, \ldots, r_{p_s+n-1})$
inner: $[P_{g_0} p_s \rightarrow p_v]$
: for each $i < k$ execute $P_{g_i}$
$[P_{g_i} p_s \rightarrow (p_v + i)]$ storing its result in $R_{p_v+i}$
: $[P_{g_{k-1}} p_s \rightarrow (p_v + k - 1)]$
outer: $[P_f p_v \rightarrow 0]$ execute $P_f$ on the values returned by the $P_{g_i}$'s
Fig. 1. The program $P_{f_n}$
4.3 Recursion
Given an $n$-ary base case function $\beta$ and an $(n + 2)$-ary recursion step function $\sigma$, the $(n + 1)$-ary recursive function $R(\beta; \sigma)$ is defined as follows:
$$R(\beta; \sigma)(0, x_0, \ldots, x_{n-1}) = \beta(x_0, \ldots, x_{n-1})$$
$$R(\beta; \sigma)(x + 1, x_0, \ldots, x_{n-1}) = \sigma(x, R(\beta; \sigma)(x, x_0, \ldots, x_{n-1}), x_0, \ldots, x_{n-1})$$
and is specified in HOL as the function $\text{FREC}: \text{pfunc} \rightarrow \text{pfunc} \rightarrow \text{pfunc}$.
$$\vdash \text{def } (\forall \text{basis step } 1. \ \text{RECURSION basis step } 0\!1 = \text{basis } 1) \land$$
$$\ (\forall \text{basis step } n\!1. \ \text{RECURSION basis step } (\text{SUC } n)\!1 =$$
$$\ (\text{let } r = \text{RECURSION basis step } n\!1 \text{ in})$$
$$\ (\text{DEFINED } r) \rightarrow \ (\text{step } (\text{CONS } n (\text{CONS } (\text{VALUE } r)\!1)))$$
$$\ | \text{Undef}))$$
$$\vdash \text{def } \forall \text{basis step } 1.$$
$$\text{FREC basis step } 1 =$$
$$\ ((1 = [])) \rightarrow (\text{basis } [1])$$
$$\ | \ (\text{RECURSION basis step } (\text{HD } 1) (\text{TL } 1)))$$
Given the programs $P_\beta$ and $P_\sigma$ which compute the functions $\beta$ and $\sigma$ respectively, the program $P_{R(\beta; \sigma)}$ shown in Fig. 2 computes the recursive function $R(\beta; \sigma)$. The value of $p_c$ is chosen to be $\max(p(P_\beta) + 1, p(P_\sigma) + 1, n + 2)$ so that the registers starting at $p_c$ are not used by $P_\beta$ and $P_\sigma$; and the values of $p_v$, $p_s$ and $p_x$ are chosen to be $p_c + 1, p_v + 1$ and $p_s + n$ respectively. The register $R_{p_c}$ is used to store a counter for the number of times the inner loop
is executed. The value of each recursion step is stored at \( R_{p_v} \) and the memory segment \((R_{p_0}, \ldots, R_{p_n}, n-1)\) is used to store the function’s parameters, which are transferred by the first step of the program. The register \( R_{p_v} \) stores the depth of the recursion such that the inner loop is repeated \( r_{p_v} \) times after the code computing the base case function, \((P_{\beta} p_s \rightarrow p_v)\), stores \( \beta(x_0, \ldots, x_{n-1}) \) into \( r_{p_v} \). The final value of \( p_v \) is then transferred into the first register \( R_0 \).
This program can be divided into three parts, which we call \( P_{\text{start}}, P_{\text{loop}} \) and \( P_{\text{final}} \). These are represented in HOL by the terms
\[
P_{\text{start}} = \text{SAPPL} \ [\text{TRANSFER_TO } p_v (n + 1); \]
\[\quad \text{TF 0 } p_v; \]
\[\quad \text{PSHIFT } P_{\beta} p_s n p_v] \]
\[
P_{\text{loop}} = \text{let } Ps = \text{PSHIFT } P p_c (n + 2) p_v \text{ in} \]
\[\quad \text{APPEND (SAPP [JP } p_c p_x (3 + \text{LENGTH Ps})] \]
\[\quad \text{Ps)} \]
\[\quad \text{[SC } p_c; \]
\[\quad \text{JP 0 0 0]] \]
\[
P_{\text{final}} = [\text{TF } p_v 0] \]
and \( P_{R(\beta;\sigma)} \) is then given by
\[
\text{SAPPL } [^*P_{\text{start}}; ^*P_{\text{loop}}; ^*P_{\text{final}}] \]
This program is then proved to compute the recursive function by considering whether the base case function \( \beta \) and the step function \( \sigma \) are defined:
- If \( \beta(x_0, \ldots, x_{n-1}) \) is defined then
• $P_\beta$ converges, and so does $[P_\beta \ p_s \ \overset{n}{\rightarrow} \ p_v]$. As a result $P_{\text{start}}$ converges to a final configuration containing the value of $\beta(x_0, \ldots, x_{n-1})$ (which is equal to $R(\beta; \sigma)(0, x_0, \ldots, x_{n-1})$) in the first register, the parameters $(x_0, \ldots, x_{n-1})$ stored in $(R_{p_s}, \ldots, R_{p_s+n-1})$ and $r_{p_s}$ set to the depth $x$.
• If, also the step function $\sigma$ is defined for all values of $i \leq x$ then
* all programs $[P_\sigma p_c \overset{n+2}{\rightarrow} p_v]$ converge for each value of the recursion counter $r_{p_c}$, and hence $P_{\text{loop}}$ converges, placing the final value of the application of $\sigma$ (which is equal to $R(\beta; \sigma)(x, x_0, \ldots, x_{n-1})$) in $(R_{p_c})$;
* and finally $P_{\text{final}}$ stores the value of $R(\beta; \sigma)(x, x_0, \ldots, x_{n-1})$ into the first register. Thus, whenever $R(\beta; \sigma)$ is defined, $P_{R(\beta; \sigma)}$ converges to the required value.
• On the other hand, if $\sigma$ is undefined for some non-zero value $i \leq x$ then
* the program $[P_\sigma p_c \overset{n+2}{\rightarrow} p_v]$ diverges when $r_{p_c} = i - 1$, thus $P_{\text{loop}}$ diverges and so does $P_{R(\beta; \sigma)}$. However, if the step function is undefined then $R(\beta; \sigma)$ is undefined as well. Hence, in this particular case, the function is undefined and the program diverges (as expected).
- Now, if the base case function $\beta$ is undefined then
• $P_\beta$ diverges. As a result, all the programs constructed from it using the $\Rightarrow$ operator diverge. In particular the programs $[P_\beta \ p_s \ \overset{n}{\rightarrow} \ p_v]$, $P_{\text{start}}$ and $P_{R(\beta; \sigma)}$. Also, given that $\beta$ is undefined, then so is $R(\beta; \sigma)$, and even in this final case the recursive function is undefined and the program diverges.
- Thus
1. $P_{R(\beta; \sigma)}$ converges to $R(\beta; \sigma)(0, x_0, \ldots, x_{n-1})$ whenever the latter is defined; and
2. $P_{R(\beta; \sigma)}$ diverges whenever $R(\beta; \sigma)(0, x_0, \ldots, x_{n-1})$ is undefined.
- So, $P_{R(\beta; \sigma)}$ computes $R(\beta; \sigma)$ proving that the latter is computable.
The same method of considering whether the constituting functions of an operation are defined or not, is used in the proofs that substitution and minimalisation of computable functions yield functions which are also computable.
4.4 Minimalisation
The unbounded minimalisation of an $(n+1)$-ary function $f$ is the $n$-ary function given by:
$$\mu_\sigma(f(x_0, \ldots, x_{n-1}) = 0) = \begin{cases}
\text{the least } x \text{ s.t. } f(x, x_0, \ldots, x_{n-1}) = 0, \text{ and for all } x' \leq x \text{ } f(x', x_0, \ldots, x_{n-1}) \text{ is defined} \\
\text{undefined if no such } x \text{ exists.}
\end{cases}$$
This is formalised in HOL by the following definition:
\[ \text{\texttt{def}} \forall f \text{.} \]
\[ \text{\texttt{FMIN}} f \text{.} \]
\[ (\text{let } Z x = f \text{.} (\text{CONS} x 1) = \text{Value} 0 \text{ in } \text{let } n = \text{FIRST THAT } Z \text{ in } \text{(Z n } \wedge (\forall m. m \leq n \Rightarrow \text{DEFINED } (f \text{. (CONS m 1)))) \rightarrow (\text{Value } n | \text{Undef})] \]
where \text{\texttt{FIRST THAT }} R \text{ returns the first natural number } n \text{ such that } R(n) \text{ holds, if such an } n \text{ exists, or any particular value otherwise.}
\[ \text{\texttt{def}} \forall P. \text{\texttt{FIRST THAT}} P = (\exists n. P n \wedge (\forall m. P m \Rightarrow n \leq n)) \]
Given that \( P_f \) computes \( f \), the program \( P_{\mu_x(f(x)=0)} \) shown in Fig. 3 computes the minimalisation function \( \mu_x(f(x) \mapsto 0) \). This is done by executing \( P_f \) until it returns the value 0. The register at position \( p_c \) is used as a counter which is incremented each time \( P_f \) is executed and is returned by \( P_{\mu_x(f(x)=0)} \) if it terminates. The value of \( p_c \) is set to \( \max(p_f + 1, n + 1) \), so that it will not be used by \( P_f \), also the parameters are stored at the memory segment starting at \( p_s \) which is set to \( p_c + 1 \). The value of \( p_0 \) is chosen to be \( p_s + n \) and is not altered during program execution, so that \( r_{p_0} = 0 \).
\[
\begin{align*}
\text{start: TRANSFER TO } & p_s \ n \quad \text{Store parameters in } (R_{p_s}, \ldots, R_{p_s+n-1}) \\
\text{fetch: } [P_f & p_c \ n \rightarrow 0] \quad \text{Execute } P_f \\
& \text{JP 0 } p_0 \text{ final } \quad \text{Until it returns } 0 \\
& \text{SC } p_c \quad \text{Otherwise, increment } r_{p_c} \\
& \text{JP 0 0 } \text{fetch } \quad \text{Jump back to fetch} \\
\text{final: TF } & p_c \ 0 \quad \text{Return } r_{p_c}. \\
\end{align*}
\]
Fig. 3. The program \( P_{\mu_x(f(x)=0)} \)
4.5 Proving the Computability of Particular Functions
The operations mentioned above make up the language of partial recursive functions and are sufficient to build up the family of computable functions. A HOL conversion simulating the application of function terms constructed using these constructs is implemented. The three basic functions are automated by simply
rewriting with the appropriate definitions; substitution is automated by first evaluating each of the substituting functions and then evaluating the function into which these functions are substituted. A function defined by recursion is animated by evaluating either the base case function, or the step function recursively. A function constructed by minimalisation, $\mu_x(f(x) \mapsto 0)$, is animated by first proving that if for some $i$, $f(i) = 0$ and for all $j < i$, $f(j)$ is defined and is greater than 0, then $\mu_x(f(x) \mapsto 0) = i$. By evaluating $f(j)$, for $j = 0, 1, \ldots$ one can construct a theorem which states that $\forall j, j' < j \Rightarrow f(j) > 0$ until $j = i$ and thus $f(j) = 0$. This theorem and the evaluation of $f(i)$ are then used to prove that $\mu_x(f(x) \mapsto 0) = i$, thus evaluating the minimalisation function.
This conversion is used to prove that particular functions are equal to some specified partial recursive function. In general an equality to a function constructed by substitution is proved by applying this conversion on the functional
application term and then proving the equality of the resulting terms (often by simple rewriting of the definitions); and equality to a function defined by recursion is proved by mathematical induction and then applying this conversion on the base case and induction step subgoals. Since the simulation of minimalisation involves a possibly non-terminating fetching process (when the function is total and never returns 0) the execution of this conversion may diverge, in such case this conversion cannot be used in the required proof; although if the fetching process terminates the proof of the equality of functions defined by minimalisation is otherwise relatively straightforward.
Moreover, since partial recursive functions are constructed from three basic functions which are proved to be computable and by three operators which are proved to preserve computability, the process of proving that such functions are computable can be automated. Given a conversion which automates this mechanism, the proof that a function is computable simply involves showing that it is equal to some partial recursive function. Figure 4 lists a number of functions which are proved to be computable.
5 Theorem Proving in HOL
The proofs of most of the results in this mechanisation tend to be quite elaborate and involve the consideration of details which are often omitted in the proofs given in mathematical texts. This is often the case with mechanical verification since most of the definitions and proofs done by hand and represented in texts omit a number of steps which are considered to be trivial or not interesting to the reader. For example the proof that for every URM program one can construct a program in standard form which has an equivalent behaviour (Sect. 3.4) is considered to be trivial in [4], although it requires a considerable number of lemmas concerning the behaviour of executing URM programs in general and programs transformed into standard form by the function $\text{SF}$. Also, in the proofs that computable functions are closed under the operations of substitution, recursion and minimalisation, little or no attention is given in showing that the program constructed to compute the required function diverges whenever the function is undefined, probably because this part of the proof is considered uninteresting. It is to note, however, that such proofs usually offer an interesting challenge in a mechanisation.
However, an advantage of theorem proving in HOL and other LCF style theorem provers is the availability of a flexible general purpose meta-language which can be used in the implementation of program modules which simulate the behaviour of the formal definitions as well as intelligent algorithms which automate parts of the verification process. In this particular implementation, such a mechanism is found to be quite useful in the verification of general computable functions. On the other hand, theorem proving in Coq is usually done by applying tactics through the specification language Gallina. This offers the advantage that unless a number of specialised tactics need to be implemented, the user does not need any knowledge on how the actual terms and theorem are
represented in the implementation of the theorem prover and is thus easier to learn than HOL. Another advantage of having a specification language which bridges the user from the meta-language is that proofs can be easily represented as lists, or trees of tactics in a format which can be read by the user. However such an approach has the disadvantage that it reduces the flexibility of the system and discourages the user from implementing his or her own tactics.
Type theories allow the definition of dependent types where a type can be parametrised by other types, and thus offer a more powerful and flexible type definition mechanism than the one available in HOL. For example, the type of functions which are considered for computability are defined as mappings from lists of numbers to possibly partial numbers (Sect. 3.3) and the type itself contains no information regarding the function’s arity. In an implementation in Coq, an n-ary partial function is defined as a single valued relation between vectors of n elements and natural numbers. Vectors are defined as the following inductive dependent type:
\[
\text{Inductive vector } [A: \text{Set}]: \text{nat} \to \text{Set} \\
\quad := \text{Vnil}: (\text{vector } A \ 0) \\
\quad \mid \text{Vcons}: (n: \text{nat})A \to (\text{vector } A \ n) \to (\text{vector } A \ (S \ n)).
\]
and partial functions as a record with two fields:
\[
\text{Record pfunc } [\text{arity: } \text{nat}]: \text{Type} := \text{mk_pfunc} \\
\quad \{ \text{reln}: (\text{Rel } (\text{vector } \text{nat arity}) \ \text{nat}); \\
\quad \text{One_value}: (\text{one_value } (\text{vector } \text{nat arity}) \ \text{nat reln}) \}.
\]
The first field \(\text{reln}\) represents the function as a relation and the second field \(\text{One_value}\) is a theorem which states that \(\text{reln}\) is single valued. Relations are defined by:
\[
\text{Definition Rel } := [A,B: \text{Set}]A \to B \to \text{Prop}.
\]
and the predicate \(\text{one_value}\) by:
\[
\text{Definition one_value} \\
\quad := [A,B: \text{Set}][R: (\text{Rel } A B)](a: A)(b1, b2: B) \\
\quad \quad (R \ a \ b1) \to (R \ a \ b2) \to (b1 = b2).
\]
Finally the type of all partial functions is defined as the dependent product
\[
\text{Inductive pfuncs}: \text{Type} \\
\quad := \text{Pfuncs}: (n: \text{nat})(\text{pfunc } n) \to \text{pfuncs}.
\]
Possible enhancements to theorem proving in the HOL system include mechanisms for naming or numbering assumptions in a goal-directed proof, for allowing constant redefinition and the declaration of local definitions. Proofs found in mathematical texts often contain definitions which are only used in showing a number of particular results. Such definitions can be made local to the results which require them. For example, in the proof that computable functions are
closed under recursion (Sect. 4.3) the constants $P_{\text{start}}$, $P_{\text{loop}}$ and $P_{\text{final}}$ are used only in obtaining this particular results. Such constants are defined as local meta-language variable definitions, however a more elegant approach would involve a theory structure mechanism where constants can be defined local to a theory module and made invisible outside their scope.
6 Conclusion
The mechanisation of computability theory discussed above includes the definition of a computable function according to the URM model and the proof of various results of the theory of which we have given particular attention to the closure property of computable functions under the operations of substitution, recursion and minimalisation. This result is used in the implementation of a process which automates the proof of the computability of functions constructed from these operations and a number of basic computable functions. In the future, it is expected that the theory will be extended through the proof of a number of theorems including the denumerability of computable functions, the $S_m$ theorem and the universal program theorem.
A mechanisation of computability theory is also being implemented in the Coq proof assistant. This implementation uses the partial recursive function model of computation and will include the proof of the results mentioned in the previous paragraph. These two implementations and other work in Alf are expected to yield a comparative study of the different theorem proving approaches.
7 Acknowledgements
I thank my supervisor, Simon Thompson, for his continuous support and for his comments on the material presented in this paper, as well as the anonymous referees for their constructive comments on the first draft of this paper.
References
|
{"Source-Url": "https://kar.kent.ac.uk/21347/1/HOL_Zammit.pdf", "len_cl100k_base": 10947, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 57866, "total-output-tokens": 12957, "length": "2e13", "weborganizer": {"__label__adult": 0.0003767013549804687, "__label__art_design": 0.0004875659942626953, "__label__crime_law": 0.000518798828125, "__label__education_jobs": 0.0019702911376953125, "__label__entertainment": 0.0001291036605834961, "__label__fashion_beauty": 0.00020706653594970703, "__label__finance_business": 0.00040531158447265625, "__label__food_dining": 0.0005817413330078125, "__label__games": 0.000912189483642578, "__label__hardware": 0.0019178390502929688, "__label__health": 0.0009627342224121094, "__label__history": 0.00041961669921875, "__label__home_hobbies": 0.0001819133758544922, "__label__industrial": 0.000927448272705078, "__label__literature": 0.0005908012390136719, "__label__politics": 0.0004189014434814453, "__label__religion": 0.0008130073547363281, "__label__science_tech": 0.29296875, "__label__social_life": 0.00012254714965820312, "__label__software": 0.00952911376953125, "__label__software_dev": 0.68408203125, "__label__sports_fitness": 0.00034117698669433594, "__label__transportation": 0.0007958412170410156, "__label__travel": 0.00020754337310791016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41663, 0.01534]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41663, 0.80856]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41663, 0.82231]], "google_gemma-3-12b-it_contains_pii": [[0, 1298, false], [1298, 3917, null], [3917, 7012, null], [7012, 9741, null], [9741, 12441, null], [12441, 15729, null], [15729, 18464, null], [18464, 21451, null], [21451, 23563, null], [23563, 25097, null], [25097, 28047, null], [28047, 30336, null], [30336, 31434, null], [31434, 34647, null], [34647, 37478, null], [37478, 40121, null], [40121, 41663, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1298, true], [1298, 3917, null], [3917, 7012, null], [7012, 9741, null], [9741, 12441, null], [12441, 15729, null], [15729, 18464, null], [18464, 21451, null], [21451, 23563, null], [23563, 25097, null], [25097, 28047, null], [28047, 30336, null], [30336, 31434, null], [31434, 34647, null], [34647, 37478, null], [37478, 40121, null], [40121, 41663, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41663, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41663, null]], "pdf_page_numbers": [[0, 1298, 1], [1298, 3917, 2], [3917, 7012, 3], [7012, 9741, 4], [9741, 12441, 5], [12441, 15729, 6], [15729, 18464, 7], [18464, 21451, 8], [21451, 23563, 9], [23563, 25097, 10], [25097, 28047, 11], [28047, 30336, 12], [30336, 31434, 13], [31434, 34647, 14], [34647, 37478, 15], [37478, 40121, 16], [40121, 41663, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41663, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
870fbbe784d5a0a9f6164b8c9739ce20ac632e5f
|
Training on Errors Experiment to Detect Fault-Prone Software Modules by Spam Filter
Osamu Mizuno
Graduate School of Information Science and Technology, Osaka University
1-5 Yamadaoka, Suita
Osaka 565-0871, Japan
o-mizuno@ist.osaka-u.ac.jp
Tohru Kikuno
Graduate School of Information Science and Technology, Osaka University
1-5 Yamadaoka, Suita
Osaka 565-0871, Japan
kikuno@ist.osaka-u.ac.jp
ABSTRACT
The fault-prone module detection in source code is of importance for assurance of software quality. Most of previous fault-prone detection approaches are based on software metrics. Such approaches, however, have difficulties in collecting the metrics and constructing mathematical models based on the metrics.
In order to mitigate such difficulties, we propose a novel approach for detecting fault-prone modules using a spam filtering technique, named Fault-Prone Filtering. Because of the increase of needs for spam e-mail detection, the spam filtering technique has been progressed as a convenient and effective technique for text mining. In our approach, fault-prone modules are detected in a way that the source code modules are considered as text files and are applied to the spam filter directly.
This paper describes the training on errors procedure to apply fault-prone filtering in practice. Since no pre-training is required, this procedure can be applied to actual development field immediately. In order to show the usefulness of our approach, we conducted an experiment using a large source code repository of Java based open source project. The result of experiment shows that our approach can classify about 85% of software modules correctly. The result also indicates that fault-prone modules can be detected relatively low cost at an early stage.
Categories and Subject Descriptors
D.2.5 [Software Engineering]: Testing and Debugging—Debugging aids; D.2.8 [Software Engineering]: Metrics—Product metrics; H.2.8 [Database Management]: Database Applications—Data mining
General Terms
Measurement, Reliability
Keywords
spam filter, fault-prone modules, text mining
1. INTRODUCTION
Fault-prone code detection is one of the most traditional and important area in software engineering. Once fault-prone modules are detected at an early stage of the development, developers can take notice on the detected modules more carefully. Furthermore, it is useful to keep track on the fault-prone modules in order to prevent injecting another faults in them.
Various studies have been done in the detection of the fault-prone modules [1, 3, 6, 9, 11–17, 22]. Most of them used some kind of software metrics, such as program complexity, size of modules, object-oriented metrics, and so on, and constructed mathematical models to calculate fault-proneness.
We have introduced a spam filter based approach, named Fault-Prone Filtering, to detect fault-prone modules [18]. The spam filter is one of the most widely used text mining applications. According to Postini Inc.’s report, 94% of entire e-mail messages on the Internet are spam on November 2006 [21]. Such explosive increase of spam e-mail messages triggered development of a lot of spam filtering techniques [2, 20]. In the spam e-mail filtering, incoming e-mail messages are classified into spam or ham (non-spam) based on the frequency of tokens appeared in e-mail messages. Recently, since the usefulness of Bayesian theory for the spam filtering has been recognized, most of spam filtering tools implemented them. Consequently, the accuracy of spam detection has been improved drastically.
Inspired by the spam filtering technique, we tried to apply text mining technique to the fault-prone detection. In the fault-prone filtering, we consider a software module as an e-mail message, and assume that all of software modules belong to either fault-prone(FP) or not-fault-prone(NFP). In the previous research [18], although we have conducted experiments using 10-fold cross validation, the experiments were not sufficient to show practical usefulness of our approach. Furthermore, the target software in the experiment was relatively small.
In this paper, we thus conduct a new experiment based on training on errors(TOE) procedure that can simulate practical situation. Training on errors procedure is a reasonable way of classification and training of spam e-mail filtering. In this procedure, e-mail messages are classified in arrival order. Only misclassified e-mail messages are used for training for further classification. This procedure reduces the time for training and avoids too much training.
The experiment is prepared to simulate actual TOE process using the source code repository of eclipse project [7]. For the experiment, methods in Java code are considered as software modules. FP and NFP modules are then collected from the repository. We then conducted TOE simulation using about 1.2 million modules and classified them into FP or NFP. The result of experiment shows...
that our approach can detect about 90% of modules correctly. Furthermore, we can see that about 85% actual FP modules can be predicted correctly and critical misclassifications rarely happen.
The rest of this paper is organized as follows: Section 2 describes related works to this study. The outline of “fault-prone filtering” is then described in Section 3. An experiment to show the effectiveness of our approach is shown in Section 4. Section 5 discusses the result obtained in the experiment. In Section 6, we compared our approach with other fault-prone prediction studies based on survey. Section 7 addresses the threats to validity of this study. Finally, Section 8 summarizes this study and also addresses the future work.
2. RELATED WORKS
2.1 Fault-Prone Detection
Much research on detection of fault prone software modules has been carried out so far. Just looking for works since 1999, a lot of fault prone prediction studies are found [1, 3, 6, 9, 11–17, 22]. Previous studies can be categorized by data sets, metrics, and classification techniques.
Data sets used in these studies are three folds: public domain, open source, and original. First, as for the public domain data sets, one of the most famous public domain data set is the NASA’s Metrics Data Program(MDP) [19]. For example, studies such as [9, 17, 22] used the NASA’s MDP. By using such public domain data sets, a new approach can be easily comparable with other approaches. Our approach, however, cannot be applied to such data sets since it requires raw software code. Next, as for the open source software data, studies such as [3, 6] collected and used for the evaluation of their fault-prone prediction approaches. Finally, original data sets are usually used in empirical studies in industries [1, 15]. Especially, Khoshgoftaar used a data from very large embedded software system and evaluated classification techniques [15].
Software metrics related to program attribute such as lines of code, complexity, frequency of modification, coherency, coupling, and so on are used in most of previous studies. In those studies, such metrics are considered as explanatory variables and fault-proneness are considered as an objective variable. Then mathematical models are constructed from those metrics. The selection of metrics varies according to studies. For example, studies such as [9, 17, 22] used NASA MDP collected metrics. The object oriented metrics are used in [3]. Some studies used metrics based on metrics collection tools [1, 6].
Our approach does not use software metrics explicitly. Accurately speaking, it uses the frequency of tokens (combination of words) in code modules as metrics. To our best knowledge, there is no work that used the frequency of tokens as predictors of fault proneness. The calculation of frequency of tokens is done by spam filtering tool. Brief explanation of calculation is shown in subsection 3.4.
Selection of classification techniques also varies according to studies. Khoshgoftaar et al. has been performed a series of fault-prone prediction studies using various classification techniques. For example, classification and regression trees [16], tree-based classification with S-PLUS [13], the Treedisc algorithm [12], Sprint-Sliq algorithm [14], logistic regression [11]. The comparison was summarized in [15]. Logistic regression is one of frequently used technique in fault-prone prediction [3, 6, 11]. Menzies et al. compared three classification techniques and reported that Naive Bayesian classifier achieved the best accuracy [17].
Our approach adopted Markov random field for the classification technique. Since it is an extension of naive Bayesian classifier, it is expected to achieve good accuracy. The comparative study based on survey is shown in Section 6.
2.2 Spam E-mail Filtering
SPAM e-mail filtering is one of the most practical application of text classification technique nowadays.
At an early stage of spam filtering software, it was mainly based on pattern matching using dictionaries of spam-prone words in e-mail messages. However, it is difficult to deal with new spam e-mail messages including new words. As a result, spammers and spam filters have been in the rat race.
Graham stated in his article that most spam e-mail messages can be automatically classified by Bayesian classification in his article [8]. The merit of Bayesian classification is flexibility for new spam messages and user’s correction. Inspired by his article, various spam filtering software based on Bayesian classification have been developed [2, 20]. Since traditional spam filters such as SpamAssassin [25] also implemented Bayesian technique in them, Bayesian classification becomes essential technique for spam filtering nowadays.
CRM114 is developed by Yerazunis [4] as an extension of Bayesian classification based filtering and it has remarkable accuracy on detecting spam messages. Since it is implemented as a generic text discriminator, it can be applied to not only spam filtering but also data stream analysis.
3. FAULT-PRONE FILTERING
3.1 Fundamental Idea
The basic idea of fault-prone filtering is inspired by spam mail filtering. In the spam mail filtering, the spam filter first trains both spam and ham (non-spam) e-mail messages from training data set. Then, an incoming e-mail is classified into either ham or spam by the spam filter.
This framework is based on the fact that spam e-mail usually include particular patterns of words or sentences. From a viewpoint of source code, similar situation usually occurs in faulty software modules. That is, similar faults may occur in similar contexts. We thus guess that faulty software modules have similar pattern of words or sentences like spam e-mail messages. In order to grab such features, we adopted a spam filter in fault-prone module prediction.
Intuitively speaking, we try to introduce a new metric as a fault-prone predictor. The metric is “frequency of particular words”. In more detail, we do not treat a single word, but we use combinations of words for the prediction. Thus, the frequency of a certain length of words is only the metrics used in our approach.
We then try to apply a spam filter to identification of fault-prone modules. We named this approach as “fault-prone filtering”. That is, the fault-prone trainer first trains both FP and NFP modules. Then, a new module can be classified into FP or NFP using the fault-prone classifier. To do so, we have to prepare spam filtering software and sets of FP and NFP modules.
3.2 Procedure of Filtering (Training on Errors)
In order to apply our approach to data from source code repository, we implemented tools named “FPTrainer” and “FPClassifier” for training and classifying software modules, respectively.
The typical procedure of fault-prone filtering is summarized as follows:
1. Apply FPClassifier to a newly created software module (say,
method in Java, function in C, and so on), $M_i$, and obtain the probability to be fault-prone.
2. By the pre-determined threshold $t_{FP} (0 < t_{FP} < 1)$, classify the module $M_i$ into FP or NFP.
3. When the actual fault-proneness of $M_i$ is revealed by fault report, investigate whether the predicted result for $M_i$ was correct or not.
4. If the predicted result was correct, go to step 1; otherwise, apply FPTrainer to $M_i$ to learn actual fault-proneness and go to step 1.
This procedure is called “Training on Errors (TOE)” procedure because training process is invoked only when classification errors happen. The TOE procedure is quite similar to actual classification procedure in practice. For example, in actual e-mail filtering, e-mail messages are classified when they arrived. If some of them are misclassified, actual results (spam or non-spam) should be trained.
Figure 1 shows an outline of this approach. At this point, we consider that the fault-prone filtering can be applied to the set of software modules which are developed in the same (or similar) project.
### 3.3 Classification Techniques
In this study, we used “CRM114” spam filtering software [5]. The reason why we used CRM114 was its versatility and accuracy. Since CRM114 is implemented as a language to classify text files for general purpose, it is easy to apply source code modules. Furthermore, the classification techniques implemented in CRM114 are mainly based on Markov random field model [4] instead of naive Bayesian classifier.
In this experiment, we used the following 2 classification strategies built in CRM114, which have relatively good accuracy.
SBPH is an extension of Bayesian classification, mapping features in the input text into a Markov Random Field. In this model, tokens are constructed from combinations of $n$ words ($n$-grams) in a text file. In CRM114, the number of words $n$ is set as 5 by default. It is determined by experience of CRM114 developers. Tokens are then stored in corpuses via hash tables.
Intuitively speaking, SBPH constructs tokens at most $n$ words and uses it as predictors.
Using $n$-grams for tokenization seems to be effective for our objective, fault-prone prediction of software source code. For the spam filtering, the simple Bayesian classification can achieve high accuracy of filtering. In the simple Bayesian classification, the frequency of a single word is stored in corpus. However, since the difference between an FP module and an NFP module is more subtle than e-mail messages, a certain combination or sequence of words should be considered.
2. **Orthogonal Sparse Bigrams Markov model (OSB)** [23]
OSB is a simplified version of SBPH and the default classification model used in CRM114. It consider tokens as combinations of exactly 2 words created in the SBPH model. This decreases both memory consumption of training and time of classification. Furthermore, it is reported that OSB usually achieves higher accuracy than SBPH [23] even though it is a simplified version of SBPH.
Intuitively speaking, OSB constructs tokens with 2 words and uses it as predictors.
Let me explain the difference between these two classifiers and typical Bayesian text classifier. The typical Bayesian text classifier utilizes the frequency of single words appeared in input text. In the case of e-mail filtering, the frequency of single words is enough to achieve high accuracy. However, in the case of source code, the problem is more complex. In our previous study, we showed that the use of simple Bayesian text classifier did not achieve enough accuracy [18].
### 3.4 Probability Calculation
Here, we explain how these classifiers works briefly. The difference among these 2 classifiers are in both tokenization and classification.
#### 3.4.1 Tokenization
Since SBPH is a base of all technique, we explain how SBPH tokenizes input text files. At first, words in a source code module are separated by a lexical analyzer. Then, separators such as braces, parentheses, colons, semicolons are deleted. SBPH then picks up a sequence of 5 words. Next, SBPH generates combinations of these words fixing the first word. For example, a sentence “if (x == 1) return;” is tokenized as shown in Figure 2.
For all words in a source code module, the above procedure is applied and tokens are obtained.
In OSB, tokens are extracted from SBPH generated ones so that they include exactly 2 words in it. Thus, in the same example as SBPH, tokens are generated as shown in Figure 3. By definition, the number of tokens drastically decreases compared to SBPH.
#### 3.4.2 Classification
Let $T_{FP}$ and $T_{NFP}$ be sets of tokens included in FP and NFP corpuses, respectively. The probability of fault-proneness is equivalent to the probability that a given set of tokens $T_s$ is included in either $T_{FP}$ or $T_{NFP}$. In SBPH and OSB, the probability that a new module $m_{new}$ is faulty, $P(T_{FP}|T_{m_{new}})$, with given set of token $T_{m_{new}}$, in a new source code module $m_{new}$ is calculated by...
modules and stored in FP corpus. Similarly, tokens
Intuitively speaking, this probability denotes that the new code is
difference between FP and NFP tokens are shown in
Figure 4 (a) includes a bug that
Figure 5 (a) and (b), respectively.
Bigrams are generated from both modules and trained as either FP
Figure 2: Example of tokens for SBPH
```
1: if
2: if x
3: if ==
4: if 1
5: if return
6: if x ==
7: if x 1
8: if x return
9: if == 1
10: if == return
11: if 1 return
12: if x == 1
13: if x == return
14: if x 1 return
15: if == 1 return
16: if x 1 return
```
Figure 4: Example code for classification











Figure 3: Example of tokens for OSB
the following Bayesian formula:
\[
P(T_{FP}|T_{m_{new}}) = \frac{P(T_{m_{new}}|T_{FP})P(T_{FP})}{P(T_{m_{new}}|T_{FP})P(T_{FP}) + P(T_{m_{new}}|T_{NFP})P(T_{NFP})}
\]
Intuitively speaking, this probability denotes that the new code is
classified into FP. According to \( P(T_{FP}|T_{m_{new}}) \) and pre-defined
threshold \( t_{FP} \), classification is performed.
3.5 Classification Example
Here, we present a very simple example of how modules are class-
ified by the OSB. Figures 4 (a) and (b) show examples of FP and
NFP modules, respectively. The module fact intends to cal-
culate a factorial of given x recursively. However, implementation in
Figure 4 (a) includes a bug that ++x in line 3 should be --x.
Assume that FPTrainer trains these 2 modules only. In this case,
Bigrams are generated from both modules and trained as either FP
or NFP. The difference between FP and NFP tokens are shown in
Figure 5 (a) and (b), respectively.
In Figure 5 (a), tokens FPx are trained as characteristic of FP
modules and stored in FP corpus. Similarly, tokens NFPx in Figure
```
1: public int fact(int x) {
2: if (x == 1) return 1;
3: return(x*fact(++x));
4: }
```
(a) Example of an FP module
```
1: public int fact(int x) {
2: if (x == 1) return 1;
3: return(x*fact(--x));
4: }
```
(b) Example of an FP module
5 (b) are trained as NFP and stored in NFP corpus. All other tokens
are stored in both corpuses, too. However, since they are identi-
cal between FP and NFP, they have no effect on future
classification.
Then, assume that a new module shown in Figure 6 is constructed
and have to be classified. After tokenization, we can obtain the to-
kens shown in Figure 7 near line 3 of Figure 6.
We can see that tokens NEW1, NEW2, NEW8 are found in FP cor-
pus. According to equation (1), we can get probability to be fault-
prone for the new module. In this example, \( P(T_{FP}) = P(T_{NFP}) =
1/2 \) since there are only 2 modules trained. The number of tokens in
both FP and NFP corpuses is 58. The number of identical tokens
between FP and new module is 53. The number of identical tokens
between NFP and new module is 50. Thus, \( P(T_{m_{new}}|T_{FP}) = \frac{40}{58} \) and \( P(T_{m_{new}}|T_{NFP}) = \frac{37}{58} \). The probability that the
new code is classified as FP is thus calculated as follows:
\[
P(T_{FP}|T_{m_{new}}) = \frac{\frac{40}{58} \times \frac{1}{2} + \frac{37}{58} \times \frac{1}{2}}{\frac{1}{2}} = 0.519
\]
As a result, a new module in Figure 6 is classified as FP with prob-
ability of 0.519. In fact, the new module has the similar bug that
the FP module in Figure 4 (a) has.
Our approach is based on the tendency that developers often
make similar mistakes and thus inject similar bugs. In other words,
it is a pattern of bugs for individual developer. In this example, making mistake \( \rightarrow x \) for \( \rightarrow x \) tends to take place in different modules. By using spam filtering technique, we try to capture such similar patterns of bugs.
Of course, this is just a trivial example. In the real situation, there is a lot of other tokens that affects classification. The calculation of probability thus becomes complex.
4. TRAINING ON ERRORS EXPERIMENT
4.1 Target Project
For the experiment, we selected an open source project that can track faults. For this reason, we selected eclipse project [7]. Table 1 shows the context of the target project. The eclipse is constructed in Java language, and revisions are maintained by concurrent version control system (cvs). The source repository of cvs used in this study is uploaded one on the eclipse project Web site, and is obtained in 27th January, 2007. We obtained fault reports from the bug database of eclipse project [7]. The total number of faults found in bug database was 40,627 in the following condition: The type of these faults is “bugs”, therefore these faults do not include any enhancements or functional patches. The status of faults are either “resolved”, “verified”, or “closed”, and the resolution of faults is “fixed”. This means that the collected faults have already resolved and fixed and thus fixed revision should be included in the entire repository. The severity of the faults was either blocker, critical, major, normal. We did not use trivial bugs in this research.
4.2 Collection of Fault-Prone Modules for Experiment
We have to collect both fault-prone(FP) modules and non fault-prone(NFP) modules from source code repository for this research. The collection of such modules seems easy for a software project which has a bug database such as an Open Source Software development. However, even in such an environment, the revision control system and bug database system are usually separated and thus tracking on the fault-prone modules needs effort. In the development of software in companies, the situation becomes harder [15].
We thus have to extract FP and NFP modules by ourselves. We assumed the target project is a Java-based development in this study. We also assumed that a module of source code is a method in Java class. We then extracted FP modules from source code based on an algorithm shown by Sliewerski et al. [24].
The following restriction and assumption exist in this collection method:
Restriction We seek FP modules by examining cvs log. Therefore, faults that does not appear in the cvs log cannot be considered. That is, the set of FP modules used in this study is not complete.
Assumption We assume that faults are reported just after they are injected in the software.
At first, we collected the following information from bug database of a target project such as Bugzilla.
- \( FLT \): A set of faults found in bug database.
- \( f_i \): Each fault in \( FLT \).
- \( date(f_i) \): Date in which a fault \( f_i \) is reported.
Here, we consider a software module \( M_i \) as a tuple of \( d_i, m_i, \) and \( s^i_f \), where \( d_i \) is the last modified date of \( M_i, m_i \) is source code of \( M_i \), and \( s^i_f \) is actual fault status (FP or NFP) of \( M_i \).
We then start mining a source code repository according to the following algorithm to extract fault-prone modules.
1. For each fault \( f_i \), find class files \( CL_{FaultFixed} \) in which the fault has just been fixed by checking all revision logs.
2. Extract modules \( MOD_{FaultFixed} \) in classes \( CL_{FaultFixed} \).
3. For each module \( M_i \) in \( MOD_{FaultFixed} \), let \( s^i_f = FP \) if \( M_i \) is unmodified since \( date(f_i) \).
4. Let \( MOD_F = \{ M_i | s^i_f = FP \} \).
5. Extract modules \( MOD_{AllRev} \) in all revision.
6. For each module \( M_i \) in \( MOD_F \), track back older revisions of \( M_i \) and append older revisions of \( M_i \) to \( MOD_{FPold} \) only if the \( M_i \) has remained unchanged until the bug fix.
7. Let \( MOD_{NFP} = MOD_{AllRev} - MOD_{FPold} - MOD_F \).
For each module \( M_k \) in \( MOD_{NFP} \), let \( s^k_f = NFP \).
This algorithm collects fault-prone modules very strictly. In other words, we collect modules in which faults are certainly included. Therefore, some modules are not collected as FP since there is a room that the module is not FP.
An illustrated example of collecting a fault-prone module is shown in Figure 8. In this example, assume that a class \( CL_{FaultFixed} \) has
revisions 1.1, 1.2, · · · , 1.9, and revision logs are appended when each revision is committed. At first, a fault \( f_{100} \) is found in 24th December, 2006. By searching all revision logs, assume that the fixed point is found as revision 1.9 of \( CL_{FaultFixed} \) (Shown as (1) in Figure 8). Then, \( MOD_{FaultFixed} \) can be extracted by taking a difference between revision 1.8 and 1.9 (Shown as (2) in Figure 8). For each module in \( MOD_{FaultFixed} \), we find modules which are not modified since 24th December, 2006 by searching revision differences. Here, assume that revision 1.6 of \( CL_{FaultFixed} \) is committed in 20th December, 2006. Therefore, we have to check all differences between revision 1.6 and 1.9. Assume that difference between revision 1.7 and 1.8 includes modification to \( x(x) \) and \( z(x) \). Then, we can find that difference between revision 1.6 and 1.7 includes modification to \( z(x) \). We thus do not include \( x(x) \) and \( z(x) \) in revision 1.8 in \( MOD_{FP} \). We implemented a prototype tool named “FPFinder” to track bugs in the cvs repository. The inputs of FPFinder is a cvs repository of target project and a bug report to track. The output of FPFinder are sets of FP modules (\( MOD_{FP} \)) and NFP modules (\( MOD_{NFP} \)).
The result of FPFinder is shown in Table 2. Number of faults found in cvs log was 21,761. It is 52% of total reported faults in the bug database. The number of FP modules corresponded to these faults was 65,782. The number of NFP modules becomes huge, and is 1,113,063.
<table>
<thead>
<tr>
<th># of faults found in cvs log</th>
<th>21,761 (52% of total)</th>
</tr>
</thead>
<tbody>
<tr>
<td># of FP modules ((</td>
<td>MOD_{FP}</td>
</tr>
<tr>
<td># of NFP modules ((</td>
<td>MOD_{NFP}</td>
</tr>
</tbody>
</table>
### 4.3 Procedure of TOE Experiment
In the experiment, we have to simulate actual TOE procedure in the experimental environment. To do so, we first prepare a list of all modules found in subsection 4.2. The list is sorted by the last modified date \( d_i \) of each module so that the first element of the list is the oldest module. We then start simulated experiment in the procedure shown in Figure 9. During the simulation, modules are classified in order of date. If the predicted result \( s_i^p \) differs from actual status \( s_i \), the training procedure is invoked.
### 4.4 Result of Experiment
In the experiment we conducted 4 experiments with 2 classifiers and 2 threshold values. That is, (e1) SBPH classifier with \( t_{FP} = 0.50 \), (e2) SBPH classifier with \( t_{FP} = 0.25 \), (e3) OSB classifier with \( t_{FP} = 0.50 \), and (e4) OSB classifier with \( t_{FP} = 0.25 \). On the threshold, \( t_{FP} = 0.50 \) is a normal way of classification. On the other hand, \( t_{FP} = 0.25 \) means that the prediction of modules tends to be FP than \( t_{FP} = 0.50 \). This configuration is reasonable on fault-prone detection since FP modules must not be missed.
For the evaluation of the experiments, we define several evaluation measurements. Table 3 shows a legend of tables for experimental result. In Table 3, \( N_1 \) shows the number of modules that are predicted as NFP and are actually NFP. \( N_2 \) shows the number of modules that are predicted as FP but are actually NFP. \( N_3 \) shows the number of modules that are predicted as FP but are actually FP. \( N_4 \) is the number of correctly predicted modules. Accuracy rate shows the ratio of correctly predicted modules to entire modules and is defined as follows:
\[
accuracy = \frac{N_1 + N_4}{N_1 + N_2 + N_3 + N_4}
\]
The rates of false positive and false negative are defined as follows:
\[
false\ positive\ rate = \frac{N_2}{N_1 + N_4}
\]
\[
false\ negative\ rate = \frac{N_3}{N_2 + N_4}
\]
For evaluation purpose, we used two measurements: recall and precision. Recall is the ratio of modules correctly predicted as FP to number of entire modules actually FP. It is defined as follows:
\[
recall = \frac{N_4}{N_3 + N_4}
\]
Intuitively speaking, the recall implies the reliability of the approach because large recall denotes that actual FP modules can be covered by the predicted FP modules.
---
**Figure 9: Procedure of TOE experiment**
**Table 3: Legend of experimental result**
<table>
<thead>
<tr>
<th>Actual</th>
<th>NFP</th>
<th>FP</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>( N_1 )</td>
<td>( N_2 )</td>
</tr>
<tr>
<td></td>
<td>( N_3 )</td>
<td>( N_4 )</td>
</tr>
</tbody>
</table>
5. ANALYSIS OF EXPERIMENTS
By investigating experimental results in more detail, we can obtain interesting findings.
5.1 Difference between Classifiers
Here we discuss the difference of classifiers. Comparing Table 4 (a) through (d), the difference between the SBPH and OSB is found on the capability of predicting FP modules. We can see in Table 4 (a) and (c) that the numbers of modules predicted as FP, $N_F + N_{FP}$, are 76,736 and 138,060 for SBPH with $t_{FP} = 0.5$ and OSB with $t_{FP} = 0.5$, respectively. Therefore, we can say that OSB tends to predict modules as FP even if it is not correct.
For the SBPH with $t_{FP} = 0.5$, the rates of false positive and false negative are 0.034 and 0.356, respectively (See Table 5.). On the other hand, for the OSB with $t_{FP} = 0.5$, they are 0.087 and 0.129, respectively (See Table 5, too.). In fault-prone detection, it is usually expected that actual FP modules should not be predicted as NFP. Low false negative rate helps to avoid such critical misclassification. Furthermore, the result of experiment showed that execution time of OSB is ten times faster than SBPH.
For these reasons, we conclude that OSB classifier is more better to apply our fault-prone filtering.
5.2 Difference of Threshold
The threshold between FP and NFP is one of the most effective parameters for the classification. From Table 4 (c) and (d), we can see that the number of predicted FP modules drastically increases in the case of OSB classifier. (However, in the case of SBPH shown in Table 4 (a) and (b), the change is much smaller than the case of OSB.) From Table 5, we can see that changing the threshold from 0.5 to 0.25 improves the recall, but the precision becomes worse. Since the recall and the precision is in trade-off, users should determine appropriate threshold for their purpose. In the software development, it is usually required to detect as many FP modules as possible. In such case, lower recall is preferred. However, lower recall increases the precision.
In a case of OSB classifier in the experiment in Table 5, recall improved from 0.728 to 0.839 by changing the threshold from 0.5 to 0.25. This means 83.9% of actual FP modules is covered in the predicted FP modules. However, the precision become 0.347 to 0.232. It means that 34.7% of predicted FP modules is actually FP when $t_{FP} = 0.5$ and the rate decreases to 23.2% when $t_{FP} = 0.25$. This implies the increase of detection cost because about 3 out of 4 FP predicted modules are actually NFP and investigating these 3 modules is in vain for detecting faults. At the same time, changing threshold decreases the number of false negative. The rate of false negative becomes 0.044 when $t_{FP} = 0.25$. In a case of SBPH, similar tendency is observed in Table 5, too. However, the degree of improvement is rather small.
We thus conclude that finding admissible threshold is required for the practical use of our approach.
5.3 Transition of Evaluation Measurements
In Figure 10, it is observed that measurements are not good at an early stage of the development. However, in all cases, the measurements became saturated after classification and training of 50,000 modules. It is about 4% of total number of modules. This fact indicates that TOE procedure works well after a certain period of the development.
Investigating the case of eclipse in more detail, it takes 12 months for the development of initial 50,000 modules. Since the eclipse has been maintained for 6 years long, it needs 1/6 of total period of the development until the fault-prone filtering takes effect.
<table>
<thead>
<tr>
<th>Table 4: Final classification results in TOE experiment</th>
</tr>
</thead>
<tbody>
<tr>
<td>(a) SBPH classifier with $t_{FP}=0.50$</td>
</tr>
<tr>
<td>Actual</td>
</tr>
<tr>
<td>----------</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>(b) SBPH classifier with $t_{FP}=0.25$</td>
</tr>
<tr>
<td>Actual</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>(c) OSB classifier with $t_{FP}=0.50$</td>
</tr>
<tr>
<td>Actual</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>(d) OSB classifier with $t_{FP}=0.25$</td>
</tr>
<tr>
<td>Actual</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
Table 5: Evaluation measurements in TOE experiment
<table>
<thead>
<tr>
<th>Classifiers</th>
<th>SBPH</th>
<th>OSB</th>
</tr>
</thead>
<tbody>
<tr>
<td>threshold ($t_{FP}$)</td>
<td>0.50</td>
<td>0.25</td>
</tr>
<tr>
<td>Accuracy</td>
<td>0.945</td>
<td>0.943</td>
</tr>
<tr>
<td>Recall</td>
<td>0.590</td>
<td>0.600</td>
</tr>
<tr>
<td>Precision</td>
<td>0.506</td>
<td>0.489</td>
</tr>
<tr>
<td>False positive rate</td>
<td>0.034</td>
<td>0.038</td>
</tr>
<tr>
<td>False negative rate</td>
<td>0.351</td>
<td>0.325</td>
</tr>
</tbody>
</table>
Precision is the ratio of modules correctly predicted as FP to number of entire modules predicted as FP. It is defined as follows:
\[ \text{precision} = \frac{N_F}{N_F + N_{FP}} \]
Intuitively speaking, the precision implies the cost of the approach because small precision makes much efforts to find actually FP modules from predicted FP modules.
Table 4 shows the classification results for each experiment at the final point of train on errors experiment. The evaluation measurements for each experiment is shown in Table 5. From the viewpoint of accuracy, SBPH classifiers seems superior to OSB classifier. However, from the viewpoint of recall and false negative, the OSB is better than SBPH. From the viewpoint of threshold of fault-prone judgement, setting the threshold $t_{FP}$ to lower value (that is, more likely to predict FP) makes recall and false negative better in both classifiers.
Figure 10 shows transitions of evaluation measurements for each experiment. In these graphs, the x-axis shows all software modules sorted by dates and smaller number shows older modules. The y-axis shows rates of accuracy, recall, precision, and so on.
The time needed for experiments using SBPH and OSB were 125 hours 11 minutes and 12 hours 15 minutes, respectively, on MacPro workstation with Xeon 2.66GHz processor. Indeed, OSB is ten times faster than SBPH in this experiment. Since there are over 1 million modules to be classified, classification time per module is less than 1 second even in SBPH.
We can also see that recall and precision jumped up just after 150,000 modules. Concretely speaking, recall and precision started to raise up near 158,000 modules and stopped raising near 164,000 modules. During classification of these 6,000 modules, there are few misclassifications for both FP and NFP. Although we cannot see what was happened during this period exactly, we guess that some kind of roll back occurred or a number of code clones [10] are generated in wide area.
As for the transition of evaluation measurements, it is expected that these measurements increase as time elapses because the more training usually achieves more accuracy. However, the recall and the precision do not follow the expectation. It is because the number of false positives ($N_2$ in Table 3) and the number of false negatives ($N_3$) increase more rapidly than the number of correctly predicted as FP ($N_1$). In order to improve this situation, it is required to achieve more accurate fault-prone detection. To do so, for example, the source code oriented classification techniques may be effective.
6. COMPARATIVE STUDY
Since fault-prone prediction is a traditional research theme in software engineering, many works has been done so far. We here compare evaluation measurements with them in order to show the effectiveness of our approach.
For comparison, we did not perform experiments using other methods since contexts of previous studies differ widely. Alternatively, we surveyed previous studies and compare their evaluation measurements shown in their paper with our ones. Thirteen classification results in seven fault-prone prediction studies since 2002 were surveyed. The following describes summaries of these studies:
**Denaro02** Denaro and Pezze proposed a logistic regression based fault-prone prediction [6]. The target is open source software (Apache 1.3 and 2.0). They used 38 metrics that can be collected by tools, RSM and TestBed.
**Briand02** Briand et al. proposed an approach based on principle component analysis(PCA) and logistic regression [3]. They used open source software for experiment, Xpose and JWriter. A model is constructed using 22 object oriented metrics.
**Guo03** Guo et al. used the Dempster-Shafer Belief Networks for fault-prone prediction [9]. They used NASA’s MDP (KC2)
for their case study and thus they used 21 metrics collected in NASA projects.
**Khoshgoftaar04** Khoshgoftaar et al. compared various classification techniques for fault-prone prediction [15]. Classification techniques used in [15] were Sprint-Sliq classification tree, classification and regression tree (CART), Regression tree in S-PLUS, the Treeedisc classification tree, C4.5 classification tree, case-based reasoning (CBR), and logistic regression. They applied their approach to very large embedded system written in high level language (more than 10 million LOC). They used 28 metrics including call graph metrics, control flow graph metrics, statement metrics, and software execution metrics. Ten-fold cross validation is used for evaluation.
**Bellini05** Bellini et al. proposed a discriminant analysis based approach [1]. They showed two data sets, INDUSTRIAL and MEDICAL for experiment. The metrics are collected by CPP analyzer and PAMPA tools, and the number of metrics were 113.
**Seliya05** Semi-supervised clustering based approach was proposed by Seliya et al. [22]. They also used NASA’s MDP (JM1 and KC2), and 13 metrics such as line count, Halstead, McCabe, branch count, are used.
**Menzies07** Menzies et al. compared three classification techniques for fault-prone prediction in [17]. Then they concluded that naive Bayesian classifier is the most accurate. They also used NASA’s MDP (PC1, PC2, PC3, PC4, MW1, KC3, KC4, CM1) and used 38 metrics related to Halstead, McCabe, branch count, are used.
Table 6 shows evaluation measurements (accuracy, recall, and false negative rate) shown in these studies. As mentioned before, since we consider that the recall is the most important in fault-prone prediction, we mainly picked up the best value of recall in each study. If the paper did not show the recall, we collected the best false negative rate instead.
Each row in Table 6 shows the best recall or false negative rate and the corresponding accuracy rate for a classification technique. The mark “*” with a value in Table 6 denotes that the value is the best case in the paper. The mark “**” denotes that the value is average value explicitly shown in the paper. The mark “†” indicates that we calculate the value from the data shown in the paper. The mark “‡” indicates that the value is approximate one since it was read from the graph.
Comparison of recall values showed that Guo03 and Menzies07 achieves extremely high recall in their best cases. However, the value of recall in our approach, 0.845, is still higher than studies such as Denaro02, Briand02, and Bellini05. As for the false negative rate, Khoshgoftaar uses it as an evaluation measure in their fault-prone prediction works. We can see that our approach achieves lowest false negative rate (0.044) in Table 6. As for the similarity of the context of target software, Denaro02 and Briand02 are more similar to our approach. Comparing our approach with these two works, accuracy of our approach (0.835) is slightly smaller than these two works. However, recall of our approach (0.839) is much higher than them.
Since this is a survey based comparison, we cannot validate advantage of our approach in a rigorous manner. However, we can show a certain degree of possibility that FP filtering can be applied to actual software development.
### 7. THREATS TO VALIDITY
The threats to validity are categorized into four as recommended in [26]: external, internal, conclusion, and construction validity. In this study, external and construction validity can be found.
One of the external validity threats for our study is the generalizability of the result. In the previous study [18], we applied our approach to several open source software projects, Eclipse BIRT plugin and argoUML. Even though these projects are much smaller than the Eclipse project, we got almost the same results to the experiment in this paper. More application to other projects, especially industrial ones, may mitigate this threat.
One of the construction validity threats is the collection of fault-prone modules from open source software projects. As I mentioned before, the number of faults found in Eclipse cvs repository was 52% of total faults reported in Bugzilla database. The algorithm adopted in this study has a limitation that faults that is not recorded
<table>
<thead>
<tr>
<th>Study</th>
<th>Approach</th>
<th>Accuracy</th>
<th>Recall</th>
<th>false negative rate</th>
<th>% of $N_4$</th>
</tr>
</thead>
<tbody>
<tr>
<td>Denaro02</td>
<td>Logistic regression</td>
<td>0.906*</td>
<td>0.682*</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Briand02</td>
<td>PCA + Logistic regression</td>
<td>0.840†</td>
<td>0.483*†</td>
<td>0.727†</td>
<td>10.4%</td>
</tr>
<tr>
<td>Guo03</td>
<td>Dempster-Shafer Belief Networks</td>
<td>0.690‡</td>
<td>0.915*</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Khoshgoftaar04</td>
<td>Sprint-Sliq classification tree, classification and regression tree (CART)</td>
<td>0.747</td>
<td>–</td>
<td>0.208*</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Classification and regression tree</td>
<td>0.699</td>
<td>–</td>
<td>0.149§</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Regression tree in S-PLUS</td>
<td>0.734</td>
<td>–</td>
<td>0.213§</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Treeedisc classification tree</td>
<td>0.721</td>
<td>–</td>
<td>0.255§</td>
<td></td>
</tr>
<tr>
<td></td>
<td>C4.5 classification tree</td>
<td>0.746</td>
<td>–</td>
<td>0.213§</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Case-based reasoning</td>
<td>0.728</td>
<td>–</td>
<td>0.277§</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Logistic regression</td>
<td>0.723</td>
<td>–</td>
<td>0.128§</td>
<td></td>
</tr>
<tr>
<td>Bellini05</td>
<td>Discriminant analysis</td>
<td>0.736</td>
<td>0.543*†</td>
<td>0.568</td>
<td>20.0%</td>
</tr>
<tr>
<td>Seliya05</td>
<td>Semi-supervised clustering</td>
<td>0.836*</td>
<td>–</td>
<td>0.274§</td>
<td></td>
</tr>
<tr>
<td>Menzies07</td>
<td>Naive Bayes</td>
<td>–</td>
<td>0.710**‡, 0.980*‡</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Mizio07</td>
<td>FP Filtering (CRM114, OSB, $t_{FP} = 0.25$)</td>
<td><strong>0.835</strong></td>
<td><strong>0.839</strong>‡</td>
<td><strong>0.044</strong>§</td>
<td><strong>4.7</strong>%</td>
</tr>
</tbody>
</table>
* The best value shown in paper.
** Average value shown in paper.
† Calculated from data shown in paper.
‡ Approximate value read from graph in paper.
in cvs log cannot be collected. In order to make accurate collection of FP modules from source code repository, further research is required.
8. CONCLUSION
This paper showed the training on errors procedure to classify fault-prone software modules using spam filtering technique. In our fault-prone filtering, source code modules were considered as text files and they are applied to the spam filter directly. In order to show the practical usefulness of fault-prone filtering, we conducted an training on errors experiment using source code repositories of Java based open source developments. The result of experiment showed that our approach can classify about 85% of software modules correctly. Furthermore, the result of experience showed that we can improve the prediction accuracy by modifying the threshold of the probability.
One of the most important future works is improvement of prediction accuracy. The current spam filter based approach considers only text information of the source code modules. Although it contributes the speed of the classification and training, some kind of improvements that considers characteristics of source code can be implemented without increasing the execution time so much.
9. ACKNOWLEDGMENTS
Authors would like to thank Mr. Shiro Ikami and Mr. Shuya Nakaichi who made remarkable contribution to the earlier version of this research. Authors also would like to thank Dr. Juichi Taka-hashi in SONY corporation who gave us many useful advice.
Authors would like to thank anonymous reviewers who gave us many appropriate corrections and suggestions to the paper. Authors also would like to express great thanks to Professor Claes Wohlin as a shepherd of our revision.
Moreover, authors would like to express their thanks to the developers of CRM114 classifier. Without the CRM114, this work cannot be established. Finally, authors also thank to the developers of eclipse who make the repository of eclipse available for research.
10. REFERENCES
|
{"Source-Url": "http://se.is.kit.ac.jp/pman/pman3.cgi?DOWNLOAD=84", "len_cl100k_base": 11478, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 41098, "total-output-tokens": 13767, "length": "2e13", "weborganizer": {"__label__adult": 0.00029015541076660156, "__label__art_design": 0.0002448558807373047, "__label__crime_law": 0.0003669261932373047, "__label__education_jobs": 0.0006799697875976562, "__label__entertainment": 4.57763671875e-05, "__label__fashion_beauty": 0.000125885009765625, "__label__finance_business": 0.00015652179718017578, "__label__food_dining": 0.00021839141845703125, "__label__games": 0.0005283355712890625, "__label__hardware": 0.0006728172302246094, "__label__health": 0.00031948089599609375, "__label__history": 0.00013399124145507812, "__label__home_hobbies": 7.206201553344727e-05, "__label__industrial": 0.0002386569976806641, "__label__literature": 0.0001780986785888672, "__label__politics": 0.0001608133316040039, "__label__religion": 0.0002923011779785156, "__label__science_tech": 0.00873565673828125, "__label__social_life": 7.194280624389648e-05, "__label__software": 0.00685882568359375, "__label__software_dev": 0.97900390625, "__label__sports_fitness": 0.0002058744430541992, "__label__transportation": 0.00026226043701171875, "__label__travel": 0.00012552738189697266}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51558, 0.049]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51558, 0.70226]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51558, 0.8874]], "google_gemma-3-12b-it_contains_pii": [[0, 4982, false], [4982, 11914, null], [11914, 17050, null], [17050, 20641, null], [20641, 25221, null], [25221, 29604, null], [29604, 36010, null], [36010, 38327, null], [38327, 45233, null], [45233, 51558, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4982, true], [4982, 11914, null], [11914, 17050, null], [17050, 20641, null], [20641, 25221, null], [25221, 29604, null], [29604, 36010, null], [36010, 38327, null], [38327, 45233, null], [45233, 51558, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51558, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51558, null]], "pdf_page_numbers": [[0, 4982, 1], [4982, 11914, 2], [11914, 17050, 3], [17050, 20641, 4], [20641, 25221, 5], [25221, 29604, 6], [29604, 36010, 7], [36010, 38327, 8], [38327, 45233, 9], [45233, 51558, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51558, 0.13636]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
72421f1383d2019b3766ed1e83d0b4f854f4a2ab
|
Virtual Appliance Size Optimization with Active Fault Injection
Gabor Kecskemeti, Gabor Terstyanszky and Peter Kacsuk
Abstract—Virtual appliances store the required information to instantiate a functional virtual machine on Infrastructure as a Service (IaaS) cloud systems. Large appliance size obstructs IaaS systems to deliver dynamic and scalable infrastructures according to their promise. To overcome this issue, this article offers a novel technique for virtual appliance developers to publish appliances for the dynamic environments of IaaS systems. Our solution achieves faster virtual machine instantiation by reducing the appliance size while maintaining its key functionality. The new virtual appliance optimization algorithm identifies the removable parts of the appliance. Then, it applies active fault injection to remove the identified parts. Afterwards, our solution assesses the functionality of the reduced virtual appliance by applying the – appliance developer provided – validation algorithms. We also introduce a technique to parallelize the fault injection and validation phases of the algorithm. Finally, the prototype implementation of the algorithm is discussed to demonstrate the efficiency of the proposed algorithm through the optimization of two well-known virtual appliances. Results show that the algorithm significantly decreased virtual machine instantiation time and increased dynamism in IaaS systems.
Index Terms—Virtual appliance, Optimization, Cloud Computing, IaaS
1 INTRODUCTION
Infrastructure as a service (IaaS – [1], [2]) cloud systems promise to provide on demand and scalable infrastructures. The scalability of this new kind of infrastructure is provided through virtualization [3]. Even the most basic IaaS systems offer service interfaces to create and manage virtual machines (VMs) hosted by various virtual machine monitors [4], [5], [6]. From the earliest commercial IaaS systems – like Amazon EC2 – these systems are marketed as an approach to dynamically extend service infrastructures. Users prepare virtual appliances (VAs – [7]) hosting the dynamic components of their service-based applications. These appliances store the necessary information to instantiate a functional virtual machine (e.g. an operating system, the dependencies and the code of the dynamic component itself).
One of the most frequently referred scenarios of commercial IaaS providers offers a solution to handle the peak demand periods of service-based applications [8], [9], [10]. The highly dynamic [11], [12] nature of these applications require IaaS users to instantiate their virtual appliances on demand within a minimal amount of time. However, the virtual appliance instantiation time is mainly dependent on the size of the appliance. Therefore, appliance developers should create virtual appliances with the smallest size while they still maintain the key functionality of the appliance. The manual creation of such appliances requires expertise and time not available for most IaaS users. Consequently, highly dynamic service environments require techniques for creating virtual appliances.
Already existing automated appliance creation techniques (e.g. [13]) utilize the dependencies between the various software components of the future virtual appliance. These techniques require the appliance developer to define the dependencies and requirements of its dynamic components before creating the appliance itself. Then, they construct the virtual appliance according to the previous definitions. As a result, these techniques rely on the virtual appliance developer’s skills of preparing optimally sized appliances for dynamic service environments. This research reduces the demands on the appliance developers by requiring them to only define the intended usage scenarios (referred as the key functionality) of dynamic components.
Active fault injection is a well-discussed topic for determining the fault tolerance of various software systems [14], [15], [16], [17]. This article introduces the concept of active fault injection to a new domain: virtual appliance size minimization. We propose to inject faults to virtual appliances by removing their parts while they are executed in virtual machines. The article offers a fault injection technique that is independent from the granularity of the virtual appliance parts (e.g. they can be software packages or files). This technique first identifies the smallest individually handled parts of the virtual appliance. Afterwards, the technique identifies the parts more favorable for removal. After their removal, the reduced virtual appliance is validated against the intended usage scenarios specified by the appliance developer.
Finally, the article discusses an approach to parallelize the removal and validation tasks of our technique.
This new technique is based on the assumption that the appliance developer intends to create single purpose virtual appliances. These appliances have a well defined and single functionality (e.g. provide a specific website). We assume that the appliance developer is capable to describe the purpose of the appliance by providing validation algorithms for the key functionality. In contrast, generic appliances are designed to be customizable by third parties (e.g. LAMP – Linux, Apache, MySQL, php – appliances that allow their arbitrary customization after deployment). As the developers cannot clearly specify the later use of their appliances they cannot define the validation algorithms. Consequently, the approach is not applicable to generic virtual appliances but only to a subclass of virtual appliances paired with the definition of their validator algorithms. The research results are utilized as part of an Automated Virtual appliance creation Service that was introduced and discussed in [18], [19].
This article discusses our implementation that is instantly applicable to IaaS systems similar to Amazon Elastic Compute Cloud (EC2 – [20]). Then, we evaluate the proposed technique through experiments executed on a Eucalyptus [21] based testbed. The experiments first present the significant virtual appliance size reduction (e.g. more than 90%) achievable with our technique. Second, the article reveals how the optimization time is reduced by refining the proposed technique reaching less than 2-hour optimization time with a 32 CPU based cluster on our test VAs (Apache and SSH).
This paper is organized as follows. Section 2 provides an overview about the related works. Then, Section 3 highlights the architecture that is proposed to include the optimization approach described in the article. Later, in Section 4, we discuss the basics of the optimization algorithm. Then, Section 5 reveals the details and the decisions we made for the first implementation. Finally, in Section 6 we measure the effectiveness of the implemented optimization algorithm.
2 Related Works
Virtual appliance distribution can be optimized by either optimizing the delivery path of the appliance (e.g. by caching or replicating some of the appliance contents for faster, multi-sourced delivery [19], [22], [23]) or by reducing its size. Size reduction results immediate effects on appliance instantiation time even without delivery path changes. This article is focused on the second approach, therefore this related works section is only focusing on the appliance size optimization approaches.
The discussed approaches can be classified based on their input requirements. The pre-optimizing approach requires the appliance developer to provide the application and its known dependencies that should be offered by the appliance. In contrast, the post-optimizing approach uses already existing but non-optimized appliances.
With pre-optimizing algorithms the dependencies of the user applications are prepared as reusable virtual appliance components. The appliance developers select from these components so that they can form the base of the user application. These algorithms then form the virtual appliance with the selected reusable components and the application itself. RBuilder [13] applies this algorithm with an extension that supports creating custom virtual appliances by building from the source code.
The extreme case of pre-optimizing algorithms is the minimalist pre-optimizing approach that offers optimized virtual appliances with known software environments. To support this approach several OS and reusable application vendors offer the minimalist version of their product packaged together with their just-enough operating system (JeOS – [24]) in virtual appliances [25], [26], [27], [28]. For example, there are several virtual appliances available prepared to host a simple LAMP project. However, this approach requires the appliance developer to manually install its application to a suitable optimized virtual appliance. The advantage of these algorithms is the fast creation of the appliances but at the price that the developer has to trust the optimization attempt of the used virtual appliance’s vendor. If the appliance is not well optimized, or the vendor offers a generic appliance for all uses then the descendant virtual appliances cannot be optimal without further efforts.
Other pre-optimizing algorithms determine dependencies within the virtual appliance by using its source code. Software clone [29] and dependency [30] detection techniques identify all of the required underlying software components by analyzing the sources. Once the dependencies are detected these algorithms leave only those components that are required for serving the key functionality of the virtual appliance. Optimizing a virtual appliance with these techniques require the source code of all the software encapsulated within the appliance. Thus they also need to analyze the underlying systems (e.g. the operating system) of the application. Unfortunately this last requirement renders these techniques unfeasible in most cases.
The most widely used post-optimizing algorithms are optimizing the free space in the disk images of the virtual appliance. If virtual appliances are created from previously used software systems then their disk images contain their available free space fragmented throughout the entire image. Before publication, virtual appliances are usually compressed for easier transfer. However, the fragmented free space is harder to compress. Therefore, these post optimizing algorithms analyze the available free space and first they fill them with easily compressible data. Next, they offer their users the option to defragment the disk images. As a result, these disk images can be shrunk so they are not only more compressible but they do not even store the free space in the disk image if they are not required. The advantage of this algorithm, that it can operate on any virtual appliance so long it can understand and use its file system. This
technique is utilized by [31].
Our investigations show that the field of post-optimizing algorithms is less developed, even though they could bring remedy for the vast amounts of already existing virtual appliances that are currently unusable in dynamic service environments. Consequently, the size optimization technique discussed in this article can also be classified as a post-optimizing algorithm.
3 THE AUTOMATIC SERVICE DEPLOYMENT ARCHITECTURE
In our previous work [18] we introduced the Automatic Service Deployment (ASD) architecture as seen in Fig. 1. The architecture provides a framework to our recent and future works. This section gives a short overview of the architecture and contextualizes current research results.
Fig. 1 presents the service deployment architecture that supports various tasks of the virtual appliance-based deployment and also depicts several issues that the current solutions do not aim at. First, the architecture offers a solution for initial virtual appliance creation. Virtual appliances are acquired and managed by the Automated Virtual Appliance Creation Service [19]. In the article only the following virtual appliance preparation tasks were solved: (i) extracting a virtual appliance from a running system, (ii) transformation of the appliance between various virtual machine image formats, and (iii) uploading the virtual appliance to a repository. Through the functionality of the optimization facility, this article extends these tasks with the size optimization of the previously extracted virtual appliances.
Second, the architecture also supports developers to create appliances more suitable for highly dynamic environments via minimal manageable virtual appliances [32] that they can use as the base of their appliance. This appliance provides management interfaces offering package installation, configuration and removal operations.
Third, the architecture defines active repositories with the following automatic entry management functionality: (i) appliance decomposition, (ii) package merging, (iii) destruction and (iv) partial replication. Therefore, these repositories have the ability to identify common virtual appliance parts and optimize their storage.
Finally, the architecture also offers decision-making support for schedulers and other high level entities that make deployment related decisions in a dynamic service ecosystem. Service deployment can be initiated by higher-level components (such as service schedulers or service composition engines), the Scheduler Assistant Service (SAS) aids their deployment decisions by offering interfaces to identify deployable services and rank sites that can host them. The research issues and design considerations of the SAS are discussed in [33].
4 VIRTUAL APPLIANCE OPTIMIZATION PRINCIPLES
As the first step towards the optimization algorithm, this section identifies the time reduction options for virtual appliance instantiation. We have defined the instantiation as a composite task of three major steps: (i) download the appliance, (ii) initialize the VM and start up its operating system and finally, (iii) activate the service in the VM. Fig. 10 presents the average execution time of these three tasks for two typical virtual appliances described in Section 6.3.
It can be observed in Fig. 10 that instantiation time mainly depends on the download time of the virtual appliance. This time can be optimized in two ways: (i) storing the virtual appliance in a repository with the smallest latency and largest transfer rate towards its executor host and (ii) minimizing the size of the virtual appliance while still maintaining its key functionality. The first option is only viable with IaaS systems that support multiple repositories (this is not the case with Amazon EC2 [20] or Eucalyptus [21]), therefore to support wider range of IaaS systems we only focus on the size minimization in this article. Throughout this article, we did not make any assumptions on the IaaS behavior; therefore, this approach is applicable to any IaaS system.
4.1 The Virtual Appliance Optimization Facility
Before detailing the features of our size optimization technique, we define the constraints of the optimization facility and system. The optimization facility incorporates the algorithms described in this article. It resides on a single host of the optimization system ($\varphi$). The optimization system incorporates multiple hosts ($h_z \in \varphi$) within a single administrative domain. These hosts also implement an IaaS system offering the required virtual machine management functionality for the facility.
The main task of the optimization facility is to solve the optimize : $P \times C \rightarrow P'$ function. Where the set $P$ refers to all virtual appliances in the optimization system, and $C$ defines the possible completion conditions that can limit the optimization according to the appliance developer. At the end of the optimization operation, the $p'_i := \text{optimize}(p_i, C)$ function provides a smaller sized
version \((p'_n)\) of the original virtual appliance \((p_o)\) and publish it among the other virtual appliances: \(P' := P \cup \{p'_n\}\). If the optimization function receives an empty completion condition set \(c = \emptyset\) then the optimization is executed until \(p'_n\) becomes optimally sized – see Eq. (4).
Active fault injection uses fault injection techniques that generate hardware and software level faults to test the fault tolerant behavior of software. However, for virtual appliance optimization, we do not test for fault tolerant behavior. Instead, fault injection identifies those parts of the \(p_o\) that are not needed for its key functionality.
First, we define the faults that can be injected in order to achieve size reduction. Having a virtualized environment enables the simulation of both software and hardware level faults. Software level faults could arise on the file system – e.g. simulating the corruption of the file system by removing a file or some of its parts. Hardware faults could occur in the memory or the disk subsystem. Simulating hardware faults need changes in virtual machine monitors. This requirement seriously reduces the adoptability of an optimization technique; thus, this article only considers software fault injection.
### 4.2 Appliance Contents Removal
This section describes the basic algorithm of the optimization procedure that is split into four tasks as seen in Fig. 2. The first task is the selection of the virtual appliance’s removable parts. The selection task is the most complex and critical task of the optimization approach. This task analyzes the package \((p_o \in P)\) of the virtual appliance and proposes how to partition the appliance.
The selection task also assigns a weight value to appliance parts. The highest weighted parts are temporarily erased from the appliance by the removal task. The third task is the validation of the modified appliance using validation algorithms provided by the appliance developer. This task decides whether the erased items should be permanently removed from the VA. Later, we refer to the triplet of selection, removal and validation as the optimization iteration (see the bold arrows in Fig. 2).
The last task of the algorithm decides whether the system should initiate further optimization iterations. The decision is based on the appliance developer provided completion conditions. If the conditions are met the algorithm publishes the optimized appliance. Otherwise, the algorithm proceeds with the next iteration. These four tasks are further outlined in the next sub-sections.

#### 4.2.1 Selection
As it was discussed previously, the main task of the selection is to identify parts to be removed. From the selection point of view the granularity of the parts in the VA is not important. However, the selection algorithm should use the same appliance part granularity that the removal task uses. Virtual appliance parts can range from single bytes, sectors, file contents, files to even directories or software packages.
The identification of the different parts and their metadata is called *itemization*. Items \((i \in I)\) are the internal representation of the virtual appliance parts with metadata. Different itemization techniques use different kinds of virtual appliance parts as items. The set of \(I\) represents all possible items created with a particular itemization technique. Items are the smallest entities handled by the selection and removal algorithms. The entire item set of an appliance is represented with the function \(i_t: P \rightarrow I\).
If multiple itemization techniques are available, then the optimization is executed in several phases. In the first phase, the facility removes and validates the item set of the current itemization technique. If there are no more items to validate and the completion conditions allow, the facility initiates a new phase using an itemization technique with smaller granularity.
For example, if the first applied itemization technique uses software package managers (e.g. the debian package manager \([34] - \text{dpkg}\)) then the facility first removes all software packages not related to the key functionality of the appliance. The facility switches to smaller granularity when it cannot purge more packages from the VA with the package manager. Consequently, during later executed phases, the facility could even erase the software package manager itself if it is not required for the key functionality of the appliance.
The second subtask of selection categorizes the various items according to the following list: (i) the *core items* \(- i_c\), (ii) the *volatile items* \(- i_v\) and finally, (iii) the *fuzzy items* \(- i_f\). Those items that the selection algorithm does not have any prior knowledge about are called volatile and are primarily exposed to active fault injection by the optimization facility. In contrast to volatile items, the core and fuzzy items are identified by the past knowledge of the selection task. The core items cannot be removed from an appliance under any circumstances (e.g. the *init* application in SystemV compatible UNIX systems); these items are predefined in the knowledge base of the selection task. Initially no fuzzy items are defined. They are identified as those items that – according to the knowledge base – were repeatedly validated unsuccessfully in prior optimization operations. If the developer specified completion conditions could not be reached, then the facility starts removing and validating fuzzy items before offering the optimized appliance.
Weight functions \((w : I \times P \rightarrow V)\) assign weight values \(V = \{v \in \mathbb{R}: (0 \leq v < 1)\}\) for each item of the virtual appliance under optimization \((i \in i_t(p_o))\).
Items with higher weight values are more likely to be removed. As a result, for any combination of core, fuzzy and volatile items the following statement is always true:
\[ 0 = w(i_c, p) < w(i_f, p) < w(i_v, p) \] \hspace{1cm} (1)
Weight functions utilize metadata available about the items. As a result, methods for collecting new metadata have to be specified along with the new weighting algorithms. Therefore, details of the weight functions and the collected metadata are discussed in Section 5.1.
The optimization facility decides on the use of the various weight functions based on the time and cost constraints specified in the completion conditions. The facility can even decide whether to use a single or multiple weight functions throughout the optimization process. Alternatively, different weight functions can be used during the different stages of the optimization process. This strategy ensures that the more expensive and more precise weight calculations used only if they would result faster size reduction.
4.2.2 Removal
The removal task sorts the items according to their weights and removes the highest weighted item \( (i_{hw} \in I) \) from the original virtual appliance \( (p_i) \).
\[
i_{hw} := i \in it(p_i) : \left( w(i, p_i) = \max_{j \in it(p_i)} w(j, p_i) \right) \hspace{1cm} (2)
\]
\[
it(p_{red}) := it(p_i) \setminus \{i_{hw}\} \hspace{1cm} (3)
\]
Where \( p_{red} \) represents the newly created reduced virtual appliance that no longer includes \( i_{hw} \). For the removal operation the optimization facility has to understand the structure of the appliance and the item type of the used itemization technique to be able to remove the highest weighted item. For instance, the facility has to handle the file system of the VA in case of file based itemization.
We have identified two basic techniques for removal: (i) pre-execution and (ii) during execution.
First, pre-execution removal operates on the items of the virtual appliance while it is not running. This technique first attaches the disk images of the original virtual appliance to the optimization facility’s host, and removes the item with the highest weight. Then to allow the validation of the new appliance, it is initiated in a virtual machine. However, IaaS systems similar to Amazon EC2 only initiate virtual machines with virtual appliances stored in their repositories. This requirement forces the optimization facility to upload the reduced virtual appliance to the repository of the IaaS system before validation. Thus, the facility applies this removal technique if the optimization system uses an IaaS system capable of instantiating virtual machines with appliances from external sources (e.g., from the optimization facility).
Second, if the virtual appliance under optimization offers management interfaces (e.g., [35], [36]) then it enables a new removal technique, called removal during execution. This approach requires the original virtual appliance instantiated in a virtual machine before the removal operation takes place. Then, the highest weighted items are removed using the management capabilities of the virtual machine. Consequently, the reduced virtual appliance \( (p_{red}) \) is created by altering the virtual machine of the original appliance. However, the functionality of the appliance could remain intact even after the management interfaces remove \( i_{hw} \) from the virtual machine because its memory still holds the removed item. Thus, the VM is restarted to erase its memory before validation. The restart cleans up the claimed address space of the VM, thus avoids security issues unclaimed memory could cause – beyond this scope we did not consider further security issues. The validation automatically fails if the restart fails; otherwise it is executed on the running virtual machine. This approach is the only practical solution in EC2 like IaaS systems, because it does not require the repeated upload of the reduced virtual appliances. This article applies the management interfaces for active fault injection only, the detailed definition of these interfaces and their further usage options are discussed in [32].
Based on the availability of the management interfaces the optimization facility automatically determines the applied removal technique. Before the optimization starts, the facility tests the management interfaces of the original virtual appliance. If the appliance offers them, then the optimization will apply removal during execution, otherwise the system automatically falls back to pre-execution removal.
4.2.3 Validation
The optimization facility requires validation algorithms to ensure that reduced appliances still offer the key functionality of their original appliances. As appliance developers precisely know the key functionality, we assume that they can accompany original virtual appliances with their validation algorithms. For example, to define validation algorithms, developers could reuse unit and integration tests (available because of the software development process [37]). However, these algorithms must evaluate virtual appliances both semantically and functionally. E.g., they could ensure response time requirements or they could also confirm the absence of known security issues. Obviously, validator algorithms cannot be discussed in the article, therefore we assume that these algorithms are available for the appliance developers before they start the optimization process.
Validator algorithms are applied by the valid : \( P \times \phi \rightarrow \{true, false\} \) function. This function calls the appliance’s \( (p_i \in P) \) validator algorithm that evaluates the virtual machine \( (vm \in \phi) \) instantiated with the reduced appliance \( (vm := initVM(p_{red})) \). Where \( initVM : P \rightarrow \phi \) depicts the instantiation of a virtual appliance in a virtual machine. Non-successful validation \( (valid(p_i, vm) = false) \) leads to the restoration of the original virtual appliance and to the omission of the previously removed item \( (i_{hw}) \) from future optimization iterations.
4.2.4 Completion
Before every new optimization iteration, the facility decides if it has reached the completion condition of the appliance developer. The completion condition limits the time and resource usage of the optimization facility and allows the creation of sub-optimally sized appliances.
The decision is made by evaluating the completion condition specified as an arbitrary conditional expression based on five metrics: (i) the number of optimization iterations executed, (ii) the current size of the virtual appliance, (iii) the size reduction achieved by the optimization iterations, (iv) the wall time for the entire optimization process and (v) the size of the remaining (or not validated) items of the virtual appliance.
If the completion conditions have not been met yet, then the optimization facility evaluates the feasibility of creating an intermediate virtual appliance: \( p_{\text{opt}} := p_{\text{pred}} \). Therefore, the evaluation takes into consideration the cost of the intermediate virtual appliance creation and compares it to the possible gains on future optimization iterations (assuming that the optimization facility will initiate a virtual machine for every non-validated item).
As a result, the system reduces the time required for future virtual machine initiations (as the size of \( p_{\text{opt}} \) is decreased during the optimization process). In other words, the facility reduces the optimization time by utilizing the effects of optimization through intermediate appliances before reaching the final optimized VA.
The optimization process concludes with the publication of the final virtual appliance when the completion conditions are met or there are no more items (\( \text{optsize} : P \rightarrow \{true, false\} \)) to remove from the appliance:
\[
\text{optsize}(p) := \begin{cases}
\text{true} & \exists i \in \text{it}(p) : \left( \text{it}(p_{\text{opt}}) = \text{it}(p) \backslash \{i\} \right) \\
\land (\text{valid}(p, \text{initVM}(p_{\text{opt}})) = \text{true}) \\
\text{false} & \text{otherwise}
\end{cases}
\]
During this step the optimization facility first fetches the original virtual appliance from the repository. Then it attaches it to the facility’s host machine where the successfully validated items are removed from the appliance. Finally, it uploads the locally modified appliance to the repository as an optimized version of the original one.
5 Implementation of the Virtual Appliance Optimization
Fig. 3 depicts the entire optimization process, however it gives details of the selection related operations only, the rest of the operations are discussed in later sections.
5.1 Item Selection
5.1.1 Virtual Appliance Itemization
When the optimization facility receives a request for minimizing a virtual appliance (\( p_{\text{opt}} \)), it first fetches the appliance from the repository. The disk image of the appliance is analyzed by the file-based itemization technique that reads its file system and identifies items (files in the current implementation) of the appliance. During itemization our technique collects and passes the following metadata about each file: (i) the item size (\( \text{size}(i) \)), (ii) dependencies representing item relations (e.g. inclusion, parent/child relationships) and (iii) creation and modification timestamps.
The optimization facility contains an item pool used as a metadata cache to avoid frequent queries on the appliance’s file system. This pool stores metadata for all items that are ready for the further tasks of the optimization iteration. The item queue is used as an intermediary between the file system and the item pool. The queue is the source to fill the unused item capacity of the pool. The length of this queue is automatically determined by the amount of removable items during a single optimization iteration. The maximum value is the same...
as the number of virtual machines used for validation as discussed in Section 5.3. If the queue is full, then the itemization procedure is blocked until the optimization facility removes items from the pool. Therefore the item queue remains full while the itemization processes all parts of the appliance.
5.1.2 Grouping
The file-based itemization algorithm produces so many items from a virtual appliance (see Table 3) that creating a virtual machine for each item’s removal and validation is inefficient. Therefore, the algorithm groups these items together to decrease the number of removal and validation operations. Grouping has two tasks: (i) form groups from items that are more likely to be removed together and (ii) aggregate the metadata attached to the individual items and present them as group metadata.
We propose three different grouping techniques: (i) directory structure based – items in the same directory will form a common group –, (ii) software package based – items in the same package (e.g. dpkg) form a group –, and (iii) creation time proximity based – items created within specific time periods belong to the same group.
Item grouping operates on the items in the pool. The algorithm waits until the pool is either full or the itemization processes all items. If the removal of a group fails the validation then it is split into smaller groups (or items). The previous groupings of an item are stored among its metadata enabling the evaluation of the prior group participation coefficient – see Eq. (7). If the validation fails on an item then the facility saves its metadata as a negative example in the knowledge base. Later, this example helps the calculation of the removal success rate coefficient – see Eq. (8) – during the optimization of other appliances.
Grouping efficiency is measured through the grouping failure rate that is the ratio between the number of successfully and unsuccessfully validated groups formed by a specific grouping solution (see Fig. 4). The grouping failure rate can reveal if the applied grouping technique cannot be used for a given appliance. We found that failure rates over 30% indicate the need for switching between grouping techniques. The current implementation uses the directory-based grouping.
5.1.3 Item Weight Calculation
After grouping, we discuss the item weighting step in the selection phase. This step was already introduced in Section 4.2.1. Here only the implemented weight calculation algorithm is described as composite of a base weight function and several coefficients:
\[ w_A(i, p) := \gamma(i)\kappa(i)w_s(i, p) \]
Where \( w_A : I \times P \rightarrow V \) is the composite weight function of volatile items. This function is based on the size-based weight function \( w_s : I \times P \rightarrow V \). The value of the \( w_s(i, p) \) function is modified by the prior group participation \( \gamma : I \rightarrow V \) coefficient that prefers items with successfully validated group siblings. The \( \kappa : I \rightarrow V \) coefficient favors items with high removal success rates of prior optimizations.
First, we define the base weight function that assigns weights considering only the item size \( \text{size}(i) \). Consequently, the optimization facility will choose removable items that have higher impact on the appliance size. As a result, the facility significantly reduces the appliance even with highly constrained completion conditions:
\[ w_s(i, p) := \frac{\text{size}(i)}{\max_{j \in \text{it}(p)}(\text{size}(j))} \]
Therefore, validation progresses from the largest items towards the smaller ones. As an advantage, this weight value can be calculated without the knowledge base.
Coefficient \( \gamma \) uses information about prior group participation. Thus, previously improperly grouped items modify each other’s weight. Item metadata stores the previous groupings of an item along with all previous siblings. If an item has participated in a wrong group and some of its group siblings have already passed validation, then their success rate alters the base weight:
\[
\gamma(i) := \begin{cases}
M(i) > 0 & \min(1, 1 + \frac{M_{\text{success}}(i) - M_{\text{faulty}}(i)}{M(i)}) \\
M(i) = 0 & 1
\end{cases}
\]
Where \( M : I \rightarrow \mathbb{N} \) defines the number of already validated siblings in a previously faulty grouping where the current item was a member. \( M_{\text{faulty}} : I \rightarrow \mathbb{N} \) specifies the number of those siblings that already failed the validation phase. Consequently, \( M_{\text{success}} : I \rightarrow \mathbb{N} \) is the number of successfully validated siblings.
Coefficient \( \kappa \) alters the base weight value with previous removal success rate of the individual items. As a prerequisite, validation results of items from previously optimized virtual appliances are stored in and restored from the knowledge base. With the help of the knowledge base this coefficient encourages the removal of
those items that were previously removed successfully.
\[ \kappa(i) := \frac{N_T(i) - N_F(i)}{N_T(i)} \]
(8)
Where \( N_F : I \rightarrow \mathbb{N} \) is the number of unsuccessful removals of a given item, and \( N_T : I \rightarrow \mathbb{N} \) is the number of trials made on the item.
### 5.2 Parallel Validation
Fig. 5 exemplifies the items and groups available for validation throughout an optimization process. During the individual iterations the removal action has had more than 400 candidate items (or groups). Our removal and validation technique (see Sections 4.2.2 and 4.2.3) requires an individual virtual machine for the evaluation of each item (or group). However, according to our measurements seen in Fig. 10, virtual machine instantiation is the most time consuming operation of the optimization facility. Therefore, multiple removal and validation tasks has to be executed in parallel. To allow parallelism, the optimization system must be deployed on a cluster capable to execute several virtual machines simultaneously.
Fig. 6 reveals that parallelism in the facility starts after assigning the weight values. First, the system selects the highest weighted groups or items, and for each one of them it initiates a removal and validation task in a dedicated virtual machine (see the “multiple selection” action in Fig. 6). As a result, we receive the success reports on several validation tasks.
These validation success reports are independent from each other. However, the key functionality of the appliance could depend on some interchangeable items (e.g. at least one of the items should be present for the key functionality). To avoid interchangeability problems, the optimization facility creates a group with the union of the successfully removed items. This group is removed from the original appliance and validated (final validation) to ensure that removed items does not cause interchangeability problems. On validation success, the group members are removed from the item pool and from the appliance. Afterwards, their removal success is added to the positive examples of the knowledge base.
If the final validation fails, the facility selects the highest weighted successful item or group for permanent removal. Other successfully validated items remain in the item pool with a successful validation marker. This enables their early revalidation with the highest weighted element already removed from the appliance.
However, our strategy for selecting permanently removed items may lead to a suboptimal solution. For the optimal selection, the optimization facility should evaluate all possible combinations of the successfully validated removals and mark the combination with the highest cumulative size. The cost of evaluating all possible combinations renders the optimal selection procedure beyond reason and therefore our system never applies it.
### 5.3 Virtual Machine Management Strategy
Parallel validation requires multiple virtual machines ready to be validated. Therefore, the virtual machine management strategy aims at pre-initializing virtual machines before their actual use by the validation tasks. However, initializing a virtual machine requires substantial amounts of bandwidth and time (see Table 3 and Fig. 10 for details). Therefore, the management strategy defines a virtual machine lifecycle (see Fig. 7) that allows the reuse of previously successfully validated virtual machines for future optimization iterations.
To reduce the delays between removal and validation the algorithm prepares a virtual machine pool that lists those virtual machines that are available for validation. Our strategy automatically determines the size of the pool as the number of available virtualized CPUs in the optimization system. If the optimization system shares the underlying IaaS system with other services then the system administrator of the facility can set up resource usage limitations relative to the entire system.
The first task of the management strategy (designated with the “Prepare VM” state) uses the IaaS system to allocate as many VMs as possible for the optimization. Each acquired virtual machine is instantiated with the original appliance (\(\text{initVM}(p_o)\)) during its “Init VM” state. Then the “conformance check” state confirms the accessibility of the created virtual machine to avoid false validation failure reports on improperly initialized virtual machines. If the conformance check fails, then the system repeats the allocation task. Otherwise, the appliances are “configured” to run inside their virtual machines. The configuration step handles internal configuration provided by the appliance developer, then it also manages the external network configuration of the virtual machine (e.g. setting up the firewall). After the VMs are initialized they are ready to be used for the removal and validation tasks (detailed in Section 5.2).
When the virtual machine reaches the “free” state then it becomes usable for the removal and validation processes. Afterwards, the next state “binds the validator” task with a virtual machine. During this phase the virtual machine handler first removes all the previously successfully validated (“remove all marked”) items from the virtual machine. Then it generates the list of removal requests (e.g. through the management interfaces of the appliance) for the highest weighted removable items (\(i_{hw}\)) or groups. Next, the VM enters the “validation” state when the handler evaluates the validation algorithms on the virtual machine running the reduced virtual appliance \((p_{red})\). If both the evaluation and the removal requests were successful then the virtual machine becomes “free” – reusable – again.
Faulty validation renders the affected virtual machine “defunct”. This leads towards the second task of the management strategy: the recovery of the defunct VM. This could imply the addition of the previously removed item. However, the addition would require the revalidation of the restored virtual machine. Therefore, instead of trying to recover the defunct VM, the manager terminates it, then initiates a new virtual machine. Next, the manager synchronizes the successfully removed items in the new VM. After recovery, the parallel validation branches compete with each other for the new VMs.
The parallel execution of the validation leads to VMs running slightly more optimized virtual appliances. Therefore, on successful validation, the final task of the manager prepares the content synchronization of all the successfully validated VMs to allow their reuse for later validations. The content synchronization is accomplished by generating the list of permanently removable items for the “remove all marked” operation.
### 6 Optimization Results
This section presents the experimental results with the optimization facility: (i) we introduce the methodology and the aim of the experiments; (ii) the testbed infrastructure for the experiments is detailed; (iii) the test virtual appliances are discussed; finally, (iv) we evaluate and analyze the experimental results.
#### 6.1 Methodology
This article represents measurements with the function \(\mathcal{M}: \mathcal{F} \rightarrow \mathbb{R}\). This function evaluates its arguments (\(\mathcal{F}\) represents an arbitrary function and a specific parameter set) repeatedly and measures the execution time \((t_{ev})\) for each individual evaluation. Measurements are executed until the sample standard deviation \((s_N)\) of the \(t_{ev}\) values becomes stable, thus the value of two subsequent standard deviation calculations are within 1%:
\[
\frac{s_N(t_{ev}) - s_{N+1}(t_{ev})}{s_N(t_{ev})} < 0.01 \text{ where } N \geq 2
\]
Function \(\mathcal{M}\) calculates the median of the measured evaluation times of \(\mathcal{F}\) after the deviation is stabilized.
#### 6.1.1 Speedup
We have defined the efficiency of the optimization facility with the speedup function – \(S: (P) \rightarrow \mathbb{R}\):
\[
S(p_o) = \frac{\mathcal{M}(\text{initVM}(p_o))}{\mathcal{M}(\text{initVM}(p'_o))}
\]
Speedup \((S(p_o))\) is the ratio of the measured instantiation times of a service package before \((p_o)\) and after \((p'_o)\)


the size optimization was applied. We consider the optimization algorithm successful if the optimized virtual appliance can be instantiated faster than the original:
\[ S(p_\sigma) > 1 \]
The baseline measurement \( (M(initVM(p_\sigma))) \) for the speedup values is presented in step 1-3 in Fig. 8. During this measurement, we used the deployment client to request the IaaS system for the instantiation of \( p_\sigma \).
Fig. 8 reveals that the baseline measurement is followed by the request to optimize the original appliance \( (p_\sigma \rightarrow \text{steps 4-5}) \). After the completion of the optimization process, the final reduced appliance \( (p'_\sigma) \) is stored in the repository (step 6). Finally, the testbed is ready to evaluate the speedup by measuring the instantiation time of \( p'_\sigma \) in steps 7-9 – \( M(initVM(p'_\sigma)) \).
### 6.1.2 Cost Efficiency
There is a tradeoff applying the technique introduced in this article. For example, before any user initiated deployment could occur, the optimization process creates virtual machines on purpose to allow the validation of the reduced appliance. To evaluate this tradeoff, we measure the time spent during the optimization process according to steps 4-6 in Fig. 8. Then, we calculate the number of virtual machine instantiations (or user initiated deployments – \( N_{dep} \)) required to compensate the time spent on the appliance size optimization task:
\[ N_{dep}(p_\sigma) := \frac{M(optimize(p_\sigma, \emptyset))}{M(initVM(p_\sigma)) - M(initVM(p'_\sigma))} \]
By default, the optimization – and therefore the measurement – is executed until \( p'_\sigma := optimize(p_\sigma, \emptyset) \) reaches its minimal size: \( optimize(p'_\sigma) = \text{true} \).
### 6.2 Testbed Infrastructure
The optimization facility is designed for implementation on top of IaaS systems (e.g. Eucalyptus [21] or Virtual Workspaces Service [38] that is part of Nimbus). In this article, we discuss an implementation based on Eucalyptus, because of its two advantages: (i) Eucalyptus supports all functionalities of the optimization facility without extensions or modifications, and (ii) Eucalyptus could be easily replaced with Amazon EC2 [20] to present the viability of the optimization facility on a commercial IaaS cloud system.
Fig. 9 shows the infrastructure used for the experiments. In this infrastructure there is a single Internet connection available only for the Eucalyptus HeadNode. This node runs as the controller of the local cluster by managing both its IaaS behavior and also its networking – e.g. DHCP, DNS and routing. We also have the internal Eucalyptus repository, Walrus, installed on this node. Finally, this node also hosts the optimization facility itself in order to have a low latency and high bandwidth connection with the IaaS system and its repository. This infrastructure satisfies the facility’s requirement to have a high bandwidth connection with the repository.
The remaining hosts are configured with the same software. They run the Xen virtual machine monitor [6] in order to enable virtual machine creation and management on the nodes. They also execute the Eucalyptus node controller that enables the remote access to the locally available virtual machine monitor. All the nodes have the same hardware configuration (4 CPUs, 4GB of RAM and 80GB of HDD) and they are connected with gigabit Ethernet towards the HeadNode.
### 6.3 The Experimental Virtual Appliances
In this subsection, we outline the virtual appliances selected to test the optimization facility. Based on the popularity of basic Internet services we have selected and defined two appliances: the SSH and the Apache web server appliance. The key functionality of the SSH appliance (see Table 1) enables a user to transfer shell scripts to the machine and allows their execution. In contrast, the key functionality of the Apache appliance (see Table 2) does not allow arbitrary code execution, however it enables users to upload static html content that
<table>
<thead>
<tr>
<th>Table 1: The definition of the SSH virtual appliance</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Key functionality</strong></td>
</tr>
<tr>
<td><strong>Construction</strong></td>
</tr>
<tr>
<td><strong>Validator algorithm</strong></td>
</tr>
</tbody>
</table>
The definition of the Apache virtual appliance
<table>
<thead>
<tr>
<th>Key functionality</th>
<th>The aim of the Apache virtual appliance is to provide an HTTP server that is capable of serving static html pages to its users. As a prerequisite, the user has to transfer the static html pages that should be offered by the server.</th>
</tr>
</thead>
</table>
| Construction | 1) Create a virtual machine image for Xen with xen-tools of debian.
2) Start up the created VM image.
3) Add the ssh, rsync and apache daemons. |
| Validator algorithm | 1) Create an HTML document that has an html header with the text of “hello world”.
2) Transfer the previously created HTML document to the apache web server’s folder on the target VM.
3) Download the pre-transferred HTML file with an HTTP request.
4) Check for the html header with the text “hello world”. If the header is not present then the target virtual machine is not valid. |
TABLE 4
Basic virtual appliance properties of the optimized test appliances
<table>
<thead>
<tr>
<th>Appliance</th>
<th>Compressed Size</th>
<th>Files</th>
<th>Opt. time</th>
<th>S(pₜ)</th>
</tr>
</thead>
<tbody>
<tr>
<td>SSH'</td>
<td>6.6MB</td>
<td>197</td>
<td>4958 secs</td>
<td>4.72x</td>
</tr>
<tr>
<td>Apache'</td>
<td>13MB</td>
<td>236</td>
<td>7468 secs</td>
<td>5.85x</td>
</tr>
<tr>
<td>rPath Apache</td>
<td>152MB</td>
<td>28923</td>
<td>N/A</td>
<td>N/A</td>
</tr>
</tbody>
</table>
Fig. 11. Increasing the effectiveness of the optimization facility
the optimization system at the end of the optimization iterations (see Section 5.1). The gathered data includes (i) the items removed, (ii) the current value of the five completion condition metrics (defined in Section 4.2.4), (iii) the number of virtual machines used, (iv) the number of validations passed, (v) the average time to initiate a virtual machine, etc. Based on these values, the system’s behavior can be evaluated without executing the optimization process in too many configurations.
As it was depicted in Table 4, the unlimited optimization process requires hours to complete. We have implemented a snapshotting technique that creates an intermediate virtual appliance after the optimization iterations as discussed in Section 4.2.4. Fig. 11a presents the optimization of the SSH virtual appliance with and without the creation of the intermediate virtual appliances. The figure reveals that intermediate VAs can dramatically decrease (e.g. from twenty minutes to less than five) the time and cost of later optimization iterations. As a result, this technique immediately results in the reduction of the total optimization time.
However, this approach still does not exploit the completion condition evaluation. We have observed, that the optimization process could not reach significant size reduction in its late stages (the size of the remaining non-validated items follows a Pareto distribution). Thus, to avoid the tail problem, we have investigated the various completion conditions (introduced in Section 4.2.4) whether they can predict the inefficiencies of the last phase of the optimization process. Unfortunately, most of the completion conditions cannot predict inefficiencies, because they are either not stable enough throughout the entire optimization process (see reduction in Fig. 11b), or their inefficiency threshold cannot be generalized for multiple appliances (e.g. optimization time). A stable completion condition has to be monotonic, in order to allow the definition of a threshold value that the completion condition variable only crosses once during the optimization process. Consequently, we define inefficiency indicators as special completion condition variables that reveal the inefficiency of the optimization process after passing a predefined threshold value.
From the list of Section 4.2.4, we have identified two completion condition variables as candidates for the role of inefficiency indicator. The first one is the size reduction percentage achieved during a single iteration.
We have chosen the conditions throughout an entire optimization process. We have chosen the remaining completion condition for further investigation because its monotonic nature.
Fig. 11c demonstrates the effects of applying different remaining completion condition variables. In this figure, we have normalized the optimization time for better comparison (for the explicit optimization time values see Table 4). In order to decrease optimization time but still maintain adequate appliance size we have identified that the remaining completion condition variable can be used as an inefficiency indicator with the threshold 10%. This threshold reduces the optimization time by 40% and still maintains close to optimal virtual appliance sizes.
Finally, using the previously introduced options for increasing effectiveness we have calculated the $N_{dep}$ values (see Eq. 12) based on the statistical information collected during the execution of the optimization processes. Fig. 11d presents the calculated values and presents the minimum amount of the future instantiations required before the optimization becomes profitable. According to the figure, the cost of the optimization procedure is high in the early stages reflecting the high grouping failure rates (see Fig. 4) and the long iteration lengths (see Fig. 11a). Later, the cost increases linearly with the executed optimization iterations because the last iterations of the process are not reducing the instantiation time considerably.
7 CONCLUSIONS
In this article, we have outlined the challenges of using virtual appliance based deployment in highly dynamic service environments and Infrastructure as a Service cloud systems. We have shown how to address these challenges by virtual appliance size optimization. The proposed approach uses active fault injection to remove parts of virtual appliances. The reduced virtual appliances are validated with appliance developer provided validator algorithms in order to maintain the key functionality of the appliance. The algorithm also includes several item selection and grouping techniques in order to decrease the number of validation steps required to achieve the optimized virtual appliance.
The proposed size optimization approach offers several advantages over the existing solutions. First, the appliance developer does not need to know the dependencies of the service that it plans to encapsulate in a virtual appliance, instead this article assumes the appliance developers can define the key functionality of their desired appliance in the form of validation algorithms. Second, this solution could also be used with existing virtual appliances. Thus, it can significantly reduce the operating costs of those appliances that are already used in highly dynamic service environments. The proposed technique not only reduces the virtual machine instantiation time, but it also provides a technique that minimizes the virtual appliance optimization time and allows the early release of the optimal appliances.
We have presented our implementation by experimenting on two well-known services encapsulated in virtual appliances. The results revealed that the size of typical virtual appliances could be significantly optimized. Based on these experiments, we have also identified that the time and cost efficiency of the optimization algorithm can be improved by (i) creating intermediate virtual appliances and by (ii) terminating the optimization process using the ratio of the remaining non-validated items in the suboptimal VA as the completion condition.
Future research considers the further optimization of the item selection and grouping techniques. We are also considering research on more efficient scheduling algorithms for the parallel validation phase in order to reduce the resource usage cause by the revalidation of previously successful validation results. We also plan to investigate the security related effects of the proposed optimization approach including the effects of virtual machine reuse for multiple removal and validation phases and whether the optimized appliance is more vulnerable than the original.
REFERENCES
Gabor Kecskeméti has received his MSc degree from the Institute of Information Technology at the University of Miskolc, in 2004. He is currently working on his Ph.D. in the Centre of Parallel Computing at the University of Westminster. He also participates in the research of the Laboratory of Parallel and Distributed Systems at MTA-SZTAKI, Hungary. He has got involved in several successful grid related projects and research resulting the P-Grade Grid Portal of MTA-SZTAKI and the Grid Execution Management for Legacy Code Applications (GEMLCA) of the University of Westminster.
Gabor Terstyanszky is Reader in Distributed Systems at the University of Westminster, London, United Kingdom. He is the co-leader of the Centre for Parallel Computing at the University of Westminster. He received his MSc degree at the Electrotechnical University, St. Petersburg, Russia. He obtained his MPhil and Ph.D. degree at the University of Miskolc, Hungary in 1990 and 1997, respectively. His research interests cover distributed and parallel computing systems including clouds, desktop and service grids. He was involved in more than 20 research projects either as Local Coordinator or Principal Investigator. He has published more than 100 papers in periodicals and conference proceedings on distributed and parallel computing systems. He was member of Program Committee of several European and world conferences. He was also Guest Editor of several special issues published in periodicals on distributed computing infrastructures.
Peter Kacsuk is the Head of the Laboratory of Parallel and Distributed Systems in MTA SZTAKI Computer and Automation Research Institute of the Hungarian Academy of Sciences. He received his MSc and university doctorate degrees from the Electrotechnical University of Budapest in 1976 and 1984, respectively. He received the candidat degree (equivalent to Ph.D.) from the Hungarian Academy in 1989. He habilitated at the University of Vienna in 1997. He received his professor title from the Hungarian President in 1999 and the Doctor of Academy degree (DSc) from the Hungarian Academy of Sciences in 2001. He has been a part-time full professor at the Cavendish School of Computer Science of the University of Westminster and the Eotvos Lorand University of Science Budapest since 2001. He has published two books, two lecture notes and more than 200 scientific papers on parallel computer architectures, parallel software engineering and Grid computing. He is the co-editor-in-chief of the Journal of Grid Computing published by Springer.
|
{"Source-Url": "https://users.iit.uni-miskolc.hu/~kecskemeti/publications/Shrinking-TPDS2012-KG-Web.pdf", "len_cl100k_base": 11902, "olmocr-version": "0.1.49", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 50231, "total-output-tokens": 13618, "length": "2e13", "weborganizer": {"__label__adult": 0.00030612945556640625, "__label__art_design": 0.0006279945373535156, "__label__crime_law": 0.00031828880310058594, "__label__education_jobs": 0.0026187896728515625, "__label__entertainment": 0.0001367330551147461, "__label__fashion_beauty": 0.00018990039825439453, "__label__finance_business": 0.0006299018859863281, "__label__food_dining": 0.0002982616424560547, "__label__games": 0.0007977485656738281, "__label__hardware": 0.0025157928466796875, "__label__health": 0.0005292892456054688, "__label__history": 0.000545501708984375, "__label__home_hobbies": 0.0001742839813232422, "__label__industrial": 0.0005812644958496094, "__label__literature": 0.0004391670227050781, "__label__politics": 0.0002651214599609375, "__label__religion": 0.0005102157592773438, "__label__science_tech": 0.27587890625, "__label__social_life": 0.0001494884490966797, "__label__software": 0.041900634765625, "__label__software_dev": 0.66943359375, "__label__sports_fitness": 0.0002079010009765625, "__label__transportation": 0.0005307197570800781, "__label__travel": 0.0002560615539550781}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63257, 0.02491]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63257, 0.23289]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63257, 0.88822]], "google_gemma-3-12b-it_contains_pii": [[0, 4730, false], [4730, 10931, null], [10931, 15993, null], [15993, 21859, null], [21859, 27983, null], [27983, 31880, null], [31880, 36869, null], [36869, 40855, null], [40855, 45220, null], [45220, 50267, null], [50267, 51373, null], [51373, 54380, null], [54380, 60692, null], [60692, 63257, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4730, true], [4730, 10931, null], [10931, 15993, null], [15993, 21859, null], [21859, 27983, null], [27983, 31880, null], [31880, 36869, null], [36869, 40855, null], [40855, 45220, null], [45220, 50267, null], [50267, 51373, null], [51373, 54380, null], [54380, 60692, null], [60692, 63257, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63257, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63257, null]], "pdf_page_numbers": [[0, 4730, 1], [4730, 10931, 2], [10931, 15993, 3], [15993, 21859, 4], [21859, 27983, 5], [27983, 31880, 6], [31880, 36869, 7], [36869, 40855, 8], [40855, 45220, 9], [45220, 50267, 10], [50267, 51373, 11], [51373, 54380, 12], [54380, 60692, 13], [60692, 63257, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63257, 0.05769]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
c6cb6542487574046c4a63808f513f79f3fff09d
|
Performance Analysis of GAME: A Generic Automated Marking Environment
Michael Blumenstein¹, Steve Green¹, Shoshana Fogelman², Ann Nguyen¹ and Vallipuram Muthukumarasamy¹
¹School of Information and Communication Technology, Griffith University, PMB 50 Gold Coast Mail Centre Bundall, QLD 9726 Australia
²School of Environmental and Applied Sciences, Griffith University, PMB 50 Gold Coast Mail Centre Bundall, QLD 9726 Australia
Abstract
This paper describes the Generic Automated Marking Environment (GAME) and provides a detailed analysis of its performance in assessing student programming projects and exercises. GAME has been designed to automatically assess programming assignments written in a variety of languages based on the "structure" of the source code and the correctness of the program's output. Currently, the system is able to mark programs written in Java, C++ and the C language. To use the system, instructors are required to provide a simple “marking schema” for each given assessment item, which includes pertinent information such as the location of files and the model solution. In this research, GAME has been tested on a number of student programming exercises and assignments and its performance has been compared against that of a human marker. An in-depth statistical analysis of the comparison is presented, providing encouraging results and directions for employing GAME as a tool for teaching and learning.
Keywords: architectures for educational technology system; post-secondary education; programming and programming languages; teaching/learning strategies
1. **Introduction**
Over the past few years, the development of tools for automatic assessment of computing programs has generated considerable interest. The desire to advance these learning tools has been in part prompted by the changing roles that are being ascribed to educators, as new learning paradigms are being adopted. An educator is no longer seen as a lecturer or supervisor, instead the role assumed is that of someone that can assist students in their ability to learn by providing an adequate learning environment, and very importantly by providing sufficient feedback on students’ work [1]. Although sufficient student feedback has been achievable in fairly small classes, this instruction methodology has been more difficult to apply to courses involving hundred of students, as well as courses undertaken through long distance education. Hence, automatic systems are being investigated not only to address student feedback issues, but also to improve the consistency, accuracy and efficiency of marking assessment items in large computer science courses [2]. This could allow educators to perform more efficiently by concentrating on tasks that cannot be automated, such as helping students grasp larger concepts and ideas.
Current automated marking systems are advancing in their ability to accurately mark students’ programming assessments, but there is still much research that must be undertaken to develop an accurate marker that can be used for small and large computer programs and can be accurately used over a range of programming languages and assessment items. Specifically, a single generic marking system is less costly to maintain and is more convenient to use than a number of smaller ones.
In an effort to address the challenge of marking large volumes of electronic assessment, a number of automated systems have been developed and tested [2]-[8]. Jackson and Usher [2] proposed a system called ASSYST that checks the correctness of an ADA program by analysing its output and comparing it to a correct specification using in-built tools of the UNIX operating system. Reek [3] details a system called TRY for grading students’ PASCAL computer programs by comparing the outputs of their program against a "model" output. Their system does not take into account style or design issues. Saikkonen et al [5] proposed a system called "Scheme-robo" for automatic assessment of scheme programs by analysing the return values of procedures and the structure of student code. English [7] has recently proposed a system for automated assessment of GUI-based Java programs using the JEWL library. Finally, Ghosh et al [8] developed a preliminary system for computer-program marking assistance and plagiarism detection (C-Marker). The system compiles and executes each student program and performs a simple comparison between the program's output and a model output file.
The main drawback of each of the systems mentioned above is that they were tested on one particular programming language. Although it was stated that some of the systems could be extended to operate on programs of other programming languages, an investigation was not conducted to determine the feasibility. Another deficiency inherent in some systems is their inability to deal with a wide variety of assessment items. In some cases the criteria for marking the correctness of student programs is hard-coded and requires the system to be updated regularly. This is a substantial limitation of these systems and needs to be addressed. Finally, many of the existing systems have been tested on small programs, whereas the challenge of marking larger pieces of software
has been essentially overlooked. In order to try and overcome the problems faced with current automated marking systems, GAME [9] was developed in SDK 1.4.1 and has emerged building on a previous system for marking C assignments [8] (C-Marker). It was designed to address the limitations of the C-Marker system and other existing systems. An overview of GAME is presented in Figure 1; it consists of four modules: structural analysis, program execution, output analysis, and plagiarism detection. The assignment is passed through a user interface to the GAME system and the results of marking are received as output through this interface. The first three modules have been developed and tested; the plagiarism module (adapted from C-Marker) is currently inactive, but will be further developed in future versions of the system.
The long-term goal for GAME is to make it accessible to students for marking/verifying their own assignments, as a student-centered tool for real-time feedback, as it is sometimes very difficult to obtain immediate feedback from educators. Its plagiarism detection unit should also make it easier for markers to identify similarities in assignments.
Based on the deficiencies of the early C-Marker system mentioned above, it was clear that the GAME system needed to address some major requirements. These may be summarized as: 1) The handling of different programming languages, 2) the handling of different assessment types, 3) the ability to implement different marking strategies to test the correct output of a variety of assessment items, 4) the handling of multiple source files and 5) the ability to accurately examine the structure of students' source code. In an earlier version, GAME addressed the first three of the five requirements mentioned above [9]. However, in order to make GAME a more robust marking system, two additional components were implemented: firstly, the ability of GAME to handle multiple source files, and secondly, the ability to accurately examine the structure of students’ source code (a preliminary discussion of these may be found in [10]). This has been achieved by assessing three different aspects of source code structure and presentation in students’ assignments. The source code structure is examined in terms of the number of comments in student code as compared to the number of lines of source code. GAME also performs an analysis of indentation practices and its consistency within the source code. Lastly, the programming style is marked by examining the students' approach to designing well-structured, reusable software. In each of the three sections, the student is awarded a percentage of the overall mark for each part. In its present form, GAME currently addresses all the above points in part or in full.
The following figure (Figure 2) provides a hierarchical representation of the GAME system presenting its composition and operation. The use of an adjustable marking scheme facilitates a weighted performance measure of a student's assignment based on each of the processes outlined in Figure 2. This information is summed and stored,
providing an overall result for each assessment item. GAME's performance has been evaluated on a large set of diverse programming assignments, and the results have been analysed in detail.
Figure 2 Hierarchical representation of the GAME system
2. Detailed Overview of GAME
2.1 Indentation
The analysis of indentation practices and their consistency within student source code is an important part of any programming assessment. Students need to understand the discipline of producing code that is maintainable and easy to read, both for themselves and other programmers. Indenting source code to an adopted standard provides the marker with a measure to examine a students’ source file for correctness, and most importantly consistency of indentation standards. At present, GAME assesses source
code indentation by examining strategic "key" points in the code. These points are at the beginning of functions, control statements, and global variables. At each key point where the source code is examined for correct indentation, a counter is incremented to record the total number of successful indentations (refer to Equation 1). Hence, indentation accuracy is determined by calculating the ratio of the successful indentations i.e. those that have the correct indentation size, to the number of tests performed at key points.
With this method, the GAME system only examines a percentage of the source code rather than every line. To assign indentation marks, the result obtained from GAME's analysis is compared to a set of indentation measures stipulated in the GAME schema file.
The indentation mark and size are specified in the marking schema (see Figure 3). In the example shown in Figure 3 it may be seen that the correct mark is worth three (3) and the correct indentation size is four white spaces. When examining a source file's indentation, the GAME system keeps a tally of the number of white spaces that should appear at any specific point in the source code. If a tab space is encountered, it is converted to the white space equivalent i.e. if the indentation size is four (4) a tab will be worth four (4) white spaces.
```markdown
@ indentation mark is made up of two parts
@ 1) the mark allocated for the source code indentation
@ 2) correct indentation size (number of white spaces)
#indentation_mark
3, 4
```
Figure 3 Illustrates a section of the marking scheme that specifies the indentation mark and indentation size.
Once all points have been examined, the average correct indentation is calculated.
The above procedure is carried out for each source file contained in a student’s assessment and is summed to form an overall correct indentation percentage (as defined in Equation 2).
\[ c = \frac{1}{n} \sum_{s=1}^{n} P_s \]
The final mark is then calculated by multiplying the correct indentation mark by the correct indentation percentage.
2.2 Commenting
Commenting standards are again a very important aspect of writing maintainable code. The methodology by which the amount and standard of commenting may be evaluated is a very fuzzy area; there are two main points to consider: 1) how many comments should be incorporated into the source code to aid in its understanding, and 2) what constitutes a good/useful comment. Currently, for the first point, GAME examines the number of comments in a student’s source code. For most common programming languages (some versions of C, C++, and Java) comments can be inline (the comment is on one single line) or they may be block comments, which span multiple lines. Again some of these areas are fuzzy, but it can be said that in most programming languages, a block comment is normally used for source file header information, function/method definitions, and anything else that requires a lengthy description. Inline comments are usually placed amongst code fragments and provide some insight into ambiguous lines of code. The second point has not been addressed in the GAME system, but is perceived to be an important step in future versions of GAME.
To calculate the commenting mark for a student’s assessment, the student source files are parsed to determine four values, 1) the number of lines of code (LOC), 2) the number of inline comments, 3) the number of block comments, and 4) the number of functions/methods. Once these values have been calculated, different metrics can be used to determine, or provide some measure of each source file’s commenting style. The LOC were calculated by counting the command lines in each source file, as opposed to counting each line. Counting the command lines in each source file provided a more accurate result when determining the source file commenting percentage.
One software metric, which relates to commenting for an entire source file, is the ratio of the number of comments (both inline and block) to LOC (see Equation 3). It was found through empirical analysis that a commenting percentage of 30% or greater provided a good indication of commenting in comparison to the number of LOC.
$$CommentingPercentage = \left( \frac{\text{NumOfComments}}{\text{LOC}} \right) \times 100$$ \hspace{1cm} (3)
A second metric, relating specifically to commenting for functions/methods, compares the number of block comments to the number of functions/methods in the source code. Good programming style would require that the student provides some description of each function in their source file. At present GAME does not verify that there is a relationship between a block comment and a function, simply the quantity of each. Marks for programming style are deducted if there are less block comments than functions. The area of evaluating programming style and structure is ongoing in the GAME system.
2.3 Programming Style
The programming style component of the source code structure mark concentrates on students' design, code reusability and maintainability. At present, the GAME system performs two operations with respect to programming style: 1) a comparison of the number of functions with the number of block comments (as described previously), and 2) a tally of the number of "magic" numbers (i.e. values hard-coded with no apparent meaning). Although GAME's functionality with respect to programming style is currently simplistic, it will be possible to extend this component with relative ease in future versions of the system.
2.4 Marking Schemas and Strategies in GAME
To be able to dynamically mark different types of programming assignments, the GAME system requires the assessor to complete a marking schema (see Figure 4). The marking schema at present is stored in a basic text format and will eventually be stored in an XML format, to ensure the correctness of parameters used for the marking schema. The marking schema currently contains information about assignment files, assignment marks, and marking criteria. The creation of a marking schema for an individual piece of assessment simplifies the use of the GAME system, as there is no need to deal with low-level details such as the method of input to the student's program (i.e. from standard input or from a file).
Currently, GAME allows the assessor to apply different marking strategies to test the result from a student’s program for correctness. The ability to apply different marking strategies to a variety of programming assessment is an important part of building a generic marking system and there is no single type of marking strategy for all types of assessment. At present there are two marking strategies: a "keyword" strategy that examines the student’s program output for a keyword at any position and an "ordered-keyword" strategy that looks for an ordered set of keywords in the student’s program output. Both strategies attempt to ignore irrelevant information by skipping those words that do not match the keyword (i.e. correct output).
2.5 Marking Multiple Programming Languages
Designing software that can only evaluate one programming language does not provide the user/marker with consistency between different programming courses. It is clear that regardless of what programming language is being taught, there is a common discipline that is required to be learnt. Students learning programming must strive to learn how to write robust and reusable code that can be understood by different programmers. To do this, the student must learn good coding design practices and standards that are expected in private industry. GAME at present is capable of marking three programming languages. Developing the implementations for other programming languages is readily achievable by extending the current model (see Figure 5) and will make GAME more robust, as a generic marking system.
From Figure 5 it may be seen that the base class “Marker” holds all the common behaviour that is required from the sub-class. In all cases, student source files are compiled, executed, and the source file examined for structure and programming style.
Each sub-class performs an inherited function in a slightly different way (polymorphic) i.e. to execute a student's program written in C a call to the ‘C’ compiler is required, whilst a Java program calls the “javac” command to compile a Java program. If a programming language does not have a compile stage i.e. Perl, an empty implementation would then be required. The empty implementation would be called but would not perform a task. All implementations of the Marker sub-class are Marker objects and therefore can be passed to a method by the base class. This means that the algorithm for marking a student’s source code is unaware of a particular implementation,
and simply calls the common behaviour in the Marker class. Java at run-time dynamically binds the correct object implementation to the method call.
The concept of designing a class that describes common behaviour for all sub-classes is the essence of designing a generic system to dynamically handle different conditions. When parsing a student’s source file, again when examining different languages, the same process is required, in that different aspects of the student source code are examined, and this is done in different ways for different language types. Figure 6 illustrates the base class `SourceCodeMarker` that holds all the common behaviour that is required for parsing a student’s source file for structure and programming style. All three sub-classes below are the required implementations for parsing a C, C++, or java source file. If GAME was extended to parse a Pascal source file, a new sub-class of `SourceCodeMarker` could be designed to handle Pascal source files.
---
Figure 5 Illustrates a class diagram of the GAME marker class with a sub-class for marking C, C++, and Java programs.
2.6 Multiple Source Files
Most programming assessments encourage their students to design their programs in a structured manner. This often requires students to develop more than one source file, in fact, most assessors would deduct marks from an assessment item if the entire student’s code was stored in a single source file. Whether designing a program in a procedural or object-oriented (OO) language, there is still a need to encourage students to structure their programs, and design meaningful source files. GAME is equipped to mark assessment items that have more than one source file. All the students’ source files are examined, and the processed information for each source file is stored in a list in the Student object that represents a particular student assessment (see Figure 7).
As each student’s source file is examined, it is inspected in two ways, 1) source file structure and 2) programming style. Each of these two components requires information to be stored about each student’s source file. When each of the student’s source files has been processed, the total mark for the student’s source file structure and programming style can be calculated. The source files’ structure and programming style is calculated by summing each of the source files’ marks and calculating an average mark for each section. In each section, structure and programming style, the marks are given as a percentage of the mark allocated in the marking schema. The results for each student are generated from the Results object (see Figure 6) stored in each Student object. The Results object combines source file information alone with compilation and execution information to produce the student's overall result for an assessment item. This information for each student can be generated in a brief outline of all results (see Figures 8 and 9), or a full breakdown for a particular student’s result.
Figure 8 Displays a brief breakdown of all the students’ results
2.7 The GAME GUI
The GAME GUI provides a straightforward interface to enable the user to mark different types of programming assessment (see Figure 9). In order to operate the system, the user is first required to select the root directory containing all student folders with their
programming assessment. The second requirement is the selection of an appropriate marking schema for the type of programming assessment being examined (see Section 2.4).
Once the above parameters have been entered, the user may then press the "Mark" button. When the students' programs have been marked, a summary of the students' results is displayed as a hypertext document within the system's main window. The summary includes a hypertext link to provide a detailed report of a particular assessment item.
In this study it was decided to investigate the capabilities and robustness of GAME on a number of real-world assessments to determine GAME's ability to mark different programming assignments and to evaluate the effectiveness of handling different programming languages, assessment items and multiple source files, as well as having the ability to use different marking strategies and the capacity to accurately examine the structure of source code. Its proficiency to mark is assessed by comparing results obtained with GAME to those obtained with a human marker.

3. Methods
To evaluate the capabilities, practical applicability and robustness of GAME in its present form, the system was used to mark a number of real-world programming assessment items. These involved different programming languages, different assessment items, multiple source files and different marking strategies. These experiments also focused attention on the structure of students' source code. The following section describes the methods employed to assess the assignment items and to evaluate the effectiveness of GAME.
3.1 Assessment Item Collection
GAME was evaluated on three different types of programming assessments, which were all command-line programs, two of the assessments were written in Java and one was written in C++. Java Test 1 was an in-class lab assessment obtained from a first year programming course. This assessment item involved only a small amount of coding, requiring a single source file. It was given to 3 different student groups, with a total of 98 assessment items being collected.
Java Test 2 was set in a more advanced OO analysis and design course. This assessment item was a "hand-in" assignment and involved a more complex programming structure requiring multiple (on average 7 to 8) source files. Students worked in groups of two or three. In total 23 assessment items were collected for Java Test 2.
The third assessment item used to evaluate GAME involved assignments from a first year C++ course. C++ Test 3 involved the students being provided with a partially
completed source file to base their design on. This skeleton included a command-line menu and header files. When examining the structure component of the students’ source code, the GAME system only examined the C++ files written by the student and did not consider the header files. In total, 13 assignments were collected and given to the GAME system for marking.
3.2 Marking of Assessment Items
Each assessment item was fed to the GAME system and marked in the following manner. Java Test 1, 2 and C++ Test 3 each were given three major marks, one for structure, the second for compilation and the third for execution. The structure mark was consistent for all three tests and was derived from three categories, commenting, indentation and style with a maximum score of 5 marks being awarded to each category for successful completion. For Java Test 1 the compile and execution marks were combined and given a total of 10 marks upon successful operation. Java Test 2 and C++ Test 3 were given a maximum mark of 5 for successful compilation and a maximum of 10 marks for successful execution.
3.3 Statistical Methodology
The ultimate aim of GAME is to be able to mark assignments and to produce very similar results to those manually obtained by a human (commonly referred to as the 'Human Marker' in this research). In order to evaluate how well GAME performs, a correlation analysis was used to compare commenting, indentation, style, compilation and execution marks to those obtained by the Human Marker. A Pearson’s linear correlation coefficient (r) [10] was used to measure the strength of association between the two sets of marks (one obtained by GAME and the other by the Human Marker), with r being 1.
indicating a perfect correlation and 0 indicating no association. The significance level was set to 5%, so that if $p < 0.05$, the correlation would be found to be statistically significant, where as if $p > 0.05$ the correlation would be found not to be statistically significant. However, if there was not a sufficient linear range to use a Pearson’s Linear Correlation, then a sign test was used to determine whether the marks obtained by GAME match the Human Marker. This is based on a binomial distribution.
4. Results
The number of assessment items correctly marked by GAME is shown in Table 1 for Java Test 1 and Table 2 for Java Test 2 and for C++ Test 3. Table 3 shows the statistical results obtained for Java Test 1, Java Test 2 and C++ Test 3. Table 3 shows the test number, number of trials, total number of assignments, and correlation and p-values of results obtained from the GAME and Human Marker methods.
<table>
<thead>
<tr>
<th>Table 1</th>
<th>Results of assignments marked by the GAME system that agreed 100% with the Human Marker for Java Test 1, trials 1, 2 and 3 combined.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Trial</td>
<td>Total Number Students</td>
</tr>
<tr>
<td>1</td>
<td>33</td>
</tr>
<tr>
<td>2</td>
<td>38</td>
</tr>
<tr>
<td>3</td>
<td>27</td>
</tr>
<tr>
<td>Total</td>
<td>98</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Table 2</th>
<th>Results of assignments marked by the GAME system that agree 100 % with the Human Marker for Java Test 2 and C++ Test 3.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Trial</td>
<td>Total Number Students</td>
</tr>
<tr>
<td>Java Test 2</td>
<td>21</td>
</tr>
<tr>
<td>C++ Test 3</td>
<td>13</td>
</tr>
</tbody>
</table>
Table 3 Statistical results obtained for Java Test 1, Java Test 2 and C++ Test 3
<table>
<thead>
<tr>
<th>Test</th>
<th>Total number of assignments marked</th>
<th>Structure Mark</th>
<th>Compiles/ executes Correctly</th>
<th>Compiles Correctly</th>
<th>Executes Correctly</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>Commenting</td>
<td>Indentation</td>
<td>Style</td>
<td></td>
</tr>
<tr>
<td>Java Test 1</td>
<td>33</td>
<td>0.85 (p = 0.000)</td>
<td>0.85 (p = 0.000)</td>
<td>* p = 0.000, n = 33</td>
<td>0.90 (p = 0.000)</td>
</tr>
<tr>
<td>Trial 1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Java Test 1</td>
<td>38</td>
<td>0.43 (p = 0.007)</td>
<td>0.93 (p = 0.000)</td>
<td>* p = 0.003, n = 38</td>
<td>0.94 (p = 0.000)</td>
</tr>
<tr>
<td>Trial 2</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Java Test 1</td>
<td>27</td>
<td>0.44 (p = 0.02)</td>
<td>1.00 (p = n/a)</td>
<td>* p = 0.013, n = 27</td>
<td>0.94 (p = 0.000)</td>
</tr>
<tr>
<td>Trial 3</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Java Test 2</td>
<td>21</td>
<td>0.97 (p = 0.000)</td>
<td>1.00 (p = n/a)</td>
<td>0.64 (p = 0.002)</td>
<td>N/A</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>C++ Test 3</td>
<td>13</td>
<td>0.93 (p = 0.000)</td>
<td>0.49 (p = 0.088)</td>
<td>1.00 (p = 0.000)</td>
<td>N/A</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
* Indicates when a sign test was used due to a limited linear distribution
5. Analysis and Discussion
5.1 Java Test 1
Table 1 shows the first type of assessment item marked by GAME; a total of 98 assessment items were presented to the system. It can be seen from this table that GAME produced marks for Indentation, Style and Compile/Execution, which agreed 100% with the Human Marker in a high proportion of cases, although not as frequently as for Indentation. For Indentation these two sets of marks (i.e. GAME and the Human Marker respectively) were nearly identical in 90% or more of the cases: 91% in Trial 1, 90% in Trial 2 and 100% in Trial 3. However for Style and Compile/Execution the two sets of marks agreed around 80% of the cases. The statistical results shown in Table 3 also confirmed this observation. For Indentation and Compile/Execution a correlation coefficient (r) of greater than 0.85 was found. In all cases it was found that the correlations with the Human Marker were significant, as p < 0.05, indicating there was a
very close association between marks given by the GAME system and the Human Marker for Indentation and Compile/Execution of students’ code.
For analysing Style, a Sign Test was used to determine whether the marks obtained by GAME matched the Human Marker. This was because the marking range was very narrow (in most cases a mark of 0 or 1.5 was given out of 5) and hence it was not possible to analyse the results using a Pearson’s Linear Correlation. The statistical results shown in Table 3 indicated that two sets of marks matched significantly as a $p<0.05$ in all cases for marking the Style of the students’ code.
The marks for “Commenting” from GAME and the Human Marker agree in fewer instances than for “indentation”, “style” and “compile/execute”: 79% for Trial 1, 66% for Trial 2 and 48% for Trial 3 (Table 1). While these are sufficient to produce significant correlation coefficients for all trials (Table 3), these discrepancies prompted further investigation. Upon closer inspection of the raw data, it becomes clear that in cases where there are differences with regard to “commenting”, GAME tends to award higher marks than the Human Marker. This can be explained largely by the fact that the GAME system, as it stands, is not yet able to distinguish what constitutes a “good” comment. In some cases the “comments” are in superseded code fragments that have been “commented out”, so that they do not compile and as such they have no documentation value. In future, the GAME system can be improved by teaching GAME to distinguish what constitutes a “good” comment.
Closer examination of the raw data also helped to gain some understanding of the deficiencies of GAME in its present form. For example, with regards to compilation and execution, it was found that human error played a major part in the 19.4% of
discrepancies between GAME and the Human Marker. Out of the 19 assessments where conflict arose, 7 were related to Human Error. This underscores the obvious, but still noteworthy point that while human markers are the model for the automated marking system, they are by no means free from errors. The remaining 12 assessment items differed from GAME because the Human Marker quite often gave part marks for the student’s effort. To overcome this problem in future, some additional strategies could be introduced into the GAME system to provide it with the ability to award part marks. Overall, GAME was able to mark this simple assignment (containing one source file) quite well with respect to indentation, style and compilation/execution, as the marks were very closely related to the Human Marker. It was found to have a lower performance in marking commenting practice, by tending to give higher marks than the Human Marker. Further research is required to design more advanced marking strategies to improve these results.
5.2 Java Test 2
In Java Test 2, GAME was tested on a more difficult assignment that involves between 7 or 8 source files. Students were required to implement a command-line program with a specific number of menu choices. Only 21 out of the 23 assignments could be marked by GAME. In both of the remaining cases, the problem was due to the students altering the assessment criteria, by implementing different command-line menu structures to the one specified in the assessment guidelines.
From Table 2, in regards to indentation and compilation, it can be seen that GAME agreed 100% with the Human Marker, for all 21 of the assessment items marked. There was also nearly complete agreement between GAME and the Human Marker for
commenting and style, with respectively 19 (91%) and 17 (81%) of the assessments items correctly being marked. Closer inspection of assignments where GAME and the Human Marker did not agree with regards to style, revealed that where the Human Marker gave a mark of 2.5 out of 5, GAME tended to award a mark of 0. This indicated a lack of ability of GAME to award part marks, which was a commonly observed trait of the Human Marker. However, GAME did not perform well at marking the execution part of the assignment for JAVA Test 2, with only 12 (57%) of assignments agreeing with the Human Marker.
Statistical results in Table 3, validate the results discussed above. In all cases except style, GAME seemed to mark very closely to the Human Marker as a statistically significant correlation \( r \) of greater than 0.97 \( (p = 0.000) \) was obtained for commenting, indentation and compilation and an \( r \) of 0.79 \( (p = 0.000) \) for execution. Even with multiple source files, GAME seemed to perform very well at automated marking. The only problem encountered with GAME in JAVA Test 2 was style, attributed to the fact that the Human Marker awarded part marks.
For the 5 assessment items that disagreed with Human Marker for source code structure, one was for the commenting section and one was for the commenting and programming style sections. The Human Marker in both instances gave fewer marks for the commenting section due to the presence of some irrelevant comments in the student’s code. The remaining three assessments that GAME disagreed with the Human Marker were for programming style, where the Human Marker assigned more marks than the GAME system.
For execution correctness, it was found that for the nine assessments that disagreed with the Human Marker, five were due to the students changing the nature of their assignment through alteration of either the menu structure or the order in which data was prompted for. For the other four assessments, the difference was attributed to the fact that the Human Marker gave part marks for the students' effort. This suggests that the discrepancies are not serious, in that more elaborate marking guides, some additional 'intelligent' component added to award part marks, would substantially increase the effectiveness of the GAME system.
Overall, the results suggest that GAME is sufficiently robust to handle multiple assignments with multiple, as well as single source files and different marking strategies.
5.3 C++ Test 3
The third major experiment devised to test GAME involved assignments from a first year C++ course. It was used to evaluate GAME’s ability to mark other programming languages. A total of 14 students’ assessments were fed to GAME, of which only 13 could be marked. The single case that could not be automatically marked, used code that disabled GAME’s ability to pass the required input stream to the student’s program.
The results in Table 2 revealed that GAME performed extremely well at marking the sections of commenting, style and compilation, as 100% of assignments marked by GAME agreed with the Human Marker. The statistical analyses (Table 3) also indicated the effectiveness of GAME as an automated marking method. For these sections, GAME was highly correlated with the Human Marker, as extremely statistically significant correlations of 1 (p = 0.000) were found. However, unlike Java Test 1 and 2 it seemed that GAME had difficulty marking indentation, as only 7 (53.8%) of assignments
agreed with the Human Marker. Statistical results (Table 3) validated this, as r was 0.49 ($p = 0.088$) indicating the correlation was poor and insignificant. One explanation for this result is that the multi-source file C++ assignments included some poorly formatted code from the instructor, which affected GAME's performance in this instance.
The ability for GAME to mark the execution of the assignment was also poor, this time only 4 (30.7%) of assignments agreed with the Human Marker. Statistical results (Table 3) showed the marks obtained by GAME in the execution section were not highly correlated with the Human Marker and were extremely insignificant with r being 0.18 ($p = 0.546$). From the raw data, this poor correlation seemed to be attributed to the fact that in all cases, the Human Marker awarded 5 out 5 for execution, whereas GAME seemed to mostly always award zero. The low mark awarded by the GAME system could be tracked down to the fact that students compiled their projects in Visual C++, whereas, GAME used the command line compiler included in Visual C++. The command line compiler did not give global values an initial value (i.e. did not set a global integer variable to zero). This caused the large majority of assessment items to not execute properly, and therefore obtain a zero mark.
For C++ Test 3, the GAME system seemed to perform well at marking assignments written in a different programming language. Since GAME worked very well at marking indentation in Java Tests 1 and 2, the problems in C++ Test 3 were attributed to formatting problems with the instructor's code. The poor correlation between marks obtained by GAME and the Human Marker for execution, emphasizes that the GAME system must compile and execute students' source code in the same environment that the students work in to give consistent results.
6. Conclusions and Future Work
This paper presented an experimental analysis of GAME, an automatic system for marking programming assessment items, in university-level courses. The generic design of the system makes it a versatile tool for marking different types of assessment items. Overall, the results obtained from the experiments conducted suggest that the GAME system is very promising for use in a real-world teaching environment. It can handle submissions in different programming languages, which comprise of single or multiple source files. GAME also has the ability to accept and implement different marking strategies. Potentially, the advantages of employing an automated marking system like GAME are evident in terms of student-centered learning (ample and timely feedback) and objective, transparent mark allocation.
In analysing the experimental results, some interesting outcomes were found that might assist future research in this area. For example, in marking the correctness of a program's execution through an automated system like GAME, measures will need to be put in place for dealing with programs whose operations have diverged from those specified in the assignment sheet. This issue is being addressed in a web-based version of GAME (currently in development to investigate its role in facilitating student-centered learning) that will automatically reject assignments, which do not meet specifications. The students involved are thus given an early warning to modify their assignments to conform to the required specifications. Also, procedures for allocating part marks for a student's effort may need to be explored via the use of intelligent techniques. Finally, further marking strategies will be added to the system to deal with issues relating to the variety of output obtained from students' programs.
In its current form, GAME is a tool that is still being fine-tuned and used mainly for research and investigation only. As such, it is not yet available in the public domain. However, the authors' intention is that, once research is complete, GAME will be made publicly and freely available on the Internet.
7. Acknowledgments
The authors wish to thank the anonymous referees for a number of helpful comments, but retain full responsibility for any shortcomings, which may remain. This work was supported by Griffith University as part of its Teaching Grant scheme.
8. References
|
{"Source-Url": "https://research-repository.griffith.edu.au/bitstream/handle/10072/23533/54430_1.pdf?sequence=1", "len_cl100k_base": 8624, "olmocr-version": "0.1.50", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 46973, "total-output-tokens": 10527, "length": "2e13", "weborganizer": {"__label__adult": 0.000766754150390625, "__label__art_design": 0.0010280609130859375, "__label__crime_law": 0.0008897781372070312, "__label__education_jobs": 0.11865234375, "__label__entertainment": 0.0001906156539916992, "__label__fashion_beauty": 0.00043129920959472656, "__label__finance_business": 0.0006489753723144531, "__label__food_dining": 0.0010499954223632812, "__label__games": 0.0020294189453125, "__label__hardware": 0.0019626617431640625, "__label__health": 0.0009069442749023438, "__label__history": 0.0006937980651855469, "__label__home_hobbies": 0.0003287792205810547, "__label__industrial": 0.0009984970092773438, "__label__literature": 0.0008478164672851562, "__label__politics": 0.0006818771362304688, "__label__religion": 0.00113677978515625, "__label__science_tech": 0.01971435546875, "__label__social_life": 0.0004012584686279297, "__label__software": 0.0105743408203125, "__label__software_dev": 0.83349609375, "__label__sports_fitness": 0.0008697509765625, "__label__transportation": 0.0014562606811523438, "__label__travel": 0.0004878044128417969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44524, 0.04734]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44524, 0.67547]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44524, 0.9444]], "google_gemma-3-12b-it_contains_pii": [[0, 1596, false], [1596, 3321, null], [3321, 5260, null], [5260, 6440, null], [6440, 8384, null], [8384, 9184, null], [9184, 10915, null], [10915, 12420, null], [12420, 14116, null], [14116, 15510, null], [15510, 16251, null], [16251, 18021, null], [18021, 19134, null], [19134, 19931, null], [19931, 21386, null], [21386, 22506, null], [22506, 24026, null], [24026, 25743, null], [25743, 27848, null], [27848, 30827, null], [30827, 32656, null], [32656, 34413, null], [34413, 36086, null], [36086, 37912, null], [37912, 39769, null], [39769, 41611, null], [41611, 44524, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1596, true], [1596, 3321, null], [3321, 5260, null], [5260, 6440, null], [6440, 8384, null], [8384, 9184, null], [9184, 10915, null], [10915, 12420, null], [12420, 14116, null], [14116, 15510, null], [15510, 16251, null], [16251, 18021, null], [18021, 19134, null], [19134, 19931, null], [19931, 21386, null], [21386, 22506, null], [22506, 24026, null], [24026, 25743, null], [25743, 27848, null], [27848, 30827, null], [30827, 32656, null], [32656, 34413, null], [34413, 36086, null], [36086, 37912, null], [37912, 39769, null], [39769, 41611, null], [41611, 44524, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44524, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44524, null]], "pdf_page_numbers": [[0, 1596, 1], [1596, 3321, 2], [3321, 5260, 3], [5260, 6440, 4], [6440, 8384, 5], [8384, 9184, 6], [9184, 10915, 7], [10915, 12420, 8], [12420, 14116, 9], [14116, 15510, 10], [15510, 16251, 11], [16251, 18021, 12], [18021, 19134, 13], [19134, 19931, 14], [19931, 21386, 15], [21386, 22506, 16], [22506, 24026, 17], [24026, 25743, 18], [25743, 27848, 19], [27848, 30827, 20], [30827, 32656, 21], [32656, 34413, 22], [34413, 36086, 23], [36086, 37912, 24], [37912, 39769, 25], [39769, 41611, 26], [41611, 44524, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44524, 0.17123]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.